"use client";

import { useState, useEffect } from "react";
import { CreditCard, Search, DollarSign, AlertCircle, CheckCircle } from "lucide-react";

interface BoletaPendiente {
  id_boleta: number;
  fecha_a_pagar: string;
  total_boleta: number;
  saldo_anterior: number;
  cosumo_m3: number;
}

interface Cliente {
  Id_cliente: number;
  nombre_cliente: string;
  rut_cliente: string;
}

export default function PagosPage() {
  const [clientes, setClientes] = useState<Cliente[]>([]);
  const [clienteSeleccionado, setClienteSeleccionado] = useState<Cliente | null>(null);
  const [boletasPendientes, setBoletasPendientes] = useState<BoletaPendiente[]>([]);
  const [busqueda, setBusqueda] = useState("");
  const [monto, setMonto] = useState("");
  const [pagaCon, setPagaCon] = useState("");
  const [esAbono, setEsAbono] = useState(false);
  const [tipoPago, setTipoPago] = useState("1");
  const [loading, setLoading] = useState(false);
  const [mensaje, setMensaje] = useState<{ tipo: string; texto: string } | null>(null);
  const [pagosHoy, setPagosHoy] = useState<any[]>([]);

  useEffect(() => {
    cargarPagosHoy();
  }, []);

  const cargarPagosHoy = async () => {
    try {
      const res = await fetch("/api/pagos?hoy=true");
      setPagosHoy(await res.json());
    } catch (error) {
      console.error("Error al cargar pagos del día:", error);
    }
  };

  const buscarClientes = async () => {
    if (busqueda.length < 2) return;
    setLoading(true);
    try {
      const res = await fetch(`/api/socios?busqueda=${encodeURIComponent(busqueda)}`);
      setClientes(await res.json());
    } catch (error) {
      console.error("Error al buscar clientes:", error);
    } finally {
      setLoading(false);
    }
  };

  const seleccionarCliente = async (cliente: Cliente) => {
    setClienteSeleccionado(cliente);
    setClientes([]);
    setBusqueda("");
    
    try {
      const res = await fetch(`/api/pagos?pendientes=true&clienteId=${cliente.Id_cliente}`);
      const boletas = await res.json();
      setBoletasPendientes(boletas);
      
      const totalDeuda = boletas.reduce((sum: number, b: BoletaPendiente) => sum + b.total_boleta, 0);
      setMonto(String(totalDeuda));
    } catch (error) {
      console.error("Error al cargar boletas pendientes:", error);
    }
  };

  const registrarPago = async () => {
    if (!clienteSeleccionado || !monto || boletasPendientes.length === 0) {
      setMensaje({ tipo: "error", texto: "Complete todos los campos requeridos" });
      return;
    }

    const montoNum = parseInt(monto);
    const pagaConNum = parseInt(pagaCon) || montoNum;

    if (montoNum <= 0) {
      setMensaje({ tipo: "error", texto: "El monto debe ser mayor a cero" });
      return;
    }

    setLoading(true);
    try {
      const res = await fetch("/api/pagos", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          clienteId: clienteSeleccionado.Id_cliente,
          boletaId: boletasPendientes[0].id_boleta,
          tipoDocumento: 3,
          monto: montoNum,
          esAbono,
          pagaCon: pagaConNum,
          vuelto: pagaConNum - montoNum,
          tipoPago: parseInt(tipoPago)
        })
      });

      const data = await res.json();
      if (data.success) {
        setMensaje({ tipo: "success", texto: data.message });
        setClienteSeleccionado(null);
        setBoletasPendientes([]);
        setMonto("");
        setPagaCon("");
        cargarPagosHoy();
      } else {
        setMensaje({ tipo: "error", texto: data.error });
      }
    } catch (error) {
      setMensaje({ tipo: "error", texto: "Error al registrar pago" });
    } finally {
      setLoading(false);
    }
  };

  const formatMoney = (valor: number) => {
    return new Intl.NumberFormat("es-CL", { style: "currency", currency: "CLP" }).format(valor);
  };

  const totalDeuda = boletasPendientes.reduce((sum, b) => sum + b.total_boleta, 0);
  const vuelto = (parseInt(pagaCon) || 0) - (parseInt(monto) || 0);

  return (
    <div>
      <h1 className="page-title">Registro de Pagos</h1>

      {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"
        }`}>
          {mensaje.tipo === "error" ? <AlertCircle className="w-5 h-5" /> : <CheckCircle className="w-5 h-5" />}
          {mensaje.texto}
          <button onClick={() => setMensaje(null)} className="ml-auto">×</button>
        </div>
      )}

      <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">Buscar Cliente</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((cliente) => (
                  <button
                    key={cliente.Id_cliente}
                    onClick={() => seleccionarCliente(cliente)}
                    className="w-full px-4 py-2 text-left hover:bg-gray-50 flex justify-between"
                  >
                    <span className="font-medium">{cliente.nombre_cliente}</span>
                    <span className="text-gray-500">{cliente.rut_cliente}</span>
                  </button>
                ))}
              </div>
            )}
          </div>

          {clienteSeleccionado && (
            <div className="card mb-6">
              <h2 className="section-title">Cliente Seleccionado</h2>
              <div className="bg-blue-50 p-4 rounded-lg mb-4">
                <p className="font-bold text-lg">{clienteSeleccionado.nombre_cliente}</p>
                <p className="text-gray-600">RUT: {clienteSeleccionado.rut_cliente}</p>
              </div>

              {boletasPendientes.length > 0 ? (
                <>
                  <h3 className="font-medium mb-2">Boletas Pendientes ({boletasPendientes.length})</h3>
                  <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">Fecha</th>
                          <th className="px-4 py-2 table-header">Consumo</th>
                          <th className="px-4 py-2 table-header">Total</th>
                        </tr>
                      </thead>
                      <tbody className="divide-y">
                        {boletasPendientes.map((boleta) => (
                          <tr key={boleta.id_boleta}>
                            <td className="px-4 py-2">{new Date(boleta.fecha_a_pagar).toLocaleDateString("es-CL")}</td>
                            <td className="px-4 py-2 text-right">{boleta.cosumo_m3} m³</td>
                            <td className="px-4 py-2 text-right font-medium">{formatMoney(boleta.total_boleta)}</td>
                          </tr>
                        ))}
                      </tbody>
                      <tfoot className="bg-gray-100">
                        <tr>
                          <td colSpan={2} className="px-4 py-2 font-bold">Total Deuda</td>
                          <td className="px-4 py-2 text-right font-bold text-lg">{formatMoney(totalDeuda)}</td>
                        </tr>
                      </tfoot>
                    </table>
                  </div>

                  <div className="grid grid-cols-2 gap-4 mb-4">
                    <div>
                      <label className="block text-sm font-medium mb-1">Monto a Pagar</label>
                      <input
                        type="number"
                        value={monto}
                        onChange={(e) => setMonto(e.target.value)}
                        className="input-field"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium mb-1">Paga Con</label>
                      <input
                        type="number"
                        value={pagaCon}
                        onChange={(e) => setPagaCon(e.target.value)}
                        className="input-field"
                        placeholder={monto}
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium mb-1">Tipo de Pago</label>
                      <select value={tipoPago} onChange={(e) => setTipoPago(e.target.value)} className="input-field">
                        <option value="1">Efectivo</option>
                        <option value="2">Cheque</option>
                        <option value="3">Transferencia</option>
                      </select>
                    </div>
                    <div className="flex items-center pt-6">
                      <label className="flex items-center gap-2 cursor-pointer">
                        <input
                          type="checkbox"
                          checked={esAbono}
                          onChange={(e) => setEsAbono(e.target.checked)}
                          className="w-4 h-4"
                        />
                        <span>Es Abono Parcial</span>
                      </label>
                    </div>
                  </div>

                  {vuelto > 0 && (
                    <div className="bg-yellow-50 p-3 rounded-lg mb-4 text-center">
                      <span className="font-bold">Vuelto: {formatMoney(vuelto)}</span>
                    </div>
                  )}

                  <button
                    onClick={registrarPago}
                    disabled={loading}
                    className="btn-success w-full flex items-center justify-center gap-2"
                  >
                    <DollarSign className="w-5 h-5" />
                    {loading ? "Procesando..." : "Registrar Pago"}
                  </button>
                </>
              ) : (
                <div className="text-center py-8 text-green-600">
                  ✓ Este cliente no tiene boletas pendientes
                </div>
              )}
            </div>
          )}
        </div>

        <div className="card h-fit">
          <h2 className="section-title flex items-center gap-2">
            <CreditCard className="w-5 h-5" /> Pagos de Hoy
          </h2>
          {pagosHoy.length === 0 ? (
            <p className="text-gray-500 text-center py-4">Sin pagos registrados hoy</p>
          ) : (
            <div className="space-y-2">
              {pagosHoy.slice(0, 10).map((pago, i) => (
                <div key={i} className="flex justify-between text-sm border-b pb-2">
                  <span className="truncate flex-1">{pago.nombre_cliente}</span>
                  <span className="font-medium">{formatMoney(pago.monto)}</span>
                </div>
              ))}
              <div className="pt-2 font-bold text-right">
                Total: {formatMoney(pagosHoy.reduce((s, p) => s + p.monto, 0))}
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
