'use client';

import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { DashboardShell } from '@/components/layouts/dashboard-shell';
import { Card, CardContent, Button, SortableHeader } from '@horux/shared-ui';
import { apiClient } from '@/lib/api/client';
import { formatCurrency } from '@/lib/utils';
import { exportToExcel } from '@/lib/export-excel';
import { useTableSort } from '@horux/shared-ui';
import { CfdiViewerModal } from '@/components/cfdi/cfdi-viewer-modal';
import { Eye, Download } from 'lucide-react';
import type { Cfdi } from '@horux/shared';

const EXCEL_COLUMNS = [
  { header: 'UUID', key: 'uuid', width: 40 },
  { header: 'Fecha', key: '_fecha', width: 15 },
  { header: 'RFC Emisor', key: 'rfcEmisor', width: 15 },
  { header: 'Nombre Emisor', key: 'nombreEmisor', width: 30 },
  { header: 'RFC Receptor', key: 'rfcReceptor', width: 15 },
  { header: 'Nombre Receptor', key: 'nombreReceptor', width: 30 },
  { header: 'Total MXN', key: '_totalMxn', width: 15 },
  { header: 'Forma Pago', key: 'formaPago', width: 12 },
];

function prepareRows(data: any[]) {
  return data.map((c) => ({
    ...c,
    _fecha: new Date(c.fechaEmision).toLocaleDateString('es-MX'),
    _totalMxn: Number(c.totalMxn || 0),
  }));
}

export default function EfectivoPage() {
  const [selectedCfdi, setSelectedCfdi] = useState<Cfdi | null>(null);

  const { data, isLoading } = useQuery({
    queryKey: ['drilldown-efectivo'],
    queryFn: async () => {
      const res = await apiClient.get<Cfdi[]>('/alertas/drilldown/efectivo');
      return res.data;
    },
  });

  const { sortedData, toggleSort, getSortIndicator } = useTableSort<Cfdi, 'fecha' | 'total'>(
    data,
    {
      fecha: (c) => new Date(c.fechaEmision).getTime(),
      total: (c) => Number(c.totalMxn || 0),
    },
    'fecha',
  );

  const handleExport = () => {
    if (!sortedData || sortedData.length === 0) return;
    exportToExcel(prepareRows(sortedData), EXCEL_COLUMNS, 'cfdis-pago-efectivo');
  };

  return (
    <DashboardShell title="CFDIs con Pago en Efectivo">
      <Card>
        <CardContent className="pt-6">
          {isLoading ? (
            <div className="text-center py-8 text-muted-foreground">Cargando...</div>
          ) : !data || data.length === 0 ? (
            <div className="text-center py-8 text-muted-foreground">No hay CFDIs con pago en efectivo</div>
          ) : (
            <div className="overflow-x-auto">
              <div className="flex items-center justify-between mb-4">
                <p className="text-xs text-muted-foreground">{data.length} CFDIs con pago en efectivo</p>
                <Button variant="outline" size="sm" onClick={handleExport}>
                  <Download className="h-4 w-4 mr-1" />
                  Excel
                </Button>
              </div>
              <table className="w-full text-sm">
                <thead>
                  <tr className="border-b text-left text-muted-foreground">
                    <th className="pb-3 font-medium">UUID</th>
                    <SortableHeader label="Fecha" active={getSortIndicator('fecha')} onClick={() => toggleSort('fecha')} />
                    <th className="pb-3 font-medium">RFC Emisor</th>
                    <th className="pb-3 font-medium">Nombre Emisor</th>
                    <th className="pb-3 font-medium">RFC Receptor</th>
                    <SortableHeader label="Total MXN" align="right" active={getSortIndicator('total')} onClick={() => toggleSort('total')} />
                    <th className="pb-3 font-medium"></th>
                  </tr>
                </thead>
                <tbody>
                  {(sortedData || []).map((cfdi: any) => (
                    <tr key={cfdi.id} className="border-b hover:bg-muted/50">
                      <td className="py-3 font-mono text-xs">{cfdi.uuid?.substring(0, 8)}</td>
                      <td className="py-3">{new Date(cfdi.fechaEmision).toLocaleDateString('es-MX')}</td>
                      <td className="py-3 font-mono text-xs">{cfdi.rfcEmisor}</td>
                      <td className="py-3 truncate max-w-[200px]">{cfdi.nombreEmisor}</td>
                      <td className="py-3 font-mono text-xs">{cfdi.rfcReceptor}</td>
                      <td className="py-3 text-right font-medium">{formatCurrency(Number(cfdi.totalMxn))}</td>
                      <td className="py-3">
                        <Button variant="ghost" size="sm" onClick={() => setSelectedCfdi(cfdi)} title="Ver factura">
                          <Eye className="h-4 w-4" />
                        </Button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </CardContent>
      </Card>

      <CfdiViewerModal
        cfdi={selectedCfdi}
        open={!!selectedCfdi}
        onClose={() => setSelectedCfdi(null)}
      />
    </DashboardShell>
  );
}
