import type { FC } from 'react';
import { useEffect, useState, useCallback } from 'react';
import { Users } from 'lucide-react';
import { Card, Input, EmptyState, Skeleton, toast } from '../ui';
import { ExportButton } from '../ui/ExportButton';
import { exportToExcel } from '../../lib/exporter';
import { odooApi, type PagoClienteRow } 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 PagosClientesReport: FC = () => {
  const [start, setStart] = useState(inicioDeMes());
  const [end, setEnd] = useState(hoy());
  const [clientes, setClientes] = useState<PagoClienteRow[]>([]);
  const [totalCobrado, setTotalCobrado] = useState(0);
  const [loading, setLoading] = useState(true);

  const load = useCallback(async () => {
    try {
      setLoading(true);
      const res = await odooApi.getPagosClientes(start, end);
      if (res.status === 'success') {
        setClientes(res.clientes);
        setTotalCobrado(res.total_cobrado);
      }
    } catch (err) {
      toast.error('Error al cargar pagos por cliente');
      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: `pagos-clientes-${start}_${end}`,
        sheetName: 'Pagos por cliente',
        title: 'Pagos · Clientes',
        subtitle: `Del ${start} al ${end}`,
        columns: [
          { header: 'Cliente', key: 'name' },
          { header: '# Pagos', key: 'num_pagos', format: 'number' },
          { header: 'Total cobrado', key: 'total_cobrado', format: 'currency' },
          { header: 'Último pago', key: 'ultimo_pago' },
        ],
        rows: clientes.map((c) => ({ ...c })),
        totals: { name: '', num_pagos: clientes.reduce((a, c) => a + c.num_pagos, 0), total_cobrado: totalCobrado },
      });
      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 sm:items-end sm:justify-between gap-3 mb-4">
          <div className="flex flex-col sm:flex-row gap-3 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]" />
            <ExportButton onClick={exportar} loading={exporting} />
          </div>
          <p className="text-sm text-theme-muted">
            Total cobrado: <span className="font-semibold text-theme-heading">{formatCurrency(totalCobrado)}</span>
          </p>
        </div>

        {loading ? (
          <Skeleton count={6} className="h-12 w-full" />
        ) : clientes.length === 0 ? (
          <EmptyState title="Sin cobros" subtitle="No hay pagos registrados en el periodo." icon={<Users 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">Cliente</th>
                  <th className="text-right px-4 py-3"># Pagos</th>
                  <th className="text-right px-4 py-3">Total cobrado</th>
                  <th className="text-left px-4 py-3 hidden sm:table-cell">Último pago</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-theme-border">
                {clientes.map((c) => (
                  <tr key={c.id} className="hover:bg-theme-bg">
                    <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_pagos}</td>
                    <td className="px-4 py-3 text-right font-medium text-theme-heading">{formatCurrency(c.total_cobrado)}</td>
                    <td className="px-4 py-3 text-theme-muted hidden sm:table-cell">{c.ultimo_pago || '-'}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </Card.Body>
    </Card>
  );
};

export default PagosClientesReport;
