"use client";

import { useState, useEffect } from "react";
import { FileText, Download, Eye, Users, DollarSign, Printer } from "lucide-react";
import Link from "next/link";

interface ResumenSector {
  sector: number;
  nombre_sector: string;
  cantidad_boletas: number;
  total_boletas: number;
  total_consumo_m3: number;
  promedio_consumo: number;
  promedio_valor: number;
}

interface ResumenBoletasSectorProps {
  mes: number;
  anio: number;
}

export default function ResumenBoletasSector({ mes, anio }: ResumenBoletasSectorProps) {
  const [resumen, setResumen] = useState<ResumenSector[]>([]);
  const [loading, setLoading] = useState(true);
  const [generandoPDF, setGenerandoPDF] = useState<number | null>(null);

  useEffect(() => {
    cargarResumen();
  }, [mes, anio]);

  const cargarResumen = async () => {
    setLoading(true);
    try {
      const [boletasRes, sectoresRes] = await Promise.all([
        fetch(`/api/reportes/boletas?mes=${mes}&anio=${anio}`),
        fetch('/api/mantenedores/sectores')
      ]);
      
      const boletas = await boletasRes.json();
      const sectores = await sectoresRes.json();
      
      // Combinar datos de boletas con nombres de sectores
      const resumenConNombres = boletas.map((b: any) => {
        const sector = sectores.find((s: any) => s.Id_sector === b.sector);
        return {
          ...b,
          nombre_sector: sector?.nombre_sector || `Sector ${b.sector}`,
          promedio_consumo: b.cantidad_boletas > 0 ? Math.round(b.total_consumo_m3 / b.cantidad_boletas) : 0,
          promedio_valor: b.cantidad_boletas > 0 ? Math.round(b.total_boletas / b.cantidad_boletas) : 0
        };
      });
      
      setResumen(resumenConNombres);
    } catch (error) {
      console.error("Error al cargar resumen:", error);
    } finally {
      setLoading(false);
    }
  };

  const descargarPDFSector = async (sectorId: number) => {
    setGenerandoPDF(sectorId);
    
    try {
      const body = {
        mes: mes,
        anio: anio,
        sectorId: sectorId,
        tipo: 'individual'
      };

      const response = await fetch('/api/reportes/boletas-pdf', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(body)
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || 'Error al generar PDFs');
      }

      // Descargar el archivo ZIP
      const blob = await response.blob();
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = `boletas_sector_${sectorId}_${mes}_${anio}.zip`;
      
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
    } catch (error: any) {
      alert(error.message || 'Error al generar PDFs');
    } finally {
      setGenerandoPDF(null);
    }
  };

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

  const totalGeneral = resumen.reduce((acc, r) => acc + r.total_boletas, 0);
  const totalBoletas = resumen.reduce((acc, r) => acc + r.cantidad_boletas, 0);
  const totalConsumo = resumen.reduce((acc, r) => acc + r.total_consumo_m3, 0);

  if (loading) {
    return (
      <div className="card">
        <div className="text-center py-8">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto mb-4"></div>
          <p className="text-gray-600">Cargando resumen...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="card">
      <div className="flex items-center justify-between mb-6">
        <div>
          <h2 className="section-title">Resumen por Sector</h2>
          <p className="text-sm text-gray-600">
            {new Date(anio, mes - 1).toLocaleString("es", { month: "long", year: "numeric" })}
          </p>
        </div>
        <div className="text-right">
          <div className="text-2xl font-bold text-blue-600">{formatMoney(totalGeneral)}</div>
          <div className="text-sm text-gray-600">{totalBoletas} boletas • {totalConsumo.toLocaleString()} m³</div>
        </div>
      </div>

      {resumen.length === 0 ? (
        <div className="text-center py-8 text-gray-500">
          <FileText className="w-12 h-12 mx-auto mb-4 text-gray-300" />
          <p>No hay boletas para el período seleccionado</p>
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {resumen.map((sector) => (
            <div key={sector.sector} className="border rounded-lg p-4 hover:shadow-md transition-shadow">
              <div className="flex items-center justify-between mb-3">
                <div>
                  <h3 className="font-semibold text-gray-900">{sector.nombre_sector}</h3>
                  <p className="text-sm text-gray-600">Sector {sector.sector}</p>
                </div>
                <div className="text-right">
                  <div className="text-lg font-bold text-blue-600">
                    {formatMoney(sector.total_boletas)}
                  </div>
                </div>
              </div>

              <div className="space-y-2 mb-4">
                <div className="flex items-center justify-between text-sm">
                  <div className="flex items-center gap-1">
                    <FileText className="w-4 h-4 text-gray-400" />
                    <span>Boletas:</span>
                  </div>
                  <span className="font-medium">{sector.cantidad_boletas}</span>
                </div>
                
                <div className="flex items-center justify-between text-sm">
                  <div className="flex items-center gap-1">
                    <Users className="w-4 h-4 text-gray-400" />
                    <span>Consumo:</span>
                  </div>
                  <span className="font-medium">{sector.total_consumo_m3.toLocaleString()} m³</span>
                </div>
                
                <div className="flex items-center justify-between text-sm">
                  <div className="flex items-center gap-1">
                    <DollarSign className="w-4 h-4 text-gray-400" />
                    <span>Promedio:</span>
                  </div>
                  <span className="font-medium">{formatMoney(sector.promedio_valor)}</span>
                </div>
              </div>

              <div className="flex gap-2">
                <Link
                  href={`/reportes/boletas?mes=${mes}&anio=${anio}&sector=${sector.sector}`}
                  className="flex-1 btn-secondary text-center flex items-center justify-center gap-1 text-xs py-2"
                >
                  <Eye className="w-3 h-3" />
                  Ver
                </Link>
                
                <Link
                  href={`/facturacion/imprimir/${sector.sector}?mes=${mes}&anio=${anio}`}
                  target="_blank"
                  className="flex-1 btn-secondary text-center flex items-center justify-center gap-1 text-xs py-2"
                >
                  <Printer className="w-3 h-3" />
                  Imprimir
                </Link>
                
                <button
                  onClick={() => descargarPDFSector(sector.sector)}
                  disabled={generandoPDF === sector.sector}
                  className="flex-1 btn-primary text-center flex items-center justify-center gap-1 text-xs py-2 disabled:opacity-50"
                >
                  {generandoPDF === sector.sector ? (
                    <>
                      <div className="animate-spin rounded-full h-3 w-3 border-b-2 border-white"></div>
                      PDF
                    </>
                  ) : (
                    <>
                      <Download className="w-3 h-3" />
                      PDF
                    </>
                  )}
                </button>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}