import type { FC } from 'react';
import { useEffect, useState, useCallback } from 'react';
import { UserCheck } from 'lucide-react';
import { Card, Input, EmptyState, Skeleton, toast } from '../ui';
import { ExportButton } from '../ui/ExportButton';
import { exportToExcel } from '../../lib/exporter';
import { odooApi, type VendedorRow } 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 VendedoresReport: FC = () => {
  const [start, setStart] = useState(inicioDeMes());
  const [end, setEnd] = useState(hoy());
  const [vendedores, setVendedores] = useState<VendedorRow[]>([]);
  const [loading, setLoading] = useState(true);

  const load = useCallback(async () => {
    try {
      setLoading(true);
      const res = await odooApi.getVendedores(start, end);
      if (res.status === 'success') setVendedores(res.vendedores);
    } catch (err) {
      toast.error('Error al cargar vendedores');
      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: `vendedores-${start}_${end}`,
        sheetName: 'Vendedores',
        title: 'Ventas por vendedor',
        subtitle: `Del ${start} al ${end} · por usuario que registró la venta`,
        columns: [
          { header: 'Usuario', key: 'usuario' },
          { header: '# Ventas', key: 'num_ventas', format: 'number' },
          { header: 'Total vendido', key: 'total', format: 'currency' },
          { header: 'Cobrado', key: 'cobrado', format: 'currency' },
        ],
        rows: vendedores.map((v) => ({ ...v })),
        totals: {
          usuario: '',
          num_ventas: vendedores.reduce((a, v) => a + v.num_ventas, 0),
          total: vendedores.reduce((a, v) => a + v.total, 0),
          cobrado: vendedores.reduce((a, v) => a + v.cobrado, 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 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>
        <p className="text-xs text-theme-muted mb-4">Ventas agrupadas por el usuario que las registró en el sistema.</p>

        {loading ? (
          <Skeleton count={6} className="h-12 w-full" />
        ) : vendedores.length === 0 ? (
          <EmptyState title="Sin ventas" subtitle="No hay ventas registradas en el periodo." icon={<UserCheck 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">Usuario</th>
                  <th className="text-right px-4 py-3"># Ventas</th>
                  <th className="text-right px-4 py-3">Total vendido</th>
                  <th className="text-right px-4 py-3">Cobrado</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-theme-border">
                {vendedores.map((v, i) => (
                  <tr key={i} className="hover:bg-theme-bg">
                    <td className="px-4 py-3 font-medium text-theme-heading">{v.usuario}</td>
                    <td className="px-4 py-3 text-right text-theme-muted">{v.num_ventas}</td>
                    <td className="px-4 py-3 text-right font-medium text-theme-heading">{formatCurrency(v.total)}</td>
                    <td className="px-4 py-3 text-right text-theme-muted">{formatCurrency(v.cobrado)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </Card.Body>
    </Card>
  );
};

export default VendedoresReport;
