"use client";

import { useState, useEffect } from "react";
import Link from "next/link";
import { FileText, Printer, XCircle, AlertCircle } from "lucide-react";
import GeneradorBoletasMasivo from "@/components/GeneradorBoletasMasivo";
import ResumenBoletasSector from "@/components/ResumenBoletasSector";
import GuiaImpresion from "@/components/GuiaImpresion";

interface Boleta {
  id_boleta: number;
  num_boleta: number;
  nombre: string;
  rut: string;
  fecha_a_pagar: string;
  cosumo_m3: number;
  total_boleta: number;
  estado_pago: number;
}

export default function FacturacionPage() {
  const [boletas, setBoletas] = useState<Boleta[]>([]);
  const [loading, setLoading] = useState(true);
  const [mensaje, setMensaje] = useState<{ tipo: string; texto: string } | null>(null);
  const [mes, setMes] = useState(new Date().getMonth() + 1);
  const [anio, setAnio] = useState(new Date().getFullYear());
  const [vistaActual, setVistaActual] = useState<'generacion' | 'resumen' | 'listado'>('generacion');

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

  const cargarDatos = async () => {
    setLoading(true);
    try {
      const res = await fetch(`/api/facturacion?mes=${mes}&anio=${anio}`);
      setBoletas(await res.json());
    } catch (error) {
      console.error("Error al cargar datos:", error);
    } finally {
      setLoading(false);
    }
  };

  const anularBoleta = async (id: number) => {
    if (!confirm("¿Está seguro de anular esta boleta?")) return;

    try {
      const res = await fetch(`/api/facturacion?id=${id}`, { method: "DELETE" });
      const data = await res.json();

      if (data.success) {
        setMensaje({ tipo: "success", texto: "Boleta anulada correctamente" });
        cargarDatos();
      } else {
        setMensaje({ tipo: "error", texto: data.error });
      }
    } catch (error) {
      setMensaje({ tipo: "error", texto: "Error al anular boleta" });
    }
  };

  const getEstadoLabel = (estado: number) => {
    switch (estado) {
      case 5: return { texto: "Pendiente", color: "bg-yellow-100 text-yellow-800" };
      case 6: return { texto: "Pagada", color: "bg-green-100 text-green-800" };
      case 9: return { texto: "Anulada", color: "bg-red-100 text-red-800" };
      default: return { texto: "Desconocido", color: "bg-gray-100 text-gray-800" };
    }
  };

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

  return (
    <div>
      <div className="flex justify-between items-center mb-6">
        <h1 className="page-title">Facturación</h1>
        <div className="flex gap-2 items-center">
          <GuiaImpresion />
          <select value={mes} onChange={(e) => setMes(parseInt(e.target.value))} className="input-field w-32">
            {Array.from({ length: 12 }, (_, i) => (
              <option key={i + 1} value={i + 1}>
                {new Date(2000, i).toLocaleString("es", { month: "long" })}
              </option>
            ))}
          </select>
          <select value={anio} onChange={(e) => setAnio(parseInt(e.target.value))} className="input-field w-24">
            {Array.from({ length: 5 }, (_, i) => new Date().getFullYear() - 2 + i).map((a) => (
              <option key={a} value={a}>{a}</option>
            ))}
          </select>
        </div>
      </div>

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

      {/* Navegación de pestañas */}
      <div className="mb-6">
        <nav className="flex space-x-8" aria-label="Tabs">
          <button
            onClick={() => setVistaActual('generacion')}
            className={`whitespace-nowrap py-2 px-1 border-b-2 font-medium text-sm ${vistaActual === 'generacion'
              ? 'border-blue-500 text-blue-600'
              : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
              }`}
          >
            Generar Boletas
          </button>
          <button
            onClick={() => setVistaActual('resumen')}
            className={`whitespace-nowrap py-2 px-1 border-b-2 font-medium text-sm ${vistaActual === 'resumen'
              ? 'border-blue-500 text-blue-600'
              : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
              }`}
          >
            Resumen por Sector
          </button>
          <button
            onClick={() => setVistaActual('listado')}
            className={`whitespace-nowrap py-2 px-1 border-b-2 font-medium text-sm ${vistaActual === 'listado'
              ? 'border-blue-500 text-blue-600'
              : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
              }`}
          >
            Listado de Boletas ({boletas.length})
          </button>
        </nav>
      </div>

      {/* Contenido según la vista actual */}
      {vistaActual === 'generacion' && (
        <GeneradorBoletasMasivo onBoletasGeneradas={cargarDatos} />
      )}

      {vistaActual === 'resumen' && (
        <ResumenBoletasSector mes={mes} anio={anio} />
      )}

      {vistaActual === 'listado' && (
        <div className="card">
          <div className="flex items-center justify-between mb-4">
            <div className="flex items-center gap-2">
              <FileText className="w-5 h-5 text-blue-600" />
              <span className="font-medium">Boletas del período: {boletas.length}</span>
            </div>
            <Link href={`/reportes/boletas?mes=${mes}&anio=${anio}`} className="btn-secondary flex items-center gap-2">
              <Printer className="w-4 h-4" /> Ver Reportes
            </Link>
          </div>

          {loading ? (
            <div className="text-center py-8 text-gray-500">Cargando...</div>
          ) : (
            <div className="table-container">
              <table className="min-w-full divide-y divide-gray-200">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="px-6 py-3 table-header">N° Boleta</th>
                    <th className="px-6 py-3 table-header">Socio</th>
                    <th className="px-6 py-3 table-header">Fecha</th>
                    <th className="px-6 py-3 table-header">Consumo</th>
                    <th className="px-6 py-3 table-header">Total</th>
                    <th className="px-6 py-3 table-header">Estado</th>
                    <th className="px-6 py-3 table-header">Acciones</th>
                  </tr>
                </thead>
                <tbody className="bg-white divide-y divide-gray-200">
                  {boletas.map((boleta) => {
                    const estado = getEstadoLabel(boleta.estado_pago);
                    return (
                      <tr key={boleta.id_boleta} className="hover:bg-gray-50">
                        <td className="table-cell font-mono">{boleta.num_boleta || boleta.id_boleta}</td>
                        <td className="table-cell">
                          <div className="font-medium">{boleta.nombre}</div>
                          <div className="text-xs text-gray-500">{boleta.rut}</div>
                        </td>
                        <td className="table-cell">{new Date(boleta.fecha_a_pagar).toLocaleDateString("es-CL")}</td>
                        <td className="table-cell text-right">{boleta.cosumo_m3} m³</td>
                        <td className="table-cell text-right font-medium">{formatMoney(boleta.total_boleta)}</td>
                        <td className="table-cell">
                          <span className={`px-2 py-1 rounded-full text-xs font-medium ${estado.color}`}>
                            {estado.texto}
                          </span>
                        </td>
                        <td className="table-cell">
                          <div className="flex gap-2">
                            <Link
                              href={`/facturacion/${boleta.id_boleta}`}
                              className="text-blue-600 hover:text-blue-800"
                              title="Ver boleta"
                            >
                              <Printer className="w-4 h-4" />
                            </Link>
                            {boleta.estado_pago === 5 && (
                              <button
                                onClick={() => anularBoleta(boleta.id_boleta)}
                                className="text-red-600 hover:text-red-800"
                                title="Anular boleta"
                              >
                                <XCircle className="w-4 h-4" />
                              </button>
                            )}
                          </div>
                        </td>
                      </tr>
                    );
                  })}
                  {boletas.length === 0 && !loading && (
                    <tr>
                      <td colSpan={7} className="px-6 py-10 text-center text-gray-500">
                        No hay boletas para el período seleccionado
                      </td>
                    </tr>
                  )}
                </tbody>
              </table>
            </div>
          )}
        </div>
      )}
    </div>
  );
}
