import { Icon } from "@iconify/react";
import {
  Alert,
  Box,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  IconButton,
  Tooltip,
  Typography,
} from "@mui/material";
import { useEffect, useMemo, useState } from "react";
import { toast } from "sonner";
import {
  actualizarDetalleIps,
  anularReporteIps,
  declararReporteIps,
  descargarReop,
  generarReporteIps,
  getLiquidaciones,
  getReporteIps,
  getReportesIps,
  pagarReporteIps,
} from "../../api/rrhh.service";
import { getTesCuentas } from "../../api/tes.service";
import { useConfirmDialog } from "../../hooks/useConfirmDialog";
import {
  Badge,
  Container,
  Divider,
  EmptyState,
  Field,
  FieldsGrid,
  Footer,
  FooterActionButton,
  FormHead,
  FormPanel,
  GhostButton,
  ListBody,
  ListPanel,
  RowActions,
  SectionTitle,
  TableWrap,
  ToolBar,
} from "../ui/FormShell";
import { TablePaginationBar } from "../_standards";
import { SearchableSelect } from "../ui/SearchableSelect";
import { RRHHGuia } from "./_shared/RRHHGuia";
import { RRHHPrereqChecklist } from "./_shared/RRHHPrereqChecklist";
import { RRHHEmptyState } from "./_shared/RRHHEmptyState";
import { hoyISO } from "../../utils/fecha";

const ESTADO_OPTIONS = [
  { id: "GENERADO", label: "Generado" },
  { id: "DECLARADO", label: "Declarado" },
  { id: "PAGADO", label: "Pagado" },
  { id: "ANULADO", label: "Anulado" },
];

const fmtMonto = (v) => Number(v || 0).toLocaleString("es-PY");
const fmtFecha = (v) => {
  if (!v) return "—";
  const d = new Date(v);
  return Number.isNaN(d.getTime()) ? "—" : d.toLocaleDateString("es-PY");
};
const fmtPeriodo = (a, m) => `${String(m).padStart(2, "0")}/${a}`;
const todayYmd = () => hoyISO();

export function ReportesIpsTab() {
  const { confirm, prompt, dialogs } = useConfirmDialog();

  const [data, setData] = useState([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [limit, setLimit] = useState(20);
  const [estadoFiltro, setEstadoFiltro] = useState("");
  const [loading, setLoading] = useState(false);

  // Generar
  const [showGenerar, setShowGenerar] = useState(false);
  const [liquidacionesCerradas, setLiquidacionesCerradas] = useState([]);
  const [generarForm, setGenerarForm] = useState({ liquidacion_id: "", observaciones: "" });
  const [generando, setGenerando] = useState(false);

  // Detalle
  const [detalle, setDetalle] = useState(null);
  const [detalleLoading, setDetalleLoading] = useState(false);
  // Cuentas de tesorería PYG (vacío si la empresa no usa Tesorería) + cuenta elegida al pagar.
  const [tesCuentas, setTesCuentas] = useState([]);
  const [pagarCuentaId, setPagarCuentaId] = useState("");
  // Edición inline de días: { [detalleId]: string } — solo aparece mientras el valor difiere del guardado
  const [editingDias, setEditingDias] = useState({});
  const [savingDias, setSavingDias] = useState({});

  const totalPages = useMemo(() => Math.max(1, Math.ceil(total / limit)), [total, limit]);
  const usaTesoreria = tesCuentas.length > 0;
  const cuentaTesoreriaOptions = tesCuentas.map((c) => ({ id: c.id, label: `${c.nombre} · PYG` }));

  const load = async () => {
    try {
      setLoading(true);
      const params = { page, limit };
      if (estadoFiltro) params.estado = estadoFiltro;
      const resp = await getReportesIps(params);
      setData(resp?.data || []);
      setTotal(resp?.total || 0);
    } catch {
      toast.error("Error al cargar reportes IPS");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => { load(); /* eslint-disable-next-line */ }, [page, limit, estadoFiltro]);

  useEffect(() => {
    getTesCuentas({ activo: true })
      .then((cuentas) => {
        const lista = Array.isArray(cuentas) ? cuentas : cuentas?.data || [];
        setTesCuentas(lista.filter((c) => c.activo !== false && c.moneda === "PYG"));
      })
      .catch(() => setTesCuentas([]));
  }, []);

  const cargarLiquidacionesCerradas = async () => {
    try {
      // Pedimos las últimas mensuales cerradas
      const resp = await getLiquidaciones({ page: 1, limit: 50, estado: "CERRADA" });
      const mensuales = (resp?.data || []).filter((l) => l.tipo === "MENSUAL");
      setLiquidacionesCerradas(mensuales);
    } catch {
      toast.error("No se pudieron cargar las liquidaciones cerradas");
    }
  };

  const liqOptions = useMemo(
    () =>
      liquidacionesCerradas.map((l) => ({
        id: l.id,
        label: `${fmtPeriodo(l.periodo_anio, l.periodo_mes)}${l.sucursal?.descripcion ? ` · ${l.sucursal.descripcion}` : " · todas"} — Gs. ${fmtMonto(l.total_ips_obrero)} IPS obrero`,
      })),
    [liquidacionesCerradas],
  );

  const handleAbrirGenerar = async () => {
    setGenerarForm({ liquidacion_id: "", observaciones: "" });
    await cargarLiquidacionesCerradas();
    setShowGenerar(true);
  };

  const handleGenerar = async () => {
    if (!generarForm.liquidacion_id) return toast.error("Elegí una liquidación cerrada");
    try {
      setGenerando(true);
      const rep = await generarReporteIps({
        liquidacion_id: generarForm.liquidacion_id,
        observaciones: generarForm.observaciones || undefined,
      });
      toast.success(`Reporte generado: ${rep.total_empleados} empleados aportantes`);
      setShowGenerar(false);
      await load();
      abrirDetalle(rep.id);
    } catch (error) {
      toast.error(error?.response?.data?.message || "Error al generar reporte");
    } finally {
      setGenerando(false);
    }
  };

  const abrirDetalle = async (id) => {
    setDetalleLoading(true);
    try {
      const rep = await getReporteIps(id);
      setPagarCuentaId(rep.cuenta_tesoreria_id || (tesCuentas.length === 1 ? tesCuentas[0].id : ""));
      setDetalle(rep);
    } catch {
      toast.error("No se pudo cargar el detalle");
      setDetalle(null);
    } finally {
      setDetalleLoading(false);
    }
  };
  const recargarDetalle = async () => {
    if (!detalle) return;
    setDetalle(await getReporteIps(detalle.id));
  };
  const cerrarDetalle = () => { setDetalle(null); load(); };

  const handleDescargarReop = async (rep) => {
    try {
      const blob = await descargarReop(rep.id);
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = `reop_ips_${rep.periodo_anio}-${String(rep.periodo_mes).padStart(2, "0")}.xlsx`;
      document.body.appendChild(a);
      a.click();
      a.remove();
      URL.revokeObjectURL(url);
    } catch {
      toast.error("No se pudo descargar el archivo REOP");
    }
  };

  const handleDeclarar = async (rep) => {
    const fecha = await prompt({
      title: "Marcar como declarado",
      message: `Reporte IPS ${fmtPeriodo(rep.periodo_anio, rep.periodo_mes)}. Registrá la fecha de declaración al IPS.`,
      label: "Fecha de declaración",
      type: "date",
      initialValue: todayYmd(),
      required: true,
      confirmText: "Declarar",
      confirmColor: "primary",
    });
    if (fecha === null) return;
    try {
      await declararReporteIps(rep.id, { fecha_declaracion: fecha || todayYmd() });
      toast.success("Marcado como DECLARADO");
      if (detalle?.id === rep.id) await recargarDetalle();
      else load();
    } catch (error) {
      toast.error(error?.response?.data?.message || "No se pudo declarar");
    }
  };

  const handlePagar = async (rep, cuentaTesoreriaId) => {
    let cuentaId = cuentaTesoreriaId || rep.cuenta_tesoreria_id || "";
    if (usaTesoreria && !cuentaId && tesCuentas.length === 1) cuentaId = tesCuentas[0].id;
    if (usaTesoreria && !cuentaId) {
      return toast.error("Elegí la cuenta de tesorería desde la que se paga el IPS (abrí el detalle para seleccionarla).");
    }
    const fecha = await prompt({
      title: "Marcar como pagado",
      message: usaTesoreria
        ? `Reporte IPS ${fmtPeriodo(rep.periodo_anio, rep.periodo_mes)}. Se registrará el egreso en Tesorería y el asiento (DEBE IPS a depositar / HABER Banco).`
        : `Reporte IPS ${fmtPeriodo(rep.periodo_anio, rep.periodo_mes)}. Registrá la fecha de pago al IPS.`,
      label: "Fecha de pago",
      type: "date",
      initialValue: todayYmd(),
      required: true,
      confirmText: "Marcar pagado",
      confirmColor: "success",
    });
    if (fecha === null) return;
    try {
      await pagarReporteIps(rep.id, {
        fecha_pago: fecha || todayYmd(),
        ...(cuentaId ? { cuenta_tesoreria_id: cuentaId } : {}),
      });
      toast.success("Marcado como PAGADO");
      if (detalle?.id === rep.id) await recargarDetalle();
      else load();
    } catch (error) {
      toast.error(error?.response?.data?.message || "No se pudo marcar como pagado");
    }
  };

  const handleAnular = async (rep) => {
    const comentario = await prompt({
      title: "Anular reporte IPS",
      message: `Reporte ${fmtPeriodo(rep.periodo_anio, rep.periodo_mes)}.`,
      label: "Motivo",
      placeholder: "Opcional",
      confirmText: "Anular",
      confirmColor: "warning",
    });
    if (comentario === null) return;
    try {
      await anularReporteIps(rep.id, comentario ? { comentario } : {});
      toast.success("Reporte anulado");
      if (detalle?.id === rep.id) cerrarDetalle();
      else load();
    } catch (error) {
      toast.error(error?.response?.data?.message || "No se pudo anular");
    }
  };

  const cancelarDias = (detId) =>
    setEditingDias((p) => { const n = { ...p }; delete n[detId]; return n; });

  const handleGuardarDias = async (det) => {
    const rawVal = editingDias[det.id];
    if (rawVal === undefined) return;
    const dias = parseInt(rawVal, 10);
    if (Number.isNaN(dias) || dias < 0 || dias > 31) {
      toast.error("Días inválidos (0–31)");
      cancelarDias(det.id);
      return;
    }
    setSavingDias((p) => ({ ...p, [det.id]: true }));
    try {
      await actualizarDetalleIps(detalle.id, det.id, { dias_trabajados: dias });
      toast.success("Días actualizados");
      cancelarDias(det.id);
      await recargarDetalle();
    } catch (e) {
      toast.error(e?.response?.data?.message || "No se pudieron guardar los días");
    } finally {
      setSavingDias((p) => { const n = { ...p }; delete n[det.id]; return n; });
    }
  };

  // ════════════════════════════════════════════════════════
  // Vista: generar
  // ════════════════════════════════════════════════════════
  if (showGenerar) {
    return (
      <Container>
        <FormPanel>
          <FormHead>
            <SectionTitle><Icon icon="lucide:file-plus-2" /> Generar reporte IPS</SectionTitle>
            <GhostButton onClick={() => setShowGenerar(false)}><Icon icon="lucide:x" /> Cerrar</GhostButton>
          </FormHead>
          <Alert severity="info" sx={{ mb: 2 }}>
            El reporte se arma a partir de una liquidación <strong>mensual CERRADA</strong>. Toma los empleados con IPS calculado y consolida base aportable + aportes (obrero 9%, patronal 16.5%, administrativo 1%).
          </Alert>
          <FieldsGrid $cols={4}>
            <Field $span={4}>
              <label>Liquidación mensual cerrada *</label>
              <SearchableSelect
                options={liqOptions}
                value={generarForm.liquidacion_id}
                onChange={(id) => setGenerarForm((p) => ({ ...p, liquidacion_id: id || "" }))}
                placeholder="Elegí el período…"
              />
            </Field>
            <Field $span={4}>
              <label>Observaciones</label>
              <input
                value={generarForm.observaciones}
                onChange={(e) => setGenerarForm((p) => ({ ...p, observaciones: e.target.value }))}
              />
            </Field>
          </FieldsGrid>
          <Footer>
            <FooterActionButton type="button" $variant="danger" disabled={generando} onClick={() => setShowGenerar(false)}>
              <Icon icon="lucide:x-circle" /> Cancelar
            </FooterActionButton>
            <FooterActionButton type="button" $variant="primary" disabled={generando || !generarForm.liquidacion_id} onClick={handleGenerar}>
              <Icon icon="lucide:check-circle" /> {generando ? "Generando…" : "Generar reporte"}
            </FooterActionButton>
          </Footer>
        </FormPanel>
        {dialogs}
      </Container>
    );
  }

  // ════════════════════════════════════════════════════════
  // Vista: detalle
  // ════════════════════════════════════════════════════════
  if (detalle) {
    const rep = detalle;
    const esGenerado = rep.estado === "GENERADO";
    const esDeclarado = rep.estado === "DECLARADO";
    const puedeDeclarar = esGenerado;
    const puedePagar = esGenerado || esDeclarado;
    const puedeAnular = rep.estado !== "PAGADO" && rep.estado !== "ANULADO";

    return (
      <Container>
        <FormPanel>
          <FormHead>
            <SectionTitle>
              <Icon icon="lucide:landmark" /> Reporte IPS {fmtPeriodo(rep.periodo_anio, rep.periodo_mes)}
              {" "}<Badge $state={rep.estado}>{rep.estado}</Badge>
            </SectionTitle>
            <Box sx={{ display: "flex", gap: 0.5 }}>
              <GhostButton onClick={() => handleDescargarReop(rep)}>
                <Icon icon="lucide:download" /> Descargar REOP (Excel)
              </GhostButton>
              {puedeDeclarar && (
                <GhostButton onClick={() => handleDeclarar(rep)}>
                  <Icon icon="lucide:file-check-2" /> Declarar
                </GhostButton>
              )}
              {puedePagar && (
                <FooterActionButton type="button" $variant="primary" onClick={() => handlePagar(rep, pagarCuentaId)}>
                  <Icon icon="lucide:check-circle" /> Marcar pagado
                </FooterActionButton>
              )}
              {puedeAnular && (
                <GhostButton onClick={() => handleAnular(rep)}>
                  <Icon icon="lucide:ban" /> Anular
                </GhostButton>
              )}
              <GhostButton onClick={cerrarDetalle}><Icon icon="lucide:arrow-left" /> Volver</GhostButton>
            </Box>
          </FormHead>

          {puedePagar && usaTesoreria && (
            <Box sx={{ mb: 1.5 }}>
              <FieldsGrid $cols={4}>
                <Field $span={2}>
                  <label>Cuenta de tesorería (pago del IPS) *</label>
                  <SearchableSelect options={cuentaTesoreriaOptions} value={pagarCuentaId}
                    onChange={(id) => setPagarCuentaId(id || "")}
                    placeholder="Desde qué cuenta se paga…" />
                  <Typography variant="caption" color="text.disabled">
                    Al marcar pagado se registra el egreso en Tesorería y el asiento DEBE «IPS a depositar» / HABER Banco.
                  </Typography>
                </Field>
              </FieldsGrid>
            </Box>
          )}

          <FieldsGrid $cols={4}>
            <Field><label>Empleados aportantes</label><input readOnly value={rep.total_empleados} /></Field>
            <Field><label>Base aportable</label><input readOnly value={fmtMonto(rep.total_base_aportable)} /></Field>
            <Field><label>Aporte obrero (9%)</label><input readOnly value={fmtMonto(rep.total_aporte_obrero)} /></Field>
            <Field><label>Aporte patronal (16.5%)</label><input readOnly value={fmtMonto(rep.total_aporte_patronal)} /></Field>
            <Field><label>Aporte admin. (1%)</label><input readOnly value={fmtMonto(rep.total_aporte_admin)} /></Field>
            <Field><label>TOTAL A DEPOSITAR</label><input readOnly value={fmtMonto(rep.total_a_depositar)} /></Field>
            <Field><label>N° planilla IPS</label><input readOnly value={rep.numero_planilla_ips || "—"} /></Field>
            <Field><label>Generado</label><input readOnly value={fmtFecha(rep.created_at)} /></Field>
            <Field><label>Declarado</label><input readOnly value={fmtFecha(rep.fecha_declaracion)} /></Field>
            <Field><label>Pagado</label><input readOnly value={fmtFecha(rep.fecha_pago)} /></Field>
          </FieldsGrid>

          <Divider />
          <SectionTitle>
            <Icon icon="lucide:users" /> Detalle por empleado ({rep.detalles?.length || 0})
          </SectionTitle>
          {(!rep.detalles || rep.detalles.length === 0) ? (
            <EmptyState>Sin filas</EmptyState>
          ) : (
            <TableWrap>
              <table>
                <thead>
                  <tr>
                    <th>N° IPS</th>
                    <th>Cédula</th>
                    <th>Empleado</th>
                    <th>Régimen</th>
                    <th style={{ textAlign: "center" }}>
                      Días{esGenerado && <span style={{ fontSize: 10, fontWeight: 400, marginLeft: 4, opacity: 0.6 }}>(editable)</span>}
                    </th>
                    <th style={{ textAlign: "right" }}>Base aportable</th>
                    <th style={{ textAlign: "right" }}>Obrero (9%)</th>
                    <th style={{ textAlign: "right" }}>Patronal (16.5%)</th>
                    <th style={{ textAlign: "right" }}>Admin. (1%)</th>
                    <th style={{ textAlign: "right" }}>Total</th>
                  </tr>
                </thead>
                <tbody>
                  {rep.detalles.map((d) => (
                    <tr key={d.id}>
                      <td>{d.numero_ips || "—"}</td>
                      <td>{d.cedula}</td>
                      <td>{d.apellidos}, {d.nombres}</td>
                      <td>{d.regimen_ips || "—"}</td>
                      <td style={{ textAlign: "center", padding: "4px 6px" }}>
                        {esGenerado ? (
                          <div style={{ display: "inline-flex", alignItems: "center", gap: 4 }}>
                            <input
                              type="number"
                              min={0}
                              max={31}
                              disabled={savingDias[d.id]}
                              value={editingDias[d.id] !== undefined ? editingDias[d.id] : (d.dias_trabajados ?? "")}
                              onChange={(e) => {
                                const v = e.target.value;
                                const original = String(d.dias_trabajados ?? "");
                                if (v === original) cancelarDias(d.id);
                                else setEditingDias((p) => ({ ...p, [d.id]: v }));
                              }}
                              onKeyDown={(e) => {
                                if (e.key === "Enter") handleGuardarDias(d);
                                if (e.key === "Escape") cancelarDias(d.id);
                              }}
                              style={{
                                width: 48,
                                textAlign: "center",
                                padding: "3px 4px",
                                fontSize: 13,
                                border: `1px solid ${editingDias[d.id] !== undefined ? "#6366f1" : "rgba(148,163,184,0.35)"}`,
                                borderRadius: 6,
                                background: "transparent",
                                color: "inherit",
                                outline: "none",
                                transition: "border-color 0.15s",
                              }}
                            />
                            {editingDias[d.id] !== undefined && (
                              <button
                                type="button"
                                disabled={savingDias[d.id]}
                                onClick={() => handleGuardarDias(d)}
                                title="Confirmar"
                                style={{
                                  display: "inline-flex",
                                  alignItems: "center",
                                  justifyContent: "center",
                                  width: 22,
                                  height: 22,
                                  borderRadius: 5,
                                  border: "none",
                                  background: "#22c55e",
                                  color: "#fff",
                                  cursor: savingDias[d.id] ? "wait" : "pointer",
                                  fontSize: 13,
                                  flexShrink: 0,
                                  opacity: savingDias[d.id] ? 0.6 : 1,
                                }}
                              >
                                ✓
                              </button>
                            )}
                          </div>
                        ) : (d.dias_trabajados ?? "—")}
                      </td>
                      <td style={{ textAlign: "right", fontFamily: "monospace" }}>{fmtMonto(d.base_aportable)}</td>
                      <td style={{ textAlign: "right", fontFamily: "monospace" }}>{fmtMonto(d.aporte_obrero)}</td>
                      <td style={{ textAlign: "right", fontFamily: "monospace" }}>{fmtMonto(d.aporte_patronal)}</td>
                      <td style={{ textAlign: "right", fontFamily: "monospace" }}>{fmtMonto(d.aporte_admin)}</td>
                      <td style={{ textAlign: "right", fontFamily: "monospace", fontWeight: 600 }}>{fmtMonto(d.total_aporte)}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </TableWrap>
          )}
        </FormPanel>
        {dialogs}
      </Container>
    );
  }

  // ════════════════════════════════════════════════════════
  // Vista: listado
  // ════════════════════════════════════════════════════════
  return (
    <Container id="rrhh-ips-list-view">
      <RRHHGuia seccion="ips" />
      <RRHHPrereqChecklist tabKey="ips" />
      <ListPanel>
        <ListBody>
          <ToolBar id="rrhh-ips-toolbar">
            <Box sx={{ minWidth: 200 }}>
              <SearchableSelect label="Estado" options={ESTADO_OPTIONS} value={estadoFiltro}
                onChange={(id) => { setEstadoFiltro(id || ""); setPage(1); }}
                placeholder="Todos los estados" />
            </Box>
            <Tooltip title="Refrescar">
              <GhostButton onClick={load} disabled={loading}><Icon icon="lucide:refresh-cw" /></GhostButton>
            </Tooltip>
            <Box sx={{ flex: 1 }} />
            <FooterActionButton id="rrhh-ips-generar-btn" type="button" $variant="primary" onClick={handleAbrirGenerar}>
              <Icon icon="lucide:plus" /> Generar reporte
            </FooterActionButton>
          </ToolBar>

          <div id="rrhh-ips-list-content">
            {loading || detalleLoading ? (
              <EmptyState>Cargando…</EmptyState>
            ) : data.length === 0 ? (
              <RRHHEmptyState
                icon="lucide:landmark"
                titulo="Sin reportes IPS generados"
                descripcion="Los reportes IPS (REOP) se generan desde una liquidación mensual cerrada y contienen los aportes de cada empleado para presentar al IPS."
                ctaLabel="Generar reporte IPS"
                onCta={handleAbrirGenerar}
                guiaSeccion="ips"
              />
            ) : (
              <TableWrap id="rrhh-ips-table">
                <table>
                  <thead>
                    <tr>
                      <th>Período</th>
                      <th style={{ textAlign: "right" }}>Empleados</th>
                      <th style={{ textAlign: "right" }}>Base aportable</th>
                      <th style={{ textAlign: "right" }}>Obrero</th>
                      <th style={{ textAlign: "right" }}>Patronal</th>
                      <th style={{ textAlign: "right" }}>Admin.</th>
                      <th style={{ textAlign: "right" }}>Total</th>
                      <th>Estado</th>
                      <th>Declarado</th>
                      <th>Pagado</th>
                      <th style={{ textAlign: "center" }}>Acciones</th>
                    </tr>
                  </thead>
                  <tbody>
                    {data.map((rep) => {
                      const esGen = rep.estado === "GENERADO";
                      const esDecl = rep.estado === "DECLARADO";
                      return (
                        <tr key={rep.id}>
                          <td>{fmtPeriodo(rep.periodo_anio, rep.periodo_mes)}</td>
                          <td style={{ textAlign: "right" }}>{rep.total_empleados}</td>
                          <td style={{ textAlign: "right", fontFamily: "monospace" }}>{fmtMonto(rep.total_base_aportable)}</td>
                          <td style={{ textAlign: "right", fontFamily: "monospace" }}>{fmtMonto(rep.total_aporte_obrero)}</td>
                          <td style={{ textAlign: "right", fontFamily: "monospace" }}>{fmtMonto(rep.total_aporte_patronal)}</td>
                          <td style={{ textAlign: "right", fontFamily: "monospace" }}>{fmtMonto(rep.total_aporte_admin)}</td>
                          <td style={{ textAlign: "right", fontFamily: "monospace", fontWeight: 600 }}>{fmtMonto(rep.total_a_depositar)}</td>
                          <td><Badge $state={rep.estado}>{rep.estado}</Badge></td>
                          <td>{fmtFecha(rep.fecha_declaracion)}</td>
                          <td>{fmtFecha(rep.fecha_pago)}</td>
                          <td style={{ textAlign: "center" }}>
                            <RowActions>
                              <Tooltip title="Abrir">
                                <IconButton size="small" onClick={() => abrirDetalle(rep.id)}>
                                  <Icon icon="lucide:eye" width={16} />
                                </IconButton>
                              </Tooltip>
                              <Tooltip title="Descargar REOP">
                                <IconButton size="small" color="primary" onClick={() => handleDescargarReop(rep)}>
                                  <Icon icon="lucide:download" width={16} />
                                </IconButton>
                              </Tooltip>
                              {esGen && (
                                <Tooltip title="Marcar declarado">
                                  <IconButton size="small" color="info" onClick={() => handleDeclarar(rep)}>
                                    <Icon icon="lucide:file-check-2" width={16} />
                                  </IconButton>
                                </Tooltip>
                              )}
                              {(esGen || esDecl) && (
                                <Tooltip title="Marcar pagado">
                                  <IconButton size="small" color="success" onClick={() => handlePagar(rep)}>
                                    <Icon icon="lucide:check-circle" width={16} />
                                  </IconButton>
                                </Tooltip>
                              )}
                              {rep.estado !== "PAGADO" && rep.estado !== "ANULADO" && (
                                <Tooltip title="Anular">
                                  <IconButton size="small" color="error" onClick={() => handleAnular(rep)}>
                                    <Icon icon="lucide:ban" width={16} />
                                  </IconButton>
                                </Tooltip>
                              )}
                            </RowActions>
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </TableWrap>
            )}
          </div>

          <TablePaginationBar
            page={page}
            totalPages={totalPages}
            onPageChange={setPage}
            total={total}
            shown={data.length}
            noun="reportes"
            rowsPerPage={limit}
            onRowsPerPageChange={(n) => {
              setLimit(n);
              setPage(1);
            }}
          />
        </ListBody>
      </ListPanel>
      {dialogs}
    </Container>
  );
}
