"use client";

import { useState, useEffect } from "react";
import { Play, Download, AlertCircle, FileText, Users } from "lucide-react";

interface Sector {
  Id_sector: number;
  nombre_sector: string;
}

interface GeneradorBoletasMasivoProps {
  onBoletasGeneradas?: () => void;
}

export default function GeneradorBoletasMasivo({ onBoletasGeneradas }: GeneradorBoletasMasivoProps) {
  const [sectores, setSectores] = useState<Sector[]>([]);
  const [sectorSeleccionado, setSectorSeleccionado] = useState("");
  const [mes, setMes] = useState(new Date().getMonth() + 1);
  const [anio, setAnio] = useState(new Date().getFullYear());
  const [generando, setGenerando] = useState(false);
  const [generandoPDF, setGenerandoPDF] = useState(false);
  const [mensaje, setMensaje] = useState<{ tipo: string; texto: string } | null>(null);
  const [estadisticas, setEstadisticas] = useState<any>(null);

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

  const cargarSectores = async () => {
    try {
      const res = await fetch("/api/mantenedores/sectores");
      const data = await res.json();
      setSectores(data);
    } catch (error) {
      console.error("Error al cargar sectores:", error);
    }
  };

  const obtenerEstadisticas = async () => {
    if (!sectorSeleccionado) return;

    try {
      const res = await fetch(`/api/facturacion/estadisticas?sectorId=${sectorSeleccionado}&mes=${mes}&anio=${anio}`);
      const data = await res.json();
      setEstadisticas(data);
    } catch (error) {
      console.error("Error al obtener estadísticas:", error);
    }
  };

  useEffect(() => {
    if (sectorSeleccionado) {
      obtenerEstadisticas();
    } else {
      setEstadisticas(null);
    }
  }, [sectorSeleccionado, mes, anio]);

  const generarMasivo = async () => {
    if (!sectorSeleccionado) {
      setMensaje({ tipo: "error", texto: "Seleccione un sector" });
      return;
    }

    setGenerando(true);
    setMensaje(null);
    try {
      const res = await fetch("/api/facturacion/generar-masivo", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ sectorId: parseInt(sectorSeleccionado), mes, anio })
      });
      const data = await res.json();

      if (data.success) {
        setMensaje({ tipo: "success", texto: data.message });
        if (onBoletasGeneradas) {
          onBoletasGeneradas();
        }
        obtenerEstadisticas();
      } else {
        setMensaje({ tipo: "error", texto: data.error });
      }
    } catch (error) {
      setMensaje({ tipo: "error", texto: "Error al generar boletas" });
    } finally {
      setGenerando(false);
    }
  };

  const descargarPDFsMasivos = async () => {
    if (!sectorSeleccionado) {
      setMensaje({ tipo: "error", texto: "Seleccione un sector" });
      return;
    }

    setGenerandoPDF(true);
    setMensaje(null);

    try {
      const body = {
        mes: mes,
        anio: anio,
        sectorId: parseInt(sectorSeleccionado),
        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_${sectorSeleccionado}_${mes}_${anio}.zip`;

      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);

      setMensaje({ tipo: "success", texto: "PDFs generados y descargados correctamente" });
    } catch (error: any) {
      setMensaje({ tipo: "error", texto: error.message || 'Error al generar PDFs' });
    } finally {
      setGenerandoPDF(false);
    }
  };

  const getSectorNombre = (id: string) => {
    const sector = sectores.find(s => s.Id_sector.toString() === id);
    return sector ? sector.nombre_sector : `Sector ${id}`;
  };

  return (
    <div className="card">
      <h2 className="section-title">Generación Masiva de Boletas</h2>

      {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>
      )}

      <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">Sector</label>
          <select
            value={sectorSeleccionado}
            onChange={(e) => setSectorSeleccionado(e.target.value)}
            className="input-field"
          >
            <option value="">Seleccione un sector...</option>
            {sectores.map((s) => (
              <option key={s.Id_sector} value={s.Id_sector}>{s.nombre_sector}</option>
            ))}
          </select>
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">Mes</label>
          <select value={mes} onChange={(e) => setMes(parseInt(e.target.value))} className="input-field">
            {Array.from({ length: 12 }, (_, i) => (
              <option key={i + 1} value={i + 1}>
                {new Date(2000, i).toLocaleString("es", { month: "long" })}
              </option>
            ))}
          </select>
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">Año</label>
          <select value={anio} onChange={(e) => setAnio(parseInt(e.target.value))} className="input-field">
            {[2024, 2025, 2026].map((a) => (
              <option key={a} value={a}>{a}</option>
            ))}
          </select>
        </div>

        <div className="flex items-end">
          <button
            onClick={generarMasivo}
            disabled={generando || !sectorSeleccionado}
            className="btn-primary flex items-center gap-2 disabled:opacity-50 w-full"
          >
            <Play className="w-4 h-4" />
            {generando ? "Generando..." : "Generar Boletas"}
          </button>
        </div>
      </div>

      {/* Estadísticas del sector */}
      {estadisticas && (
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
          <div className="bg-blue-50 p-4 rounded-lg">
            <div className="flex items-center">
              <Users className="w-8 h-8 text-blue-600" />
              <div className="ml-3">
                <p className="text-sm font-medium text-blue-600">Clientes en Sector</p>
                <p className="text-2xl font-bold text-blue-900">{estadisticas.total_clientes || 0}</p>
              </div>
            </div>
          </div>

          <div className="bg-green-50 p-4 rounded-lg">
            <div className="flex items-center">
              <FileText className="w-8 h-8 text-green-600" />
              <div className="ml-3">
                <p className="text-sm font-medium text-green-600">Con Lectura</p>
                <p className="text-2xl font-bold text-green-900">{estadisticas.con_lectura || 0}</p>
              </div>
            </div>
          </div>

          <div className="bg-yellow-50 p-4 rounded-lg">
            <div className="flex items-center">
              <AlertCircle className="w-8 h-8 text-yellow-600" />
              <div className="ml-3">
                <p className="text-sm font-medium text-yellow-600">Sin Lectura</p>
                <p className="text-2xl font-bold text-yellow-900">{estadisticas.sin_lectura || 0}</p>
              </div>
            </div>
          </div>

          <div className="bg-purple-50 p-4 rounded-lg">
            <div className="flex items-center">
              <FileText className="w-8 h-8 text-purple-600" />
              <div className="ml-3">
                <p className="text-sm font-medium text-purple-600">Boletas Generadas</p>
                <p className="text-2xl font-bold text-purple-900">{estadisticas.boletas_generadas || 0}</p>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Acciones adicionales */}
      {sectorSeleccionado && estadisticas?.boletas_generadas > 0 && (
        <div className="flex gap-4 p-4 bg-gray-50 rounded-lg">
          <div className="flex-1">
            <h3 className="font-medium text-gray-900 mb-1">
              {getSectorNombre(sectorSeleccionado)} - {new Date(anio, mes - 1).toLocaleString("es", { month: "long", year: "numeric" })}
            </h3>
            <p className="text-sm text-gray-600">
              {estadisticas.boletas_generadas} boletas generadas y listas para descargar
            </p>
          </div>

          <button
            onClick={descargarPDFsMasivos}
            disabled={generandoPDF}
            className="btn-secondary flex items-center gap-2 disabled:opacity-50"
          >
            {generandoPDF ? (
              <>
                <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-gray-600"></div>
                Generando PDFs...
              </>
            ) : (
              <>
                <Download className="w-4 h-4" />
                Descargar PDFs
              </>
            )}
          </button>
        </div>
      )}
    </div>
  );
}