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

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

const AdeudosReport: FC = () => {
  const [adeudos, setAdeudos] = useState<AdeudoRow[]>([]);
  const [totalCartera, setTotalCartera] = useState(0);
  const [totalPacientes, setTotalPacientes] = useState(0);
  const [loading, setLoading] = useState(true);

  const load = useCallback(async () => {
    try {
      setLoading(true);
      const res = await odooApi.getAdeudos();
      if (res.status === 'success') {
        setAdeudos(res.adeudos);
        setTotalCartera(res.total_cartera);
        setTotalPacientes(res.total_pacientes);
      }
    } catch (err) {
      toast.error('Error al cargar adeudos');
      console.error(err);
    } finally {
      setLoading(false);
    }
  }, []);

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

  const [exporting, setExporting] = useState(false);
  const exportar = async () => {
    try {
      setExporting(true);
      await exportToExcel({
        filename: `adeudos-${new Date().toISOString().split('T')[0]}`,
        sheetName: 'Adeudos',
        title: 'Adeudos de clientes',
        subtitle: `${totalPacientes} pacientes con adeudo`,
        columns: [
          { header: 'Paciente', key: 'name' },
          { header: 'Teléfono', key: 'phone' },
          { header: '# Ventas', key: 'num_ventas', format: 'number' },
          { header: 'Adeudo', key: 'total_adeudo', format: 'currency' },
          { header: 'Última venta', key: 'ultima_venta', format: 'date' },
        ],
        rows: adeudos.map((a) => ({ ...a })),
        totals: { name: '', total_adeudo: totalCartera, num_ventas: adeudos.reduce((a, x) => a + x.num_ventas, 0) },
      });
      toast.success('Excel descargado');
    } catch (err) {
      toast.error('Error al exportar');
      console.error(err);
    } finally {
      setExporting(false);
    }
  };

  return (
    <div className="space-y-4 sm:space-y-6">
      <div className="flex justify-end">
        <ExportButton onClick={exportar} loading={exporting} />
      </div>
      <div className="grid grid-cols-2 gap-4">
        <Card className="p-4 bg-theme-bg border-0">
          <p className="text-xs text-theme-muted">Total cartera por cobrar</p>
          <p className={`text-xl font-heading font-semibold ${totalCartera > 0 ? 'text-rose-600' : 'text-theme-heading'}`}>
            {formatCurrency(totalCartera)}
          </p>
        </Card>
        <Card className="p-4 bg-theme-bg border-0">
          <p className="text-xs text-theme-muted">Pacientes con adeudo</p>
          <p className="text-xl font-heading font-semibold text-theme-heading">{totalPacientes}</p>
        </Card>
      </div>

      <Card>
        <Card.Body>
          {loading ? (
            <Skeleton count={8} className="h-10 w-full" />
          ) : adeudos.length === 0 ? (
            <EmptyState title="Sin adeudos" subtitle="Ningún paciente tiene saldo pendiente." icon={<HandCoins 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">Paciente</th>
                    <th className="text-left px-4 py-3 hidden sm:table-cell">Teléfono</th>
                    <th className="text-right px-4 py-3"># Ventas</th>
                    <th className="text-right px-4 py-3">Adeudo</th>
                    <th className="text-left px-4 py-3 hidden md:table-cell">Última venta</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-theme-border">
                  {adeudos.map((a) => (
                    <tr key={a.id} className="hover:bg-theme-bg">
                      <td className="px-4 py-3 font-medium text-theme-heading">
                        {a.phone ? (
                          <Link to={`/pacientes?q=${encodeURIComponent(a.phone)}`} className="hover:underline">
                            {a.name}
                          </Link>
                        ) : (
                          a.name
                        )}
                      </td>
                      <td className="px-4 py-3 text-theme-muted hidden sm:table-cell">{a.phone || '-'}</td>
                      <td className="px-4 py-3 text-right text-theme-muted">{a.num_ventas}</td>
                      <td className="px-4 py-3 text-right font-semibold text-rose-600">{formatCurrency(a.total_adeudo)}</td>
                      <td className="px-4 py-3 text-theme-muted hidden md:table-cell">{a.ultima_venta || '-'}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </Card.Body>
      </Card>
    </div>
  );
};

export default AdeudosReport;
