"use client";

import { useEffect, useMemo, useState } from "react";
import { AlertCircle, BadgePercent, Search } from "lucide-react";

type Cliente = {
  Id_cliente: number;
  nombre_cliente: string;
  rut_cliente: string;
};

type BoletaPendiente = {
  id_boleta: number;
  fecha_a_pagar: string;
  total_boleta: number;
  total_original?: number;
};

type Concesion = {
  Id_condonacion: number;
  fecha_condonacion: string;
  Id_cliente: number;
  nombre_cliente?: string;
  rut_cliente?: string;
  Id_boleta: number;
  total_boleta: number;
  monto_descontado: number;
  no_acta?: string | null;
  otra_info?: string | null;
};

export default function CondonacionesPage() {
  const [busqueda, setBusqueda] = useState("");
  const [clientes, setClientes] = useState<Cliente[]>([]);
  const [clienteSel, setClienteSel] = useState<Cliente | null>(null);

  const [boletas, setBoletas] = useState<BoletaPendiente[]>([]);
  const [boletaSel, setBoletaSel] = useState<BoletaPendiente | null>(null);

  const [monto, setMonto] = useState<string>("");
  const [noActa, setNoActa] = useState<string>("");
  const [otraInfo, setOtraInfo] = useState<string>("");

  const [historial, setHistorial] = useState<Concesion[]>([]);
  const [loading, setLoading] = useState(false);
  const [mensaje, setMensaje] = useState<{ tipo: "error" | "success"; texto: string } | null>(null);

  const formatMoney = (valor: any) => {
    const n = typeof valor === "number" ? valor : Number(valor || 0);
    return new Intl.NumberFormat("es-CL", { style: "currency", currency: "CLP" }).format(n);
  };

  const buscarClientes = async () => {
    if (busqueda.trim().length < 2) return;
    setLoading(true);
    setMensaje(null);
    try {
      const res = await fetch(`/api/socios?busqueda=${encodeURIComponent(busqueda.trim())}`);
      const data = await res.json();
      if (!res.ok) throw new Error(data?.error || "Error al buscar socios");
      setClientes(data);
    } catch (e: any) {
      setMensaje({ tipo: "error", texto: e?.message || "Error al buscar" });
    } finally {
      setLoading(false);
    }
  };

  const cargarHistorial = async (clienteId?: number) => {
    try {
      const url = clienteId ? `/api/condonaciones?clienteId=${clienteId}` : `/api/condonaciones`;
      const res = await fetch(url);
      const data = await res.json();
      if (!res.ok) throw new Error(data?.error || "Error al cargar historial");
      setHistorial(data);
    } catch {
      // silencioso
    }
  };

  useEffect(() => {
    void cargarHistorial();
  }, []);

  const seleccionarCliente = async (c: Cliente) => {
    setClienteSel(c);
    setClientes([]);
    setBusqueda("");
    setBoletaSel(null);
    setBoletas([]);
    setMonto("");
    setNoActa("");
    setOtraInfo("");
    setMensaje(null);

    try {
      const res = await fetch(`/api/pagos?pendientes=true&clienteId=${c.Id_cliente}`);
      const data = await res.json();
      if (!res.ok) throw new Error(data?.error || "Error al cargar boletas pendientes");
      setBoletas(data);
      await cargarHistorial(c.Id_cliente);
    } catch (e: any) {
      setMensaje({ tipo: "error", texto: e?.message || "Error al cargar boletas" });
    }
  };

  const seleccionarBoleta = (b: BoletaPendiente) => {
    setBoletaSel(b);
    setMonto("");
    setMensaje(null);
  };

  const maxCondonable = useMemo(() => {
    if (!boletaSel) return 0;
    const total = Number(boletaSel.total_boleta || 0);
    return Math.max(0, total - 1);
  }, [boletaSel]);

  const registrarCondonacion = async () => {
    if (!clienteSel || !boletaSel) {
      setMensaje({ tipo: "error", texto: "Debe seleccionar socio y boleta" });
      return;
    }

    const montoNum = parseInt(monto);
    if (!Number.isFinite(montoNum) || montoNum <= 0) {
      setMensaje({ tipo: "error", texto: "El monto a condonar debe ser mayor a cero" });
      return;
    }

    const total = Number(boletaSel.total_boleta || 0);
    if (montoNum >= total) {
      setMensaje({ tipo: "error", texto: "El monto a condonar debe ser menor al total vigente" });
      return;
    }

    const ok = confirm(
      `¿Confirmas condonar ${formatMoney(montoNum)} de la boleta ${boletaSel.id_boleta} (total vigente ${formatMoney(total)})?`
    );
    if (!ok) return;

    setLoading(true);
    setMensaje(null);
    try {
      const res = await fetch("/api/condonaciones", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          clienteId: clienteSel.Id_cliente,
          boletaId: boletaSel.id_boleta,
          montoDescontado: montoNum,
          noActa: noActa.trim() || null,
          otraInfo: otraInfo.trim() || null,
        }),
      });

      const data = await res.json();
      if (!res.ok) throw new Error(data?.error || "Error al registrar condonación");

      setMensaje({ tipo: "success", texto: data?.message || "Condonación registrada" });

      // refresh boletas pendientes + historial
      const res2 = await fetch(`/api/pagos?pendientes=true&clienteId=${clienteSel.Id_cliente}`);
      const boletasData = await res2.json();
      if (res2.ok) setBoletas(boletasData);
      await cargarHistorial(clienteSel.Id_cliente);

      setBoletaSel(null);
      setMonto("");
      setNoActa("");
      setOtraInfo("");
    } catch (e: any) {
      setMensaje({ tipo: "error", texto: e?.message || "Error" });
    } finally {
      setLoading(false);
    }
  };

  return (
    <div>
      <div className="flex justify-between items-center mb-6">
        <h1 className="page-title">Condonaciones</h1>
      </div>

      {mensaje ? (
        <div
          className={`mb-4 p-4 rounded-lg flex items-center gap-2 ${
            mensaje.tipo === "error" ? "bg-red-50 text-red-700" : "bg-green-50 text-green-700"
          }`}
        >
          <AlertCircle className="w-5 h-5" />
          {mensaje.texto}
          <button onClick={() => setMensaje(null)} className="ml-auto">
            ×
          </button>
        </div>
      ) : null}

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <div className="lg:col-span-2">
          <div className="card mb-6">
            <h2 className="section-title">Seleccionar Socio</h2>

            <div className="flex gap-2">
              <div className="flex-1 relative">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
                <input
                  type="text"
                  placeholder="Buscar por nombre o RUT..."
                  value={busqueda}
                  onChange={(e) => setBusqueda(e.target.value)}
                  onKeyDown={(e) => e.key === "Enter" && buscarClientes()}
                  className="input-field pl-10"
                />
              </div>
              <button onClick={buscarClientes} className="btn-primary" disabled={loading}>
                Buscar
              </button>
            </div>

            {clientes.length > 0 ? (
              <div className="mt-4 border rounded-lg divide-y max-h-48 overflow-y-auto">
                {clientes.map((c) => (
                  <button
                    key={c.Id_cliente}
                    onClick={() => seleccionarCliente(c)}
                    className="w-full px-4 py-2 text-left hover:bg-gray-50 flex justify-between"
                  >
                    <span className="font-medium">{c.nombre_cliente}</span>
                    <span className="text-gray-500">{c.rut_cliente}</span>
                  </button>
                ))}
              </div>
            ) : null}
          </div>

          {clienteSel ? (
            <div className="card mb-6">
              <div className="flex items-center justify-between mb-3">
                <div>
                  <div className="font-bold text-lg">{clienteSel.nombre_cliente}</div>
                  <div className="text-gray-600">RUT: {clienteSel.rut_cliente}</div>
                </div>
              </div>

              <h3 className="font-medium mb-2">Boletas Pendientes</h3>
              {boletas.length === 0 ? (
                <div className="text-center py-6 text-gray-500">No hay boletas pendientes</div>
              ) : (
                <div className="table-container mb-4">
                  <table className="min-w-full divide-y divide-gray-200">
                    <thead className="bg-gray-50">
                      <tr>
                        <th className="px-4 py-2 table-header">Boleta</th>
                        <th className="px-4 py-2 table-header">Fecha</th>
                        <th className="px-4 py-2 table-header">Total Vigente</th>
                        <th className="px-4 py-2 table-header">Acción</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y">
                      {boletas.map((b) => (
                        <tr key={b.id_boleta} className={boletaSel?.id_boleta === b.id_boleta ? "bg-blue-50" : ""}>
                          <td className="px-4 py-2 font-mono">{b.id_boleta}</td>
                          <td className="px-4 py-2">{new Date(b.fecha_a_pagar).toLocaleDateString("es-CL")}</td>
                          <td className="px-4 py-2 text-right font-mono">{formatMoney(b.total_boleta)}</td>
                          <td className="px-4 py-2 text-right">
                            <button className="btn-secondary text-sm" onClick={() => seleccionarBoleta(b)}>
                              Seleccionar
                            </button>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              )}

              {boletaSel ? (
                <div className="border-t pt-4">
                  <div className="flex items-center gap-2 mb-3">
                    <BadgePercent className="w-5 h-5 text-blue-600" />
                    <span className="font-medium">Condonar boleta {boletaSel.id_boleta}</span>
                  </div>

                  <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-4">
                    <div>
                      <label className="block text-sm font-medium mb-1">Monto a condonar</label>
                      <input
                        type="number"
                        value={monto}
                        onChange={(e) => setMonto(e.target.value)}
                        className="input-field"
                        max={maxCondonable}
                      />
                      <div className="text-xs text-gray-500 mt-1">Máx: {formatMoney(maxCondonable)}</div>
                    </div>
                    <div>
                      <label className="block text-sm font-medium mb-1">N° Acta</label>
                      <input type="text" value={noActa} onChange={(e) => setNoActa(e.target.value)} className="input-field" />
                    </div>
                    <div>
                      <label className="block text-sm font-medium mb-1">Otra info</label>
                      <input
                        type="text"
                        value={otraInfo}
                        onChange={(e) => setOtraInfo(e.target.value)}
                        className="input-field"
                      />
                    </div>
                  </div>

                  <button
                    onClick={registrarCondonacion}
                    disabled={loading}
                    className="btn-primary w-full disabled:opacity-50"
                  >
                    {loading ? "Procesando..." : "Registrar condonación"}
                  </button>
                </div>
              ) : null}
            </div>
          ) : null}
        </div>

        <div className="card h-fit">
          <h2 className="section-title">Historial</h2>
          {historial.length === 0 ? (
            <div className="text-gray-500 text-center py-4">Sin registros</div>
          ) : (
            <div className="space-y-2">
              {historial.slice(0, 15).map((h) => (
                <div key={h.Id_condonacion} className="border rounded-lg p-3">
                  <div className="text-sm font-medium">
                    {h.nombre_cliente || `Cliente ${h.Id_cliente}`} - Boleta {h.Id_boleta}
                  </div>
                  <div className="text-xs text-gray-500">{new Date(h.fecha_condonacion).toLocaleDateString("es-CL")}</div>
                  <div className="mt-1 text-sm">
                    Condonado: <span className="font-mono">{formatMoney(h.monto_descontado)}</span>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
