"use client";

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

type Row = {
  Id_cliente: number;
  rut: string;
  nombre: string;
  direccion: string;
  cosumo_m3: number;
  subsidio: number;
  total_boleta: number;
  nro_decreto?: string;
  fecha_decreto?: string;
  fecha_venc?: string;
  titular_subsidio?: string;
  tipo_subsidio?: string;
};

export default function ReporteSubsidiosOtorgadosPage() {
  const now = new Date();
  const [anio, setAnio] = useState(String(now.getFullYear()));
  const [mes, setMes] = useState(String(now.getMonth() + 1));
  const [loading, setLoading] = useState(false);
  const [mensaje, setMensaje] = useState<string | null>(null);
  const [rows, setRows] = useState<Row[]>([]);

  const totalSubsidio = useMemo(
    () => rows.reduce((acc, r) => acc + Number(r.subsidio || 0), 0),
    [rows]
  );

  const cargar = async () => {
    setLoading(true);
    setMensaje(null);
    try {
      const res = await fetch(`/api/reportes/subsidios?anio=${encodeURIComponent(anio)}&mes=${encodeURIComponent(mes)}`);
      const data = await res.json();
      if (!res.ok) throw new Error(data?.error || "Error al obtener reporte");
      setRows(data);
    } catch (e: any) {
      setMensaje(e?.message || "Error al obtener reporte");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    void cargar();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-3xl font-bold text-gray-900">Subsidios Otorgados</h1>
        <p className="mt-1 text-sm text-gray-500">Listado mensual desde vista legacy.</p>
      </div>

      {mensaje && (
        <div className="rounded-md p-4 border bg-red-50 border-red-200">
          <div className="flex">
            <div className="flex-shrink-0">
              <AlertCircle className="h-5 w-5 text-red-400" />
            </div>
            <div className="ml-3">
              <p className="text-sm text-red-700">{mensaje}</p>
            </div>
          </div>
        </div>
      )}

      <div className="bg-white shadow sm:rounded-lg p-4">
        <div className="flex flex-wrap gap-2 items-end">
          <div>
            <label className="block text-sm font-medium text-gray-700">Año</label>
            <input
              className="mt-1 w-28 rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500"
              value={anio}
              onChange={(e) => setAnio(e.target.value)}
              inputMode="numeric"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700">Mes</label>
            <input
              className="mt-1 w-20 rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500"
              value={mes}
              onChange={(e) => setMes(e.target.value)}
              inputMode="numeric"
            />
          </div>
          <button
            className="inline-flex items-center px-3 py-2 rounded-md text-sm bg-white border border-gray-200 text-gray-700 hover:bg-gray-50"
            onClick={() => void cargar()}
            disabled={loading}
          >
            <RefreshCw className={`h-4 w-4 mr-2 ${loading ? "animate-spin" : ""}`} />
            Consultar
          </button>
          <div className="ml-auto text-sm text-gray-600">Total subsidio: ${totalSubsidio.toLocaleString("es-CL")}</div>
        </div>
      </div>

      <div className="bg-white shadow sm:rounded-lg overflow-hidden">
        <div className="overflow-x-auto">
          <table className="min-w-full divide-y divide-gray-200">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Cliente</th>
                <th className="px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">Consumo m3</th>
                <th className="px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">Subsidio</th>
                <th className="px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">Total boleta</th>
              </tr>
            </thead>
            <tbody className="bg-white divide-y divide-gray-200">
              {rows.map((r) => (
                <tr key={`${r.Id_cliente}-${r.rut}`}> 
                  <td className="px-4 py-3 whitespace-nowrap">
                    <div className="text-sm font-medium text-gray-900">{r.nombre}</div>
                    <div className="text-xs text-gray-500">{r.rut}</div>
                  </td>
                  <td className="px-4 py-3 whitespace-nowrap text-sm text-gray-700 text-right">
                    {Number(r.cosumo_m3 || 0).toLocaleString("es-CL")}
                  </td>
                  <td className="px-4 py-3 whitespace-nowrap text-sm text-gray-700 text-right">
                    ${Number(r.subsidio || 0).toLocaleString("es-CL")}
                  </td>
                  <td className="px-4 py-3 whitespace-nowrap text-sm text-gray-700 text-right">
                    ${Number(r.total_boleta || 0).toLocaleString("es-CL")}
                  </td>
                </tr>
              ))}
              {!loading && rows.length === 0 && (
                <tr>
                  <td colSpan={4} className="px-4 py-10 text-center text-gray-500">
                    No hay datos.
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
