import type { FC } from 'react';
import { useEffect, useState, useCallback } from 'react';
import { RotateCcw } from 'lucide-react';
import { Card, Input, EmptyState, Skeleton, toast } from '../ui';
import { ExportButton } from '../ui/ExportButton';
import { exportToExcel } from '../../lib/exporter';
import { odooApi, type DevolucionRow } 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 DevolucionesReport: FC = () => {
  const [start, setStart] = useState(inicioDeMes());
  const [end, setEnd] = useState(hoy());
  const [devoluciones, setDevoluciones] = useState<DevolucionRow[]>([]);
  const [totalDevuelto, setTotalDevuelto] = useState(0);
  const [loading, setLoading] = useState(true);

  const load = useCallback(async () => {
    try {
      setLoading(true);
      const res = await odooApi.getDevoluciones(start, end);
      if (res.status === 'success') {
        setDevoluciones(res.devoluciones);
        setTotalDevuelto(res.total_devuelto);
      }
    } catch (err) {
      toast.error('Error al cargar devoluciones');
      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: `devoluciones-${start}_${end}`,
        sheetName: 'Devoluciones',
        title: 'Devoluciones',
        subtitle: `Del ${start} al ${end}`,
        columns: [
          { header: 'Folio', key: 'folio' },
          { header: 'Paciente', key: 'paciente' },
          { header: 'Fecha venta', key: 'fecha', format: 'date' },
          { header: 'Total venta', key: 'total', format: 'currency' },
          { header: 'Devuelto', key: 'refund_amount', format: 'currency' },
          { header: 'Motivo', key: 'refund_reason' },
          { header: 'Fecha devolución', key: 'refunded_at' },
        ],
        rows: devoluciones.map((d) => ({ ...d })),
        totals: { folio: '', refund_amount: totalDevuelto, total: devoluciones.reduce((a, d) => a + d.total, 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 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 devuelto: <span className={`font-semibold ${totalDevuelto > 0 ? 'text-rose-600' : 'text-theme-heading'}`}>{formatCurrency(totalDevuelto)}</span>
          </p>
        </div>

        {loading ? (
          <Skeleton count={6} className="h-12 w-full" />
        ) : devoluciones.length === 0 ? (
          <EmptyState title="Sin devoluciones" subtitle="No hay ventas devueltas en el periodo." icon={<RotateCcw 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">Folio</th>
                  <th className="text-left px-4 py-3">Paciente</th>
                  <th className="text-left px-4 py-3 hidden sm:table-cell">Fecha venta</th>
                  <th className="text-right px-4 py-3">Total venta</th>
                  <th className="text-right px-4 py-3">Devuelto</th>
                  <th className="text-left px-4 py-3 hidden md:table-cell">Motivo</th>
                  <th className="text-left px-4 py-3 hidden md:table-cell">Fecha devolución</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-theme-border">
                {devoluciones.map((d) => (
                  <tr key={d.id} className="hover:bg-theme-bg">
                    <td className="px-4 py-3 font-medium text-theme-heading">{d.folio}</td>
                    <td className="px-4 py-3 text-theme-heading">{d.paciente}</td>
                    <td className="px-4 py-3 text-theme-muted hidden sm:table-cell">{d.fecha || '-'}</td>
                    <td className="px-4 py-3 text-right text-theme-muted">{formatCurrency(d.total)}</td>
                    <td className="px-4 py-3 text-right font-medium text-rose-600">{formatCurrency(d.refund_amount)}</td>
                    <td className="px-4 py-3 text-theme-muted hidden md:table-cell">
                      <span className="block max-w-[220px] truncate" title={d.refund_reason}>{d.refund_reason || '-'}</span>
                    </td>
                    <td className="px-4 py-3 text-theme-muted hidden md:table-cell">{d.refunded_at || '-'}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </Card.Body>
    </Card>
  );
};

export default DevolucionesReport;
