import { useState } from 'react';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { bsDesdeUsd, formatBs, type Restaurante } from '@gustito/shared';
import { supabase } from '../lib/supabase';

type Gasto = { id: string; concepto: string; monto_usd: number; creado_en: string };

const usd = (n: number) => `$${n.toFixed(2)}`;

export default function Caja({ restaurante, marca, txtMarca }: { restaurante: Restaurante; marca: string; txtMarca: string }) {
  const qc = useQueryClient();
  const [concepto, setConcepto] = useState('');
  const [monto, setMonto] = useState('');
  const [guardando, setGuardando] = useState(false);
  const [err, setErr] = useState<string | null>(null);

  const inicioHoy = new Date();
  inicioHoy.setHours(0, 0, 0, 0);

  const { data: gastos } = useQuery({
    queryKey: ['gastos-caja', restaurante.id],
    queryFn: async () => {
      const { data } = await supabase
        .from('gastos_caja')
        .select('id,concepto,monto_usd,creado_en')
        .eq('restaurante_id', restaurante.id)
        .eq('archivado', false)
        .order('creado_en', { ascending: false });
      return (data ?? []) as unknown as Gasto[];
    },
  });

  const { data: ingresos } = useQuery({
    queryKey: ['ventas-hoy', restaurante.id],
    refetchInterval: 30000,
    queryFn: async () => {
      const { data } = await supabase
        .from('pedidos')
        .select('total_usd')
        .eq('restaurante_id', restaurante.id)
        .eq('estado', 'entregado')
        .gte('recibido_en', inicioHoy.toISOString());
      const rows = (data ?? []) as { total_usd: number | null }[];
      return rows.reduce((s, r) => s + Number(r.total_usd ?? 0), 0);
    },
  });

  const totalGastos = (gastos ?? []).reduce((s, g) => s + Number(g.monto_usd), 0);
  const ventas = ingresos ?? 0;
  const neto = ventas - totalGastos;
  const tasa = restaurante.tasa_bs;
  const bsTxt = (n: number) => (tasa && tasa > 0 ? formatBs(bsDesdeUsd(n, tasa)) : null);

  async function agregar() {
    const m = parseFloat(monto.replace(',', '.'));
    if (!concepto.trim() || !(m >= 0) || Number.isNaN(m)) {
      setErr('Pon un concepto y un monto válido.');
      return;
    }
    setErr(null);
    setGuardando(true);
    const { data: sess } = await supabase.auth.getUser();
    const { error } = await supabase.from('gastos_caja').insert({
      restaurante_id: restaurante.id,
      concepto: concepto.trim(),
      monto_usd: m,
      registrado_por: sess.user?.id ?? null,
    });
    setGuardando(false);
    if (error) {
      setErr(error.message);
      return;
    }
    setConcepto('');
    setMonto('');
    qc.invalidateQueries({ queryKey: ['gastos-caja', restaurante.id] });
  }

  async function borrar(id: string) {
    await supabase.from('gastos_caja').delete().eq('id', id);
    qc.invalidateQueries({ queryKey: ['gastos-caja', restaurante.id] });
  }

  return (
    <div className="space-y-5">
      <h1 className="text-xl font-extrabold">Caja del día</h1>

      {/* Ingresos / Gastos / Neto */}
      <div className="grid grid-cols-3 gap-2 sm:gap-3">
        <ResumenCaja label="Ingresos" valor={usd(ventas)} bs={bsTxt(ventas)} color="#22C55E" nota="Ventas entregadas hoy" />
        <ResumenCaja label="Gastos" valor={usd(totalGastos)} bs={bsTxt(totalGastos)} color="#EF4444" nota="Egresos del día" />
        <ResumenCaja label="Neto" valor={usd(neto)} bs={bsTxt(neto)} color={neto < 0 ? '#EF4444' : '#22C55E'} nota="Ingresos menos gastos" />
      </div>

      {/* Registrar gasto */}
      <section className="rounded-2xl bg-superficie p-4 ring-1 ring-white/10">
        <h2 className="mb-3 text-sm font-extrabold uppercase tracking-wide text-niebla">Registrar gasto</h2>
        <div className="flex flex-col gap-2 sm:flex-row">
          <input
            className="flex-1 rounded-xl border border-white/10 bg-superficie-2 px-3.5 py-2.5 text-sm text-white placeholder:text-white/40 outline-none focus:border-white/25"
            placeholder="Concepto (ej: compra de harina)"
            value={concepto}
            onChange={(e) => setConcepto(e.target.value)}
          />
          <input
            className="rounded-xl border border-white/10 bg-superficie-2 px-3.5 py-2.5 text-sm text-white placeholder:text-white/40 outline-none focus:border-white/25 sm:w-32"
            placeholder="Monto $"
            inputMode="decimal"
            value={monto}
            onChange={(e) => setMonto(e.target.value)}
            onKeyDown={(e) => e.key === 'Enter' && agregar()}
          />
          <button
            onClick={agregar}
            disabled={guardando}
            className="rounded-xl px-4 py-2.5 text-sm font-bold disabled:opacity-60"
            style={{ background: marca, color: txtMarca }}
          >
            {guardando ? '...' : 'Agregar'}
          </button>
        </div>
        {err && <p className="mt-2 text-sm text-red-400">{err}</p>}
      </section>

      {/* Lista de gastos */}
      <section>
        <div className="mb-2 flex items-center justify-between">
          <h2 className="text-sm font-extrabold uppercase tracking-wide text-niebla">Gastos de hoy</h2>
          <span className="text-sm font-bold text-red-400">{usd(totalGastos)}</span>
        </div>
        {(gastos ?? []).length === 0 ? (
          <p className="rounded-2xl border border-dashed border-white/15 bg-superficie p-6 text-center text-sm text-niebla">
            Sin gastos registrados hoy.
          </p>
        ) : (
          <div className="divide-y divide-white/10 overflow-hidden rounded-2xl bg-superficie ring-1 ring-white/10">
            {(gastos ?? []).map((g) => (
              <div key={g.id} className="flex items-center justify-between gap-3 px-4 py-3">
                <div className="min-w-0">
                  <p className="truncate font-semibold">{g.concepto}</p>
                  <p className="text-xs text-niebla">
                    {new Date(g.creado_en).toLocaleTimeString('es-VE', { hour: '2-digit', minute: '2-digit' })}
                  </p>
                </div>
                <div className="flex items-center gap-3">
                  <span className="font-bold text-red-400">{usd(Number(g.monto_usd))}</span>
                  <button onClick={() => borrar(g.id)} className="text-xs font-semibold text-niebla hover:text-red-400">
                    Borrar
                  </button>
                </div>
              </div>
            ))}
          </div>
        )}
      </section>
    </div>
  );
}

function ResumenCaja({
  label,
  valor,
  bs,
  color,
  nota,
}: {
  label: string;
  valor: string;
  bs?: string | null;
  color: string;
  nota: string;
}) {
  return (
    <div className="rounded-2xl bg-superficie p-3 text-center ring-1 ring-white/10 sm:p-4">
      <p className="text-xs font-semibold uppercase tracking-wide text-niebla">{label}</p>
      <p className="mt-1 text-xl font-black tabular-nums sm:text-2xl" style={{ color }}>
        {valor}
      </p>
      {bs && <p className="text-[11px] font-semibold tabular-nums text-niebla">{bs}</p>}
      <p className="mt-0.5 text-[11px] text-niebla">{nota}</p>
    </div>
  );
}
