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

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

const inicioDeMes = () => {
  const d = new Date();
  d.setDate(1);
  return d.toISOString().split('T')[0];
};
const hoy = () => new Date().toISOString().split('T')[0];

const TopClientesReport: FC = () => {
  const [start, setStart] = useState(inicioDeMes());
  const [end, setEnd] = useState(hoy());
  const [clientes, setClientes] = useState<TopClienteRow[]>([]);
  const [loading, setLoading] = useState(true);

  const load = useCallback(async () => {
    try {
      setLoading(true);
      const res = await odooApi.getTopClientes(start, end, 20);
      if (res.status === 'success') setClientes(res.clientes);
    } catch (err) {
      toast.error('Error al cargar top clientes');
      console.error(err);
    } finally {
      setLoading(false);
    }
  }, [start, end]);

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

  const [exporting, setExporting] = useState(false);
  const exportar = async () => {
    try {
      setExporting(true);
      await exportToExcel({
        filename: `top-clientes-${start}_${end}`,
        sheetName: 'Top clientes',
        title: 'Top clientes por compras',
        subtitle: `Del ${start} al ${end}`,
        columns: [
          { header: '#', key: 'rank', format: 'number' },
          { header: 'Cliente', key: 'name' },
          { header: '# Ventas', key: 'num_ventas', format: 'number' },
          { header: 'Total comprado', key: 'total', format: 'currency' },
          { header: 'Ticket promedio', key: 'ticket_promedio', format: 'currency' },
        ],
        rows: clientes.map((c, i) => ({ ...c, rank: i + 1 })),
      });
      toast.success('Excel descargado');
    } catch (err) {
      toast.error('Error al exportar');
      console.error(err);
    } finally {
      setExporting(false);
    }
  };

  return (
    <Card>
      <Card.Body>
        <div className="flex flex-col sm:flex-row gap-3 mb-4 items-end">
          <Input label="Inicio" type="date" value={start} onChange={(e) => setStart(e.target.value)} className="sm:max-w-[160px]" />
          <Input label="Fin" type="date" value={end} onChange={(e) => setEnd(e.target.value)} className="sm:max-w-[160px]" />
          <div className="sm:ml-auto">
            <ExportButton onClick={exportar} loading={exporting} />
          </div>
        </div>

        {loading ? (
          <Skeleton count={6} className="h-12 w-full" />
        ) : clientes.length === 0 ? (
          <EmptyState title="Sin ventas" subtitle="No hay ventas en el periodo." icon={<Trophy 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">#</th>
                  <th className="text-left px-4 py-3">Cliente</th>
                  <th className="text-right px-4 py-3"># Ventas</th>
                  <th className="text-right px-4 py-3">Total comprado</th>
                  <th className="text-right px-4 py-3">Ticket promedio</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-theme-border">
                {clientes.map((c, i) => (
                  <tr key={c.id} className="hover:bg-theme-bg">
                    <td className="px-4 py-3 text-theme-muted">{i + 1}</td>
                    <td className="px-4 py-3 font-medium text-theme-heading">{c.name}</td>
                    <td className="px-4 py-3 text-right text-theme-muted">{c.num_ventas}</td>
                    <td className="px-4 py-3 text-right font-medium text-theme-heading">{formatCurrency(c.total)}</td>
                    <td className="px-4 py-3 text-right text-theme-muted">{formatCurrency(c.ticket_promedio)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </Card.Body>
    </Card>
  );
};

export default TopClientesReport;
