"use client";

import { useState, useEffect } from "react";
import { useParams, useSearchParams } from "next/navigation";
import BoletaImpresion from "@/components/BoletaImpresion";
import type { BoletaData } from "@/components/BoletaPDF";

export default function ImprimirBoletasSectorPage() {
  const params = useParams();
  const searchParams = useSearchParams();
  const [boletas, setBoletas] = useState<BoletaData[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const sectorId = params.sector as string;
  const mes = searchParams.get('mes') || new Date().getMonth() + 1;
  const anio = searchParams.get('anio') || new Date().getFullYear();

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

  const cargarBoletasSector = async () => {
    setLoading(true);
    setError(null);
    try {
      // Obtener boletas del sector
      const res = await fetch(`/api/facturacion?sector=${sectorId}&mes=${mes}&anio=${anio}`);
      if (!res.ok) {
        throw new Error('Error al cargar boletas');
      }
      const boletasBasicas = await res.json();
      
      // Obtener datos completos para cada boleta
      const boletasCompletas = await Promise.all(
        boletasBasicas.map(async (boleta: any) => {
          const resDetalle = await fetch(`/api/facturacion/${boleta.id_boleta}/pdf`);
          return await resDetalle.json();
        })
      );
      
      setBoletas(boletasCompletas);
    } catch (err: any) {
      setError(err.message || 'Error al cargar boletas');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    // Auto-imprimir cuando las boletas estén cargadas
    if (boletas.length > 0) {
      const timer = setTimeout(() => {
        window.print();
      }, 1000); // Esperar 1 segundo para que se renderice todo
      
      return () => clearTimeout(timer);
    }
  }, [boletas]);

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-screen print:hidden">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
          <p className="text-gray-600">Cargando boletas para impresión...</p>
          <p className="text-sm text-gray-500">Sector {sectorId} - {mes}/{anio}</p>
        </div>
      </div>
    );
  }

  if (error || boletas.length === 0) {
    return (
      <div className="flex items-center justify-center min-h-screen print:hidden">
        <div className="text-center">
          <div className="text-red-600 mb-4">
            <svg className="w-16 h-16 mx-auto" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.732-.833-2.5 0L4.268 18.5c-.77.833.192 2.5 1.732 2.5z" />
            </svg>
          </div>
          <h2 className="text-xl font-semibold text-gray-900 mb-2">
            {error || 'No hay boletas para imprimir'}
          </h2>
          <p className="text-gray-600 mb-4">Sector {sectorId} - {mes}/{anio}</p>
          <button
            onClick={() => window.history.back()}
            className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
          >
            Volver
          </button>
        </div>
      </div>
    );
  }

  return (
    <>
      {/* Estilos específicos para impresión masiva */}
      <style jsx>{`
        @media print {
          body * {
            visibility: hidden;
          }
          .print-area, .print-area * {
            visibility: visible;
          }
          .print-area {
            position: absolute;
            left: 0;
            top: 0;
            width: 100%;
          }
          .page-break {
            page-break-before: always;
          }
          .no-print {
            display: none !important;
          }
        }
      `}</style>

      {/* Información de control (solo visible en pantalla) */}
      <div className="print:hidden p-4 bg-blue-50 border-b">
        <div className="max-w-4xl mx-auto">
          <h1 className="text-xl font-bold text-blue-900">Impresión Masiva de Boletas</h1>
          <p className="text-blue-700">
            Sector {sectorId} - {mes}/{anio} - {boletas.length} boletas
          </p>
          <p className="text-sm text-blue-600 mt-2">
            La impresión se iniciará automáticamente. Si no se abre el diálogo de impresión, 
            presiona <kbd className="bg-white px-1 rounded">Ctrl+P</kbd> (Windows) o <kbd className="bg-white px-1 rounded">Cmd+P</kbd> (Mac)
          </p>
        </div>
      </div>

      {/* Área de impresión */}
      <div className="print-area">
        {boletas.map((boleta, index) => (
          <div key={boleta.id_boleta} className={index > 0 ? 'page-break' : ''}>
            <BoletaImpresion boleta={boleta} />
          </div>
        ))}
      </div>
    </>
  );
}