import type { FC } from 'react';
import { useEffect, useState, useCallback } from 'react';
import { Package } from 'lucide-react';
import { Card, Badge, EmptyState, Skeleton, toast } from '../ui';
import { ExportButton } from '../ui/ExportButton';
import { exportToExcel } from '../../lib/exporter';
import { odooApi, type PaqueteRow } from '../../services/odoo';

const formatCurrency = (value: number) =>
  new Intl.NumberFormat('es-MX', { style: 'currency', currency: 'MXN', maximumFractionDigits: 0 }).format(value);

const PaquetesReport: FC = () => {
  const [paquetes, setPaquetes] = useState<PaqueteRow[]>([]);
  const [loading, setLoading] = useState(true);

  const load = useCallback(async () => {
    try {
      setLoading(true);
      const res = await odooApi.getPaquetes();
      if (res.status === 'success') setPaquetes(res.paquetes);
    } catch (err) {
      toast.error('Error al cargar paquetes');
      console.error(err);
    } finally {
      setLoading(false);
    }
  }, []);

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

  const [exporting, setExporting] = useState(false);
  const exportar = async () => {
    try {
      setExporting(true);
      await exportToExcel({
        filename: `paquetes-${new Date().toISOString().split('T')[0]}`,
        sheetName: 'Paquetes',
        title: 'Paquetes de sesiones',
        columns: [
          { header: 'Servicio', key: 'name' },
          { header: 'Sesiones', key: 'package_sessions', format: 'number' },
          { header: 'Precio paquete', key: 'package_price', format: 'currency' },
          { header: 'Precio sesión', key: 'price', format: 'currency' },
          { header: 'Citas agendadas', key: 'citas', format: 'number' },
          { header: 'Paquetes terminados', key: 'terminados', format: 'number' },
        ],
        rows: paquetes.map((p) => ({ ...p })),
        totals: { name: '', citas: paquetes.reduce((a, p) => a + p.citas, 0), terminados: paquetes.reduce((a, p) => a + p.terminados, 0) },
      });
      toast.success('Excel descargado');
    } catch (err) {
      toast.error('Error al exportar');
      console.error(err);
    } finally {
      setExporting(false);
    }
  };

  return (
    <Card>
      <Card.Body>
        <div className="flex items-start justify-between mb-1">
          <h3 className="font-heading text-xl text-theme-heading">Paquetes de sesiones</h3>
          <ExportButton onClick={exportar} loading={exporting} />
        </div>
        <p className="text-xs text-theme-muted mb-4">Servicios vendidos como paquete: sesiones contratadas, citas agendadas y paquetes terminados.</p>
        {loading ? (
          <Skeleton count={6} className="h-12 w-full" />
        ) : paquetes.length === 0 ? (
          <EmptyState title="Sin paquetes" subtitle="No hay servicios configurados como paquete." icon={<Package size={28} />} />
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead className="bg-theme-bg text-theme-muted text-xs uppercase">
                <tr>
                  <th className="text-left px-4 py-3">Servicio</th>
                  <th className="text-right px-4 py-3">Sesiones</th>
                  <th className="text-right px-4 py-3">Precio paquete</th>
                  <th className="text-right px-4 py-3 hidden sm:table-cell">Precio sesión</th>
                  <th className="text-right px-4 py-3">Citas agendadas</th>
                  <th className="text-right px-4 py-3">Paquetes terminados</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-theme-border">
                {paquetes.map((p) => (
                  <tr key={p.id} className="hover:bg-theme-bg">
                    <td className="px-4 py-3 font-medium text-theme-heading">{p.name}</td>
                    <td className="px-4 py-3 text-right text-theme-muted">{p.package_sessions}</td>
                    <td className="px-4 py-3 text-right text-theme-heading">{formatCurrency(p.package_price)}</td>
                    <td className="px-4 py-3 text-right text-theme-muted hidden sm:table-cell">{formatCurrency(p.price)}</td>
                    <td className="px-4 py-3 text-right text-theme-muted">{p.citas}</td>
                    <td className="px-4 py-3 text-right">
                      <Badge variant={p.terminados > 0 ? 'success' : 'default'}>{p.terminados}</Badge>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </Card.Body>
    </Card>
  );
};

export default PaquetesReport;
