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

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

const metodoLabels: Record<string, string> = {
  cash: 'Efectivo', card: 'Tarjeta', transfer: 'Transferencia',
  stripe: 'Stripe', mercadopago: 'MercadoPago',
};

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

const PagosServiciosReport: FC = () => {
  const [start, setStart] = useState(inicioDeMes());
  const [end, setEnd] = useState(hoy());
  const [servicios, setServicios] = useState<PagoServicioRow[]>([]);
  const [byMethod, setByMethod] = useState<Record<string, number>>({});
  const [totalCobrado, setTotalCobrado] = useState(0);
  const [totalPagadoCompleto, setTotalPagadoCompleto] = useState(0);
  const [loading, setLoading] = useState(true);

  const load = useCallback(async () => {
    try {
      setLoading(true);
      const res = await odooApi.getPagosServicios(start, end);
      if (res.status === 'success') {
        setServicios(res.servicios);
        setByMethod(res.by_method);
        setTotalCobrado(res.total_cobrado);
        setTotalPagadoCompleto(res.total_pagado_completo);
      }
    } catch (err) {
      toast.error('Error al cargar pagos por servicio');
      console.error(err);
    } finally {
      setLoading(false);
    }
  }, [start, end]);

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

  const [exporting, setExporting] = useState(false);
  const exportar = async () => {
    try {
      setExporting(true);
      const rows: Record<string, unknown>[] = servicios.map((s) => ({
        servicio: s.servicio, cantidad: s.cantidad, total: s.total, metodo: '', monto: null,
      }));
      Object.entries(byMethod).forEach(([k, v]) =>
        rows.push({ servicio: '', cantidad: null, total: null, metodo: metodoLabels[k] || k, monto: v }));
      await exportToExcel({
        filename: `pagos-servicios-${start}_${end}`,
        sheetName: 'Pagos por servicio',
        title: 'Pagos · Servicios',
        subtitle: `Del ${start} al ${end} · ventas liquidadas por servicio y cobros por método`,
        columns: [
          { header: 'Servicio', key: 'servicio' },
          { header: 'Cantidad', key: 'cantidad', format: 'number' },
          { header: 'Total', key: 'total', format: 'currency' },
          { header: 'Método', key: 'metodo' },
          { header: 'Monto', key: 'monto', format: 'currency' },
        ],
        rows,
        totals: { servicio: '', total: totalPagadoCompleto, monto: totalCobrado },
      });
      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">
      <Card>
        <Card.Body>
          <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]" />
            <div className="sm:ml-auto">
              <ExportButton onClick={exportar} loading={exporting} />
            </div>
          </div>
        </Card.Body>
      </Card>

      <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 cobrado (pagos del periodo)</p>
          <p className="text-xl font-heading font-semibold text-theme-heading">{formatCurrency(totalCobrado)}</p>
        </Card>
        <Card className="p-4 bg-theme-bg border-0">
          <p className="text-xs text-theme-muted">Ventas liquidadas en el periodo</p>
          <p className="text-xl font-heading font-semibold text-theme-heading">{formatCurrency(totalPagadoCompleto)}</p>
        </Card>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-4 sm:gap-6">
        <Card className="lg:col-span-2">
          <Card.Body>
            <h3 className="font-heading text-xl text-theme-heading mb-1">Cobrado por servicio</h3>
            <p className="text-xs text-theme-muted mb-4">Ventas totalmente pagadas del periodo, agrupadas por servicio.</p>
            {loading ? (
              <Skeleton count={6} className="h-10 w-full" />
            ) : servicios.length === 0 ? (
              <EmptyState title="Sin datos" subtitle="No hay ventas liquidadas en el periodo." icon={<CreditCard 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">Servicio</th>
                      <th className="text-right px-4 py-3">Cantidad</th>
                      <th className="text-right px-4 py-3">Total</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-theme-border">
                    {servicios.map((s, i) => (
                      <tr key={i} className="hover:bg-theme-bg">
                        <td className="px-4 py-3 font-medium text-theme-heading">{s.servicio}</td>
                        <td className="px-4 py-3 text-right text-theme-muted">{s.cantidad}</td>
                        <td className="px-4 py-3 text-right font-medium text-theme-heading">{formatCurrency(s.total)}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </Card.Body>
        </Card>

        <Card>
          <Card.Body>
            <h3 className="font-heading text-xl text-theme-heading mb-4">Cobros por método</h3>
            {loading ? (
              <Skeleton className="h-32 w-full" />
            ) : Object.keys(byMethod).length === 0 ? (
              <p className="text-sm text-theme-muted">Sin cobros en el periodo.</p>
            ) : (
              <div className="space-y-2">
                {Object.entries(byMethod).map(([method, amount]) => (
                  <div key={method} className="flex items-center justify-between p-2.5 bg-theme-bg rounded-lg text-sm">
                    <span className="text-theme-heading">{metodoLabels[method] || method}</span>
                    <span className="font-medium text-theme-heading">{formatCurrency(amount)}</span>
                  </div>
                ))}
              </div>
            )}
          </Card.Body>
        </Card>
      </div>
    </div>
  );
};

export default PagosServiciosReport;
