"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { ArrowLeft, Banknote, MapPin, Phone, Save, Search, User, Users } from "lucide-react";
import { motion } from "framer-motion";
import Button from "@/components/ui/Button";
import Input from "@/components/ui/Input";
import CommercialItemsEditor from "@/components/presupuestos/CommercialItemsEditor";
import CortesEditor from "@/components/cortes/CortesEditor";
import { listClientes } from "@/lib/pb/clientes";
import { listCuentas } from "@/lib/pb/cuentas";
import { createPedidoRapido } from "@/lib/pb/pedido-rapido";
import { todayIsoDate } from "@/lib/pb/pagos";
import { summarizeCommercialItems } from "@/lib/presupuestos/domain";
import { emptyCorteDraft } from "@/lib/cortes/drafts";
import { useUnsavedChangesGuard } from "@/lib/useUnsavedChangesGuard";
import type { Cliente } from "@/lib/types/pedido";
import type { PresupuestoItemDraft } from "@/lib/types/presupuesto";
import type { CorteItemDraft } from "@/lib/cortes/types";
import type { Cuenta } from "@/lib/types/pago";
import { money } from "@/lib/format";

export default function PedidoRapidoPage() {
  const router = useRouter();
  const [clienteMode, setClienteMode] = useState<"existente" | "nuevo">("existente");
  const [clienteSearch, setClienteSearch] = useState("");
  const [clientes, setClientes] = useState<Cliente[]>([]);
  const [selectedCliente, setSelectedCliente] = useState<Cliente | null>(null);
  const [nombre, setNombre] = useState("");
  const [celular, setCelular] = useState("");
  const [direccion, setDireccion] = useState("");
  const [descripcion, setDescripcion] = useState("");
  const [items, setItems] = useState<PresupuestoItemDraft[]>([]);
  const [cortes, setCortes] = useState<CorteItemDraft[]>([]);
  const [cuentas, setCuentas] = useState<Cuenta[]>([]);
  const [pagoMonto, setPagoMonto] = useState("");
  const [pagoCuenta, setPagoCuenta] = useState("");
  const [pagoFecha, setPagoFecha] = useState(todayIsoDate());
  const [pagoNota, setPagoNota] = useState("Pedido rápido");
  const [saving, setSaving] = useState(false);
  const [err, setErr] = useState("");

  const total = summarizeCommercialItems(items).total;
  const hasUnsavedChanges = Boolean(
    selectedCliente || clienteSearch.trim() || nombre.trim() || celular.trim() || direccion.trim() ||
      descripcion.trim() || items.length || cortes.length || pagoMonto.trim(),
  );

  async function handleSaveOnly() {
    if (clienteMode === "existente" && !selectedCliente) {
      throw new Error("Elegí un cliente o cargá uno nuevo.");
    }
    if (clienteMode === "nuevo" && !nombre.trim()) {
      throw new Error("Falta el nombre del cliente.");
    }
    if (total <= 0) {
      throw new Error("Cargá al menos una línea con precio.");
    }
    const pedido = await createPedidoRapido({
      cliente: {
        id: selectedCliente?.id,
        nombre: selectedCliente?.nombre || nombre.trim(),
        celular: selectedCliente?.celular || celular.trim() || undefined,
        direccion: selectedCliente?.direccion || direccion.trim() || undefined,
      },
      descripcion: descripcion.trim() || "Pedido rápido",
      items,
      cortes,
      pago: Number(pagoMonto) > 0 ? {
        monto: Number(pagoMonto),
        cuenta: pagoCuenta,
        fecha: pagoFecha,
        nota: pagoNota.trim() || "Pedido rápido",
      } : undefined,
    });
    return pedido;
  }

  useUnsavedChangesGuard(hasUnsavedChanges && !saving, async () => {
    const pedido = await handleSaveOnly();
    return !!pedido;
  });

  useEffect(() => {
    if (clienteMode !== "existente") return;
    const t = setTimeout(async () => {
      try {
        const res = await listClientes(clienteSearch, 60);
        setClientes(res.items);
      } catch {
        setClientes([]);
      }
    }, clienteSearch ? 250 : 0);
    return () => clearTimeout(t);
  }, [clienteMode, clienteSearch]);

  useEffect(() => {
    (async () => {
      const list = await listCuentas();
      setCuentas(list);
      setPagoCuenta((current) => current || list[0]?.id || "");
    })();
  }, []);


  async function submit(e: React.FormEvent) {
    e.preventDefault();
    setErr("");
    setSaving(true);
    try {
      const pedido = await handleSaveOnly();
      router.replace(`/pedidos/${pedido.id}`);
    } catch (e) {
      setErr((e as Error).message || "No se pudo crear el pedido rápido.");
      setSaving(false);
    }
  }

  function addCorteInicial() {
    setCortes((current) => current.length ? current : [emptyCorteDraft(0)]);
  }

  return (
    <div className="max-w-5xl">
      <div className="mb-6 flex items-center gap-3">
        <Link href="/pedidos" className="text-ink-soft hover:text-ink">
          <ArrowLeft size={20} />
        </Link>
        <div className="flex-1">
          <h1 className="text-2xl font-extrabold text-ink">Pedido rápido</h1>
          <p className="text-sm text-ink-soft">Crea presupuesto aprobado, pedido y pago en una sola carga.</p>
        </div>
        <Button type="submit" form="pedido-rapido-form" loading={saving}>
          <Save size={16} /> Crear pedido rápido
        </Button>
      </div>

      <form id="pedido-rapido-form" onSubmit={submit} className="grid grid-cols-1 gap-5 lg:grid-cols-3">
        <motion.section initial={{ opacity: 0, y: 8 }} animate={{ opacity: 1, y: 0 }} className="card space-y-4 p-5 lg:col-span-3">
          <div className="flex flex-wrap items-center justify-between gap-3">
            <h2 className="flex items-center gap-2 font-bold text-ink">
              <User size={16} /> Cliente
            </h2>
            <div className="flex rounded-xl border border-line bg-canvas p-1 text-sm font-semibold">
              <button type="button" onClick={() => setClienteMode("existente")} className={`rounded-lg px-3 py-1.5 ${clienteMode === "existente" ? "bg-surface text-ink shadow-sm" : "text-ink-soft"}`}>
                Buscar contacto
              </button>
              <button type="button" onClick={() => { setClienteMode("nuevo"); setSelectedCliente(null); }} className={`rounded-lg px-3 py-1.5 ${clienteMode === "nuevo" ? "bg-surface text-ink shadow-sm" : "text-ink-soft"}`}>
                Nuevo cliente
              </button>
            </div>
          </div>

          {clienteMode === "existente" ? (
            <div className="space-y-3">
              <Input label="Buscar en contactos" value={clienteSearch} onChange={(e) => setClienteSearch(e.target.value)} prefix={<Search size={16} />} placeholder="Nombre o celular" autoFocus />
              <div className="max-h-64 overflow-auto rounded-xl border border-line">
                {clientes.length === 0 ? (
                  <div className="p-5 text-center text-sm text-faint">
                    <Users size={24} className="mx-auto mb-2" /> No hay contactos para mostrar.
                  </div>
                ) : (
                  <div className="divide-y divide-line">
                    {clientes.map((cliente) => (
                      <button key={cliente.id} type="button" onClick={() => setSelectedCliente(cliente)} className={`flex w-full items-center justify-between gap-3 px-4 py-3 text-left hover:bg-canvas ${selectedCliente?.id === cliente.id ? "bg-brand-soft/60" : ""}`}>
                        <div>
                          <p className="font-semibold text-ink">{cliente.nombre}</p>
                          <p className="text-xs text-faint">{[cliente.celular, cliente.direccion].filter(Boolean).join(" · ") || "Sin datos extra"}</p>
                        </div>
                        {selectedCliente?.id === cliente.id && <span className="rounded-lg bg-brand px-2 py-1 text-xs font-bold text-white">Elegido</span>}
                      </button>
                    ))}
                  </div>
                )}
              </div>
            </div>
          ) : (
            <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
              <Input label="Nombre *" value={nombre} onChange={(e) => setNombre(e.target.value)} prefix={<User size={16} />} autoFocus />
              <Input label="Celular" type="tel" value={celular} onChange={(e) => setCelular(e.target.value)} prefix={<Phone size={16} />} />
              <div className="sm:col-span-2">
                <Input label="Dirección" value={direccion} onChange={(e) => setDireccion(e.target.value)} prefix={<MapPin size={16} />} />
              </div>
            </div>
          )}
        </motion.section>

        <motion.section initial={{ opacity: 0, y: 8 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.04 }} className="card space-y-4 p-5 lg:col-span-3">
          <label className="flex flex-col gap-1.5">
            <span className="text-sm font-medium text-ink-soft">Descripción corta</span>
            <textarea
              value={descripcion}
              onChange={(e) => setDescripcion(e.target.value)}
              rows={3}
              className="rounded-xl border border-line bg-surface px-3 py-2 text-sm text-ink outline-none resize-y focus:border-brand"
              placeholder="Ej: cortes mostrador, estante, herrajes, reparación..."
            />
          </label>
          <CommercialItemsEditor items={items} onChange={setItems} title="Productos / trabajos" />
        </motion.section>

        <motion.section initial={{ opacity: 0, y: 8 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.08 }} className="card p-5 lg:col-span-3">
          {cortes.length === 0 ? (
            <button type="button" onClick={addCorteInicial} className="w-full rounded-xl border border-dashed border-line bg-canvas px-4 py-6 text-sm text-faint hover:border-line-strong hover:text-ink">
              Agregar cortes si este pedido los necesita.
            </button>
          ) : (
            <CortesEditor items={cortes} onChange={setCortes} />
          )}
        </motion.section>

        <motion.section initial={{ opacity: 0, y: 8 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.12 }} className="card space-y-4 p-5 lg:col-span-3">
          <div className="flex flex-wrap items-center justify-between gap-3">
            <h2 className="flex items-center gap-2 font-bold text-ink">
              <Banknote size={16} /> Pago
            </h2>
            <span className="rounded-xl bg-brand-soft px-3 py-2 text-sm font-bold text-brand-dark">
              Total {money(total)}
            </span>
          </div>
          <div className="grid grid-cols-1 gap-3 md:grid-cols-[1fr_1fr_1fr_1.2fr]">
            <Input label="Seña (opcional)" type="number" min="0" placeholder="0" value={pagoMonto} onChange={(e) => setPagoMonto(e.target.value)} />
            <label className="flex flex-col gap-1.5">
              <span className="text-sm font-medium text-ink-soft">Cuenta</span>
              <select value={pagoCuenta} onChange={(e) => setPagoCuenta(e.target.value)} className="h-11 rounded-xl border border-line bg-surface px-3 text-sm outline-none focus:border-brand">
                {cuentas.map((cuenta) => <option key={cuenta.id} value={cuenta.id}>{cuenta.nombre}</option>)}
              </select>
            </label>
            <Input label="Fecha" type="date" value={pagoFecha} onChange={(e) => setPagoFecha(e.target.value)} />
            <Input label="Nota" value={pagoNota} onChange={(e) => setPagoNota(e.target.value)} />
          </div>
        </motion.section>

        <div className="lg:col-span-3 flex items-center justify-end gap-3">
          {err && <span className="text-sm font-medium text-bad">{err}</span>}
          <Button type="submit" size="lg" loading={saving}>
            <Save size={18} /> Crear pedido rápido
          </Button>
        </div>
      </form>
    </div>
  );
}
