"use client";

import { useCallback, useEffect, useState } from "react";
import Link from "next/link";
import { FileText, Filter, Plus, Search } from "lucide-react";
import { motion } from "framer-motion";
import Button from "@/components/ui/Button";
import Input from "@/components/ui/Input";
import { listPresupuestos } from "@/lib/pb/presupuestos";
import {
  ESTADO_PRESUPUESTO_LABELS,
  PRESUPUESTO_CIERRE_LABELS,
  type EstadoPresupuesto,
  type Presupuesto,
} from "@/lib/types/presupuesto";
import { dateShort, money } from "@/lib/format";

export default function PresupuestosPage() {
  const [items, setItems] = useState<Presupuesto[]>([]);
  const [estado, setEstado] = useState<EstadoPresupuesto | "todos">("todos");
  const [search, setSearch] = useState("");
  const [loading, setLoading] = useState(true);
  const [err, setErr] = useState("");

  const reload = useCallback(async () => {
    setLoading(true);
    setErr("");
    try {
      const res = await listPresupuestos({ estado, search });
      setItems(res.items);
    } catch (e) {
      setErr((e as Error).message || "No se pudieron cargar presupuestos");
    } finally {
      setLoading(false);
    }
  }, [estado, search]);

  useEffect(() => {
    const t = setTimeout(reload, search ? 250 : 0);
    return () => clearTimeout(t);
  }, [reload, search]);

  return (
    <div className="max-w-7xl">
      <div className="mb-6 flex items-center justify-between gap-4">
        <div>
          <h1 className="text-2xl font-extrabold text-ink">Presupuestos</h1>
          <p className="mt-0.5 text-sm text-ink-soft">
            {items.length} {items.length === 1 ? "presupuesto" : "presupuestos"}
          </p>
        </div>
        <Link href="/presupuestos/nuevo">
          <Button size="lg">
            <Plus size={18} /> Nuevo presupuesto
          </Button>
        </Link>
      </div>

      <div className="card mb-4 flex flex-col gap-3 p-4 md:flex-row md:items-end">
        <div className="min-w-0 flex-1">
          <Input
            label="Buscar"
            placeholder="Codigo, cliente o celular"
            prefix={<Search size={16} />}
            value={search}
            onChange={(e) => setSearch(e.target.value)}
          />
        </div>
        <label className="flex flex-col gap-1.5">
          <span className="text-sm font-medium text-ink-soft">Estado</span>
          <div className="flex h-11 items-center gap-2 rounded-xl border border-line bg-surface px-3">
            <Filter size={16} className="text-faint" />
            <select
              value={estado}
              onChange={(e) => setEstado(e.target.value as EstadoPresupuesto | "todos")}
              className="min-w-36 bg-transparent text-ink outline-none"
            >
              <option value="todos">Todos</option>
              {Object.entries(ESTADO_PRESUPUESTO_LABELS).map(([value, label]) => (
                <option key={value} value={value}>{label}</option>
              ))}
            </select>
          </div>
        </label>
      </div>

      <div className="card overflow-hidden">
        {err && <div className="border-b border-line bg-red-50 px-4 py-2 text-sm text-bad">{err}</div>}
        {loading ? (
          <div className="p-10 text-center text-sm text-faint">Cargando...</div>
        ) : items.length === 0 ? (
          <div className="p-16 text-center">
            <FileText size={32} className="mx-auto mb-3 text-faint" />
            <p className="mb-4 text-ink-soft">No hay presupuestos cargados.</p>
            <Link href="/presupuestos/nuevo">
              <Button><Plus size={16} /> Crear presupuesto</Button>
            </Link>
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead>
                <tr className="border-b border-line bg-canvas/50 text-left">
                  <Th>Codigo</Th>
                  <Th>Cliente</Th>
                  <Th>Fecha</Th>
                  <Th>Estado</Th>
                  <Th className="text-right">Total</Th>
                  <Th className="text-right">Saldo</Th>
                  <Th>Pedido</Th>
                </tr>
              </thead>
              <tbody>
                {items.map((p, i) => (
                  <motion.tr
                    key={p.id}
                    initial={{ opacity: 0, y: 4 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ delay: i * 0.015 }}
                    className="cursor-pointer border-b border-line/60 last:border-b-0 hover:bg-canvas/50"
                    onClick={() => { window.location.href = `/presupuestos/${p.id}`; }}
                  >
                    <Td><span className="font-bold text-ink">{p.codigo || "-"}</span></Td>
                    <Td>
                      <div className="font-medium text-ink">{p.expand?.cliente?.nombre || "-"}</div>
                      <div className="text-xs text-faint">{p.expand?.cliente?.celular || ""}</div>
                    </Td>
                    <Td className="text-sm text-ink-soft">{dateShort(p.fecha || p.created)}</Td>
                    <Td>
                      <EstadoBadge estado={p.estado} />
                      {p.cierre_motivo && (
                        <div className="mt-1 text-xs text-faint">{PRESUPUESTO_CIERRE_LABELS[p.cierre_motivo]}</div>
                      )}
                    </Td>
                    <Td className="text-right font-medium tabular-nums">{money(p.total)}</Td>
                    <Td className={`text-right font-semibold tabular-nums ${p.saldo > 0 ? "text-bad" : "text-good"}`}>
                      {money(p.saldo)}
                    </Td>
                    <Td className="text-sm text-ink-soft">{p.pedido ? "Convertido" : "-"}</Td>
                  </motion.tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
}

function EstadoBadge({ estado }: { estado: EstadoPresupuesto }) {
  const cls = estado === "aprobado"
    ? "bg-green-100 text-green-700"
    : estado === "rechazado" || estado === "cancelado"
      ? "bg-red-100 text-red-700"
      : estado === "sin_respuesta"
        ? "bg-zinc-200 text-zinc-700"
      : estado === "enviado"
        ? "bg-blue-100 text-blue-700"
        : "bg-amber-100 text-amber-700";
  return (
    <span className={`rounded-full px-2 py-1 text-xs font-bold ${cls}`}>
      {ESTADO_PRESUPUESTO_LABELS[estado]}
    </span>
  );
}

function Th({ children, className }: { children: React.ReactNode; className?: string }) {
  return <th className={`px-3 py-2.5 text-[11px] font-bold uppercase tracking-wider text-faint ${className || ""}`}>{children}</th>;
}

function Td({ children, className }: { children: React.ReactNode; className?: string }) {
  return <td className={`px-3 py-3 ${className || ""}`}>{children}</td>;
}
