import type { FC } from 'react';
import { useEffect, useState, useCallback } from 'react';
import { Link } from 'react-router-dom';
import { Receipt, ExternalLink } from 'lucide-react';
import { Card, Button, Badge, EmptyState, Skeleton, toast } from '../ui';
import { ExportButton } from '../ui/ExportButton';
import { exportToExcel } from '../../lib/exporter';
import { odooApi, type CashClosing } from '../../services/odoo';

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

const PAGE = 20;

const CortesReport: FC = () => {
  const [cortes, setCortes] = useState<CashClosing[]>([]);
  const [loading, setLoading] = useState(true);
  const [verMas, setVerMas] = useState(false);

  const load = useCallback(async () => {
    try {
      setLoading(true);
      const res = await odooApi.getCashClosings();
      if (res.status === 'success') setCortes(res.cash_closings);
    } catch (err) {
      toast.error('Error al cargar cortes de caja');
      console.error(err);
    } finally {
      setLoading(false);
    }
  }, []);

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

  const [exporting, setExporting] = useState(false);
  const exportar = async () => {
    try {
      setExporting(true);
      const money = { format: 'currency' as const };
      await exportToExcel({
        filename: `cortes-de-caja-${new Date().toISOString().split('T')[0]}`,
        sheetName: 'Cortes de caja',
        title: 'Cortes de caja',
        subtitle: `${cortes.length} cortes`,
        columns: [
          { header: 'Fecha', key: 'date', format: 'date' },
          { header: 'Usuario', key: 'user' },
          { header: 'Apertura', key: 'opening_cash', ...money },
          { header: 'Efectivo', key: 'total_cash', ...money },
          { header: 'Tarjeta', key: 'total_card', ...money },
          { header: 'Transferencia', key: 'total_transfer', ...money },
          { header: 'Otros', key: 'total_other', ...money },
          { header: 'Total ventas', key: 'total_sales', ...money },
          { header: 'Diferencia', key: 'difference', ...money },
          { header: 'Estado', key: 'estado' },
        ],
        rows: cortes.map((c) => ({ ...c, estado: c.state === 'closed' ? 'Cerrado' : 'Abierto' })),
        totals: {
          date: '', user: '', opening_cash: cortes.reduce((a, c) => a + c.opening_cash, 0),
          total_cash: cortes.reduce((a, c) => a + c.total_cash, 0),
          total_card: cortes.reduce((a, c) => a + c.total_card, 0),
          total_transfer: cortes.reduce((a, c) => a + c.total_transfer, 0),
          total_other: cortes.reduce((a, c) => a + c.total_other, 0),
          total_sales: cortes.reduce((a, c) => a + c.total_sales, 0),
        },
      });
      toast.success('Excel descargado');
    } catch (err) {
      toast.error('Error al exportar');
      console.error(err);
    } finally {
      setExporting(false);
    }
  };

  const visibles = verMas ? cortes : cortes.slice(0, PAGE);

  return (
    <Card>
      <Card.Body>
        <div className="flex items-center justify-between mb-4">
          <h3 className="font-heading text-xl text-theme-heading">Cortes de caja</h3>
          <div className="flex items-center gap-2">
            <ExportButton onClick={exportar} loading={exporting} />
            <Link to="/cortes">
              <Button variant="outline" size="sm">
                <ExternalLink size={14} className="mr-1.5" />
                Ir a Cortes
              </Button>
            </Link>
          </div>
        </div>

        {loading ? (
          <Skeleton count={6} className="h-12 w-full" />
        ) : cortes.length === 0 ? (
          <EmptyState title="Sin cortes" subtitle="Aún no hay cortes de caja registrados." icon={<Receipt 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">Fecha</th>
                    <th className="text-left px-4 py-3 hidden md:table-cell">Usuario</th>
                    <th className="text-right px-4 py-3">Apertura</th>
                    <th className="text-right px-4 py-3 hidden sm:table-cell">Efectivo</th>
                    <th className="text-right px-4 py-3 hidden sm:table-cell">Tarjeta</th>
                    <th className="text-right px-4 py-3 hidden md:table-cell">Transfer.</th>
                    <th className="text-right px-4 py-3 hidden md:table-cell">Otros</th>
                    <th className="text-right px-4 py-3">Total ventas</th>
                    <th className="text-right px-4 py-3 hidden sm:table-cell">Diferencia</th>
                    <th className="text-left px-4 py-3">Estado</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-theme-border">
                  {visibles.map((c) => (
                    <tr key={c.id} className="hover:bg-theme-bg">
                      <td className="px-4 py-3 text-theme-heading whitespace-nowrap">{c.date}</td>
                      <td className="px-4 py-3 text-theme-muted hidden md:table-cell">{c.user || '-'}</td>
                      <td className="px-4 py-3 text-right text-theme-muted">{formatCurrency(c.opening_cash)}</td>
                      <td className="px-4 py-3 text-right text-theme-muted hidden sm:table-cell">{formatCurrency(c.total_cash)}</td>
                      <td className="px-4 py-3 text-right text-theme-muted hidden sm:table-cell">{formatCurrency(c.total_card)}</td>
                      <td className="px-4 py-3 text-right text-theme-muted hidden md:table-cell">{formatCurrency(c.total_transfer)}</td>
                      <td className="px-4 py-3 text-right text-theme-muted hidden md:table-cell">{formatCurrency(c.total_other)}</td>
                      <td className="px-4 py-3 text-right font-medium text-theme-heading">{formatCurrency(c.total_sales)}</td>
                      <td className={`px-4 py-3 text-right hidden sm:table-cell ${c.difference ? 'text-rose-600' : 'text-theme-muted'}`}>
                        {c.state === 'closed' ? formatCurrency(c.difference) : '-'}
                      </td>
                      <td className="px-4 py-3">
                        <Badge variant={c.state === 'closed' ? 'success' : 'warning'}>
                          {c.state === 'closed' ? 'Cerrado' : 'Abierto'}
                        </Badge>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
            {!verMas && cortes.length > PAGE && (
              <div className="mt-4 text-center">
                <Button variant="outline" size="sm" onClick={() => setVerMas(true)}>
                  Ver más ({cortes.length - PAGE} restantes)
                </Button>
              </div>
            )}
          </>
        )}
      </Card.Body>
    </Card>
  );
};

export default CortesReport;
