import { Icon } from "@iconify/react";
import { useState } from "react";
import styled from "styled-components";
import {
  useReporteCobranzasDiaQuery,
  useReporteComisionesLiquidarQuery,
  useReporteDiferenciasQuery,
  useReportePendientesQuery,
} from "../../../tanstack/RendicionesStack";
import { ScreenGuia } from "../../_standards";
import { useAuthStore } from "../../../store/AuthStore";
import { generarReporteCobranzasPDF } from "../../../reportesPDF/generarReporteCobranzasPdf";
import { generarReportePendientesPDF } from "../../../reportesPDF/generarReportePendientesPdf";
import { generarReporteDiferenciasPDF } from "../../../reportesPDF/generarReporteDiferenciasPdf";
import { generarReporteComisionesPDF } from "../../../reportesPDF/generarReporteComisionesPdf";
import { hoyISO } from "../../../utils/fecha";

const GUIA_PASOS = [
  {
    icon: "lucide:calendar-days",
    color: "#3b82f6",
    titulo: "Cobranzas del día",
    desc: "Agregado por cobrador en un rango de fechas (hoy, semana, mes…): rendiciones, recibos, declarado vs verificado y diferencia. Exportable a PDF.",
  },
  {
    icon: "lucide:clock",
    color: "#f59e0b",
    titulo: "Pendientes",
    desc: "Rendiciones en PENDIENTE/OBSERVADO con antigüedad — ámbar a las 24h, rojo a partir de 72h.",
  },
  {
    icon: "lucide:alert-triangle",
    color: "#ef4444",
    titulo: "Diferencias",
    desc: "Lista las rendiciones con diferencia entre declarado y verificado. Filtrá por nivel (menor / mayor).",
  },
  {
    icon: "lucide:badge-dollar-sign",
    color: "#22c55e",
    titulo: "Comisiones a liquidar",
    desc: "Comisiones aprobadas pendientes de pago al cobrador, listas para incluir en una liquidación.",
  },
];
const GUIA_NOTAS = [
  { icon: "lucide:info", text: "Los datos provienen de vistas SQL: actualizados al momento, refresco automático cada 60s para Pendientes." },
  { icon: "lucide:info", text: "Una comisión pasa a 'aprobada' al aprobar la rendición y desaparece de aquí cuando se incluye en una liquidación." },
];

const fmtMoney = (n) => new Intl.NumberFormat("es-PY").format(Number(n) || 0);
const fmtFecha = (f) => {
  if (!f) return "-";
  const d = new Date(f);
  if (isNaN(d.getTime())) return "-";
  return `${String(d.getUTCDate()).padStart(2, "0")}/${String(d.getUTCMonth() + 1).padStart(2, "0")}/${d.getUTCFullYear()}`;
};
const hoy = () => hoyISO();

// ── Styled ─────────────────────────────────────────────────────────
const Wrapper = styled.div`
  display: flex;
  flex-direction: column;
  gap: 1.25rem;
`;
const Tabs = styled.div`
  display: flex;
  gap: 0.25rem;
  border-bottom: 1px solid ${(p) => p.theme.borderColor};
  overflow-x: auto;
`;
const Tab = styled.button`
  background: none;
  border: none;
  padding: 0.65rem 1rem;
  font-size: 0.85rem;
  font-weight: 600;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 0.35rem;
  color: ${(p) => (p.$active ? p.theme.primary : p.theme.textSecondary)};
  border-bottom: 2px solid
    ${(p) => (p.$active ? p.theme.primary : "transparent")};
  margin-bottom: -1px;
  white-space: nowrap;
  &:hover {
    color: ${(p) => p.theme.text};
  }
`;
const Toolbar = styled.div`
  display: flex;
  gap: 0.75rem;
  align-items: end;
  flex-wrap: wrap;
  background: ${(p) => p.theme.bg6};
  border-radius: 10px;
  padding: 0.85rem 1rem;
  label {
    font-size: 0.7rem;
    font-weight: 600;
    color: ${(p) => p.theme.textSecondary};
    text-transform: uppercase;
    display: block;
    margin-bottom: 0.25rem;
  }
  input,
  select {
    background: ${(p) => p.theme.inputBg};
    border: 1px solid ${(p) => p.theme.inputBorder};
    border-radius: 8px;
    padding: 0.45rem 0.75rem;
    color: ${(p) => p.theme.text};
    font-size: 0.82rem;
    outline: none;
    font-family: inherit;
    &:focus {
      border-color: ${(p) => p.theme.primary};
      box-shadow: 0 0 0 3px ${(p) => p.theme.primary}20;
    }
  }
`;
const KpiGrid = styled.div`
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
  gap: 0.75rem;
`;
const KpiCard = styled.div`
  border: 1px solid ${(p) => p.theme.borderColor};
  border-radius: 12px;
  padding: 0.85rem 1rem;
  display: flex;
  align-items: center;
  gap: 0.85rem;
  .icon-box {
    width: 2.4rem;
    height: 2.4rem;
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: ${(p) => p.$color}15;
    color: ${(p) => p.$color};
    font-size: 1.1rem;
    flex-shrink: 0;
  }
  .label {
    font-size: 0.72rem;
    color: ${(p) => p.theme.textSecondary};
    font-weight: 600;
    text-transform: uppercase;
  }
  .value {
    font-size: 1.1rem;
    font-weight: 700;
    color: ${(p) => p.$color};
    line-height: 1.3;
  }
`;
const DataTable = styled.div`
  border: 1px solid ${(p) => p.theme.borderColor};
  border-radius: 12px;
  overflow: hidden;
  table {
    width: 100%;
    border-collapse: collapse;
    font-size: 0.82rem;
    th,
    td {
      padding: 0.6rem 0.85rem;
      text-align: left;
    }
    th {
      background: ${(p) => p.theme.bg6};
      font-weight: 700;
      color: ${(p) => p.theme.textSecondary};
      font-size: 0.72rem;
      text-transform: uppercase;
      letter-spacing: 0.05em;
    }
    tbody tr {
      border-bottom: 1px solid ${(p) => p.theme.borderColor};
      &:last-child {
        border-bottom: none;
      }
      &:hover {
        background: ${(p) => p.theme.bgAlpha};
      }
    }
    .right {
      text-align: right;
      white-space: nowrap;
    }
    .bold {
      font-weight: 700;
    }
  }
`;
const Badge = styled.span`
  display: inline-flex;
  align-items: center;
  gap: 0.25rem;
  padding: 0.2rem 0.6rem;
  border-radius: 20px;
  font-size: 0.7rem;
  font-weight: 600;
  color: ${(p) => p.$color};
  background: ${(p) => p.$color}14;
  border: 1px solid ${(p) => p.$color}30;
  white-space: nowrap;
`;
const Empty = styled.div`
  padding: 2.5rem;
  text-align: center;
  color: ${(p) => p.theme.textSecondary};
  font-size: 0.85rem;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 0.5rem;
`;
const Title = styled.h3`
  margin: 0;
  font-size: 1.05rem;
  font-weight: 700;
  color: ${(p) => p.theme.text};
  display: flex;
  align-items: center;
  gap: 0.5rem;
`;
const RangeBtns = styled.div`
  display: flex;
  gap: 0.35rem;
  flex-wrap: wrap;
  align-self: end;
`;
const QuickBtn = styled.button`
  background: ${(p) => p.theme.bg6};
  border: 1px solid ${(p) => p.theme.borderColor};
  color: ${(p) => p.theme.text};
  border-radius: 999px;
  padding: 0.35rem 0.75rem;
  font-size: 0.72rem;
  font-weight: 600;
  cursor: pointer;
  &:hover {
    background: ${(p) => p.theme.primary}18;
    border-color: ${(p) => p.theme.primary};
    color: ${(p) => p.theme.primary};
  }
`;
const ExportBtn = styled.button`
  margin-left: auto;
  background: #ef4444;
  border: none;
  color: #fff;
  border-radius: 8px;
  padding: 0.5rem 0.9rem;
  font-size: 0.78rem;
  font-weight: 700;
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  gap: 0.35rem;
  align-self: end;
  &:disabled {
    opacity: 0.45;
    cursor: not-allowed;
  }
  &:hover:not(:disabled) {
    background: #dc2626;
  }
`;
const PdfOverlay = styled.div`
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.7);
  z-index: 1100;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 1rem;
`;
const PdfDialog = styled.div`
  background: ${(p) => p.theme.bg2};
  border: 1px solid ${(p) => p.theme.borderColor};
  border-radius: 14px;
  width: 100%;
  max-width: 980px;
  height: 90vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5);
`;
const PdfHeader = styled.div`
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 1rem;
  padding: 0.75rem 1rem;
  border-bottom: 1px solid ${(p) => p.theme.borderColor};
  flex-shrink: 0;
  background: ${(p) => p.theme.bg6};
  > div:first-child {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    color: ${(p) => p.theme.text};
    font-size: 0.9rem;
  }
`;
const PdfHeaderActions = styled.div`
  display: flex;
  gap: 0.4rem;
`;
const PdfActionBtn = styled.button`
  display: inline-flex;
  align-items: center;
  gap: 0.3rem;
  padding: 0.45rem 0.8rem;
  border-radius: 8px;
  border: 1px solid
    ${(p) => (p.$primary ? p.theme.primary : p.theme.borderColor)};
  background: ${(p) => (p.$primary ? p.theme.primary : "transparent")};
  color: ${(p) => (p.$primary ? "#fff" : p.theme.text)};
  font-size: 0.78rem;
  font-weight: 600;
  cursor: pointer;
  &:hover {
    opacity: 0.88;
  }
`;
const PdfFrame = styled.iframe`
  flex: 1;
  width: 100%;
  border: none;
  background: #525659;
`;
const Spinner = styled(Icon)`
  animation: spin 1s linear infinite;
  @keyframes spin {
    to {
      transform: rotate(360deg);
    }
  }
`;

const colorDif = (dif) => {
  const d = Number(dif) || 0;
  if (d === 0) return "#22c55e";
  if (Math.abs(d) < 50000) return "#f59e0b";
  return "#ef4444";
};
const colorAntiguedad = (h) => {
  if (h < 24) return "#22c55e";
  if (h < 72) return "#f59e0b";
  return "#ef4444";
};

// ── Hook compartido para preview PDF ───────────────────────────────
const usePdfPreview = () => {
  const [pdfPreview, setPdfPreview] = useState(null);
  const open = (factory) => {
    const { pdf, fileName } = factory();
    pdf.getBlob((blob) => {
      const url = URL.createObjectURL(blob);
      setPdfPreview({ url, pdf, fileName });
    });
  };
  const close = () => {
    if (pdfPreview?.url) URL.revokeObjectURL(pdfPreview.url);
    setPdfPreview(null);
  };
  return { pdfPreview, open, close };
};

// ── Tab 1: Cobranzas (rango de fechas) ─────────────────────────────
const TabCobranzasDia = () => {
  const [fechaDesde, setFechaDesde] = useState(hoy());
  const [fechaHasta, setFechaHasta] = useState(hoy());
  const { data, isLoading } = useReporteCobranzasDiaQuery(fechaDesde, fechaHasta);
  const porCobrador = data?.por_cobrador || [];
  const tot = data?.totales || {};
  const empresa = useAuthStore((s) => s.empresa);

  const aplicarRango = (dias) => {
    const hastaD = new Date();
    const desdeD = new Date();
    desdeD.setDate(hastaD.getDate() - dias + 1);
    setFechaDesde(desdeD.toISOString().split("T")[0]);
    setFechaHasta(hastaD.toISOString().split("T")[0]);
  };

  const aplicarMesActual = () => {
    const hoyD = new Date();
    const primero = new Date(hoyD.getFullYear(), hoyD.getMonth(), 1);
    setFechaDesde(primero.toISOString().split("T")[0]);
    setFechaHasta(hoyD.toISOString().split("T")[0]);
  };

  const { pdfPreview, open: openPdf, close: closePreview } = usePdfPreview();

  const handleExportPdf = () => {
    if (!data) return;
    openPdf(() =>
      generarReporteCobranzasPDF({
        fechaDesde: data.fecha_desde || fechaDesde,
        fechaHasta: data.fecha_hasta || fechaHasta,
        porCobrador,
        totales: tot,
        empresa: empresa || {},
      }),
    );
  };

  return (
    <>
      <Toolbar>
        <div>
          <label>Desde</label>
          <input
            type="date"
            value={fechaDesde}
            onChange={(e) => setFechaDesde(e.target.value)}
          />
        </div>
        <div>
          <label>Hasta</label>
          <input
            type="date"
            value={fechaHasta}
            onChange={(e) => setFechaHasta(e.target.value)}
          />
        </div>
        <RangeBtns>
          <QuickBtn onClick={() => aplicarRango(1)} type="button">
            Hoy
          </QuickBtn>
          <QuickBtn onClick={() => aplicarRango(7)} type="button">
            Últimos 7 días
          </QuickBtn>
          <QuickBtn onClick={() => aplicarRango(30)} type="button">
            Últimos 30 días
          </QuickBtn>
          <QuickBtn onClick={aplicarMesActual} type="button">
            Mes actual
          </QuickBtn>
        </RangeBtns>
        <ExportBtn
          type="button"
          onClick={handleExportPdf}
          disabled={isLoading || porCobrador.length === 0}
          title={
            porCobrador.length === 0
              ? "Sin datos para exportar"
              : "Exportar a PDF"
          }
        >
          <Icon icon="lucide:file-down" />
          PDF
        </ExportBtn>
      </Toolbar>
      <KpiGrid>
        <KpiCard $color="#3b82f6">
          <div className="icon-box">
            <Icon icon="lucide:users" />
          </div>
          <div>
            <div className="label">Cobradores</div>
            <div className="value">{tot.cobradores || 0}</div>
          </div>
        </KpiCard>
        <KpiCard $color="#22c55e">
          <div className="icon-box">
            <Icon icon="lucide:wallet" />
          </div>
          <div>
            <div className="label">Cobrado</div>
            <div className="value">{fmtMoney(tot.cobrado)}</div>
          </div>
        </KpiCard>
        <KpiCard $color="#f59e0b">
          <div className="icon-box">
            <Icon icon="lucide:file-text" />
          </div>
          <div>
            <div className="label">Recibos</div>
            <div className="value">{tot.recibos || 0}</div>
          </div>
        </KpiCard>
        <KpiCard $color="#94a3b8">
          <div className="icon-box">
            <Icon icon="lucide:layers" />
          </div>
          <div>
            <div className="label">Rendiciones</div>
            <div className="value">{tot.rendiciones || 0}</div>
          </div>
        </KpiCard>
      </KpiGrid>
      <DataTable>
        <table>
          <thead>
            <tr>
              <th>Cobrador</th>
              <th>Rend.</th>
              <th>Recibos</th>
              <th className="right">Efectivo</th>
              <th className="right">Cheque</th>
              <th className="right">Transferencia</th>
              <th className="right">Tarjeta</th>
              <th className="right">Declarado</th>
              <th className="right">Verificado</th>
              <th className="right">Diferencia</th>
            </tr>
          </thead>
          <tbody>
            {isLoading ? (
              <tr>
                <td colSpan={10}>
                  <Empty>
                    <Spinner icon="lucide:loader-2" />
                    Cargando…
                  </Empty>
                </td>
              </tr>
            ) : porCobrador.length === 0 ? (
              <tr>
                <td colSpan={10}>
                  <Empty>
                    <Icon icon="lucide:inbox" style={{ fontSize: "2rem" }} />
                    Sin cobranzas en este rango
                  </Empty>
                </td>
              </tr>
            ) : (
              <>
                {porCobrador.map((c) => {
                  const declarado = Number(c.declarado ?? c.total_cobrado ?? 0);
                  const verificado = Number(c.verificado ?? declarado);
                  const dif = Number(c.diferencia ?? verificado - declarado);
                  return (
                    <tr key={c.cobrador_id || c.cobrador}>
                      <td className="bold">{c.cobrador_nombre || c.cobrador || "-"}</td>
                      <td>{c.rendiciones}</td>
                      <td>{c.recibos}</td>
                      <td className="right">{fmtMoney(c.total_efectivo)}</td>
                      <td className="right">{fmtMoney(c.total_cheque)}</td>
                      <td className="right">{fmtMoney(c.total_transferencia)}</td>
                      <td className="right">{fmtMoney(c.total_tarjeta)}</td>
                      <td className="right">{fmtMoney(declarado)}</td>
                      <td className="right">{fmtMoney(verificado)}</td>
                      <td className="right">
                        <Badge $color={colorDif(dif)}>{fmtMoney(dif)}</Badge>
                      </td>
                    </tr>
                  );
                })}
                <tr style={{ fontWeight: 700, background: "rgba(148,163,184,0.08)" }}>
                  <td className="bold">TOTAL</td>
                  <td>{tot.rendiciones || 0}</td>
                  <td>{tot.recibos || 0}</td>
                  <td className="right">{fmtMoney(tot.total_efectivo)}</td>
                  <td className="right">{fmtMoney(tot.total_cheque)}</td>
                  <td className="right">{fmtMoney(tot.total_transferencia)}</td>
                  <td className="right">{fmtMoney(tot.total_tarjeta)}</td>
                  <td className="right">{fmtMoney(tot.total_cobrado)}</td>
                  <td className="right">{fmtMoney(tot.total_cobrado)}</td>
                  <td className="right">{fmtMoney(tot.diferencia)}</td>
                </tr>
              </>
            )}
          </tbody>
        </table>
      </DataTable>

      {pdfPreview && (
        <PdfPreviewModal
          preview={pdfPreview}
          onClose={closePreview}
        />
      )}
    </>
  );
};

// ── Modal de preview PDF ──────────────────────────────────────────
const PdfPreviewModal = ({ preview, onClose }) => {
  const handleDownload = () => preview.pdf.download(preview.fileName);
  const handlePrint = () => preview.pdf.print();
  return (
    <PdfOverlay onClick={onClose}>
      <PdfDialog onClick={(e) => e.stopPropagation()}>
        <PdfHeader>
          <div>
            <Icon icon="lucide:file-text" />
            <strong>Vista previa del reporte</strong>
          </div>
          <PdfHeaderActions>
            <PdfActionBtn onClick={handlePrint} title="Imprimir">
              <Icon icon="lucide:printer" /> Imprimir
            </PdfActionBtn>
            <PdfActionBtn $primary onClick={handleDownload} title="Descargar">
              <Icon icon="lucide:download" /> Descargar
            </PdfActionBtn>
            <PdfActionBtn onClick={onClose} title="Cerrar">
              <Icon icon="lucide:x" />
            </PdfActionBtn>
          </PdfHeaderActions>
        </PdfHeader>
        <PdfFrame title="Vista previa PDF" src={preview.url} />
      </PdfDialog>
    </PdfOverlay>
  );
};

// ── Tab 2: Pendientes ──────────────────────────────────────────────
const TabPendientes = () => {
  const { data, isLoading } = useReportePendientesQuery();
  const items = data || [];
  const empresa = useAuthStore((s) => s.empresa);
  const { pdfPreview, open: openPdf, close: closePreview } = usePdfPreview();
  const handleExportPdf = () =>
    openPdf(() =>
      generarReportePendientesPDF({ items, empresa: empresa || {} }),
    );
  return (
    <>
    <Toolbar>
      <ExportBtn
        type="button"
        onClick={handleExportPdf}
        disabled={isLoading || items.length === 0}
        title={items.length === 0 ? "Sin datos para exportar" : "Exportar a PDF"}
      >
        <Icon icon="lucide:file-down" />
        PDF
      </ExportBtn>
    </Toolbar>
    <DataTable>
      <table>
        <thead>
          <tr>
            <th>Código</th>
            <th>Cobrador</th>
            <th>Estado</th>
            <th>Enviada</th>
            <th>Antigüedad</th>
            <th className="right">Declarado</th>
            <th>Recibos</th>
          </tr>
        </thead>
        <tbody>
          {isLoading ? (
            <tr>
              <td colSpan={7}>
                <Empty>
                  <Spinner icon="lucide:loader-2" />
                  Cargando…
                </Empty>
              </td>
            </tr>
          ) : items.length === 0 ? (
            <tr>
              <td colSpan={7}>
                <Empty>
                  <Icon icon="lucide:check-circle" style={{ fontSize: "2rem", color: "#22c55e" }} />
                  No hay rendiciones pendientes
                </Empty>
              </td>
            </tr>
          ) : (
            items.map((r) => {
              const horas = Number(r.antiguedad_horas) || 0;
              const dias = Number(r.antiguedad_dias) || 0;
              const lbl = dias >= 1 ? `${dias} día${dias > 1 ? "s" : ""}` : `${horas}h`;
              return (
                <tr key={r.id}>
                  <td className="bold">{r.codigo || "-"}</td>
                  <td>{r.cobrador_nombre || r.cobrador?.nombre || "-"}</td>
                  <td>
                    <Badge $color={r.estado === "OBSERVADO" ? "#3b82f6" : "#f59e0b"}>
                      {r.estado}
                    </Badge>
                  </td>
                  <td>{fmtFecha(r.fecha_envio_tesoreria || r.fecha_rendicion)}</td>
                  <td>
                    <Badge $color={colorAntiguedad(horas)}>{lbl}</Badge>
                  </td>
                  <td className="right">{fmtMoney(r.total_declarado || r.monto_esperado)}</td>
                  <td>{r._count?.recibos_cobro ?? r.recibos_count ?? "-"}</td>
                </tr>
              );
            })
          )}
        </tbody>
      </table>
    </DataTable>
    {pdfPreview && <PdfPreviewModal preview={pdfPreview} onClose={closePreview} />}
    </>
  );
};

// ── Tab 3: Diferencias ─────────────────────────────────────────────
const TabDiferencias = () => {
  const [filters, setFilters] = useState({ nivel: "", fecha_desde: "", fecha_hasta: "" });
  const { data, isLoading } = useReporteDiferenciasQuery(filters);
  const items = data || [];
  const empresa = useAuthStore((s) => s.empresa);
  const { pdfPreview, open: openPdf, close: closePreview } = usePdfPreview();
  const handleExportPdf = () =>
    openPdf(() =>
      generarReporteDiferenciasPDF({
        items,
        filters,
        empresa: empresa || {},
      }),
    );
  return (
    <>
      <Toolbar>
        <div>
          <label>Nivel</label>
          <select
            value={filters.nivel}
            onChange={(e) => setFilters((s) => ({ ...s, nivel: e.target.value }))}
          >
            <option value="">Todos</option>
            <option value="menor">Menor</option>
            <option value="mayor">Mayor</option>
          </select>
        </div>
        <div>
          <label>Desde</label>
          <input
            type="date"
            value={filters.fecha_desde}
            onChange={(e) => setFilters((s) => ({ ...s, fecha_desde: e.target.value }))}
          />
        </div>
        <div>
          <label>Hasta</label>
          <input
            type="date"
            value={filters.fecha_hasta}
            onChange={(e) => setFilters((s) => ({ ...s, fecha_hasta: e.target.value }))}
          />
        </div>
        <ExportBtn
          type="button"
          onClick={handleExportPdf}
          disabled={isLoading || items.length === 0}
          title={items.length === 0 ? "Sin datos para exportar" : "Exportar a PDF"}
        >
          <Icon icon="lucide:file-down" />
          PDF
        </ExportBtn>
      </Toolbar>
      <DataTable>
        <table>
          <thead>
            <tr>
              <th>Código</th>
              <th>Fecha</th>
              <th>Cobrador</th>
              <th className="right">Declarado</th>
              <th className="right">Verificado</th>
              <th className="right">Diferencia</th>
              <th>Nivel</th>
            </tr>
          </thead>
          <tbody>
            {isLoading ? (
              <tr>
                <td colSpan={7}>
                  <Empty>
                    <Spinner icon="lucide:loader-2" />
                    Cargando…
                  </Empty>
                </td>
              </tr>
            ) : items.length === 0 ? (
              <tr>
                <td colSpan={7}>
                  <Empty>
                    <Icon icon="lucide:check-circle" style={{ fontSize: "2rem", color: "#22c55e" }} />
                    Sin diferencias detectadas
                  </Empty>
                </td>
              </tr>
            ) : (
              items.map((d) => {
                const dif = Number(d.diferencia) || 0;
                const c = colorDif(dif);
                return (
                  <tr key={d.id || d.rendicion_id}>
                    <td className="bold">{d.codigo}</td>
                    <td>{fmtFecha(d.fecha_rendicion)}</td>
                    <td>{d.cobrador_nombre || "-"}</td>
                    <td className="right">{fmtMoney(d.total_declarado)}</td>
                    <td className="right">{fmtMoney(d.total_verificado)}</td>
                    <td className="right">
                      <Badge $color={c}>{fmtMoney(dif)}</Badge>
                    </td>
                    <td>
                      <Badge $color={c}>{d.nivel || (Math.abs(dif) < 50000 ? "menor" : "mayor")}</Badge>
                    </td>
                  </tr>
                );
              })
            )}
          </tbody>
        </table>
      </DataTable>
      {pdfPreview && <PdfPreviewModal preview={pdfPreview} onClose={closePreview} />}
    </>
  );
};

// ── Tab 4: Comisiones a liquidar ───────────────────────────────────
const TabComisiones = () => {
  const { data, isLoading } = useReporteComisionesLiquidarQuery();
  const items = data || [];
  const total = items.reduce((acc, c) => acc + (Number(c.monto_comision) || 0), 0);
  const empresa = useAuthStore((s) => s.empresa);
  const { pdfPreview, open: openPdf, close: closePreview } = usePdfPreview();
  const handleExportPdf = () =>
    openPdf(() =>
      generarReporteComisionesPDF({ items, empresa: empresa || {} }),
    );

  return (
    <>
      <Toolbar>
        <ExportBtn
          type="button"
          onClick={handleExportPdf}
          disabled={isLoading || items.length === 0}
          title={items.length === 0 ? "Sin datos para exportar" : "Exportar a PDF"}
        >
          <Icon icon="lucide:file-down" />
          PDF
        </ExportBtn>
      </Toolbar>
      <KpiGrid>
        <KpiCard $color="#22c55e">
          <div className="icon-box">
            <Icon icon="lucide:badge-dollar-sign" />
          </div>
          <div>
            <div className="label">Total a liquidar</div>
            <div className="value">{fmtMoney(total)}</div>
          </div>
        </KpiCard>
        <KpiCard $color="#3b82f6">
          <div className="icon-box">
            <Icon icon="lucide:list" />
          </div>
          <div>
            <div className="label">Comisiones</div>
            <div className="value">{items.length}</div>
          </div>
        </KpiCard>
      </KpiGrid>
      <DataTable>
        <table>
          <thead>
            <tr>
              <th>Aprobada</th>
              <th>Cobrador</th>
              <th>Rendición</th>
              <th>Recibo</th>
              <th className="right">Base</th>
              <th className="right">%</th>
              <th className="right">Comisión</th>
            </tr>
          </thead>
          <tbody>
            {isLoading ? (
              <tr>
                <td colSpan={7}>
                  <Empty>
                    <Spinner icon="lucide:loader-2" />
                    Cargando…
                  </Empty>
                </td>
              </tr>
            ) : items.length === 0 ? (
              <tr>
                <td colSpan={7}>
                  <Empty>
                    <Icon icon="lucide:inbox" style={{ fontSize: "2rem" }} />
                    Sin comisiones pendientes de liquidación
                  </Empty>
                </td>
              </tr>
            ) : (
              items.map((c) => (
                <tr key={c.id}>
                  <td>{fmtFecha(c.fecha_aprobacion)}</td>
                  <td className="bold">{c.cobrador_nombre || "-"}</td>
                  <td>{c.rendicion_codigo || "-"}</td>
                  <td>{c.recibo_nro || c.recibo_codigo || "-"}</td>
                  <td className="right">{fmtMoney(c.monto_base)}</td>
                  <td className="right">{Number(c.porcentaje || 0).toFixed(2)}%</td>
                  <td className="right">
                    <Badge $color="#22c55e">{fmtMoney(c.monto_comision)}</Badge>
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </DataTable>
      {pdfPreview && <PdfPreviewModal preview={pdfPreview} onClose={closePreview} />}
    </>
  );
};

// ── Panel principal ────────────────────────────────────────────────
const TABS = [
  { key: "dia", label: "Cobranzas del día", icon: "lucide:calendar-days", Comp: TabCobranzasDia },
  { key: "pend", label: "Pendientes", icon: "lucide:clock", Comp: TabPendientes },
  { key: "dif", label: "Diferencias", icon: "lucide:alert-triangle", Comp: TabDiferencias },
  { key: "com", label: "Comisiones a liquidar", icon: "lucide:badge-dollar-sign", Comp: TabComisiones },
];

export const ReportesRendicionesPanel = () => {
  const [active, setActive] = useState("dia");
  const ActiveComp = TABS.find((t) => t.key === active)?.Comp || TabCobranzasDia;
  return (
    <Wrapper>
      <ScreenGuia
        titulo="¿Cómo leer los reportes de rendiciones?"
        intro="Cuatro vistas analíticas sobre el flujo de rendiciones: operación del día, cuello de botella en Tesorería, calidad de la verificación y comisiones a pagar."
        pasos={GUIA_PASOS}
        notas={GUIA_NOTAS}
      />
      <Title>
        <Icon icon="lucide:bar-chart-3" />
        Reportes de Rendiciones
      </Title>
      <Tabs>
        {TABS.map((t) => (
          <Tab key={t.key} $active={active === t.key} onClick={() => setActive(t.key)}>
            <Icon icon={t.icon} />
            {t.label}
          </Tab>
        ))}
      </Tabs>
      <ActiveComp />
    </Wrapper>
  );
};

export default ReportesRendicionesPanel;
