"use client";

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

type Row = {
  id_boleta: number;
  id_cliente: number;
  fecha_a_pagar: string;
  cosumo_m3: number;
  total_mes_act: number;
  sector: number;
};

export default function ReporteConsumoMensualPage() {
  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 totalConsumo = useMemo(
    () => rows.reduce((acc, r) => acc + Number(r.cosumo_m3 || 0), 0),
    [rows]
  );

  const cargar = async () => {
    setLoading(true);
    setMensaje(null);
    try {
      const res = await fetch(`/api/reportes/consumo?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">Consumo Mensual</h1>
        <p className="mt-1 text-sm text-gray-500">Listado desde tabla estadística legacy (máx. 500 filas).</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">Consumo total: {totalConsumo.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">Fecha</th>
                <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-left text-xs font-medium text-gray-500 uppercase tracking-wider">Sector</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">Total mes</th>
              </tr>
            </thead>
            <tbody className="bg-white divide-y divide-gray-200">
              {rows.map((r) => (
                <tr key={r.id_boleta}>
                  <td className="px-4 py-3 whitespace-nowrap text-sm text-gray-700">{String(r.fecha_a_pagar || "")}</td>
                  <td className="px-4 py-3 whitespace-nowrap text-sm text-gray-700">{r.id_cliente}</td>
                  <td className="px-4 py-3 whitespace-nowrap text-sm text-gray-700">{r.sector}</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.total_mes_act || 0).toLocaleString("es-CL")}
                  </td>
                </tr>
              ))}
              {!loading && rows.length === 0 && (
                <tr>
                  <td colSpan={5} className="px-4 py-10 text-center text-gray-500">
                    No hay datos.
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
