import { Icon } from "@iconify/react";
import {
  Alert,
  Box,
  Button,
  Card,
  CardContent,
  Chip,
  CircularProgress,
  Grid,
  IconButton,
  Paper,
  Skeleton,
  Stack,
  Tab,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Tabs,
  Tooltip,
  Typography,
} from "@mui/material";
import { useMemo, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { useCallback } from "react";
import { getRendicionPDF } from "../api/rendicion-viaticos.service";
import { EmptyState, PDFPreviewDialog } from "../components/_standards";
import { usePermission } from "../hooks/usePermission";
import { getEstadoRendicion } from "../components/_standards/enums/estadosRendicionViatico";
import { fmtMoneda } from "../components/_standards/enums/monedas";
import { useConfirmDialog } from "../hooks/useConfirmDialog";
import {
  useAnularRendicionMutation,
  useAprobarRendicionMutation,
  useQuitarGastoRendicionMutation,
  useRechazarRendicionMutation,
  useRendicionQuery,
} from "../tanstack/RendicionViaticosStack";
import { fmtFechaCalendario, fmtFechaHora } from "../utils/fecha";
import { AgregarAdelantoDialog } from "../components/organismos/RendicionViaticosDesign/AgregarAdelantoDialog";
import { AgregarGastoRendicionDialog } from "../components/organismos/RendicionViaticosDesign/AgregarGastoRendicionDialog";
import { CerrarRendicionDialog } from "../components/organismos/RendicionViaticosDesign/CerrarRendicionDialog";
import { saldoRendicion } from "../components/organismos/RendicionViaticosDesign/saldoRendicion";
import { useConfigViaticosQuery } from "../tanstack/RendicionViaticosStack";

export function RendicionViaticoDetallePage() {
  const { id } = useParams();
  const navigate = useNavigate();
  const { confirm, dialogs } = useConfirmDialog();
  const { data: rendicion, isLoading } = useRendicionQuery(id);
  const aprobarMut = useAprobarRendicionMutation();
  const rechazarMut = useRechazarRendicionMutation();
  const anularMut = useAnularRendicionMutation();
  const quitarGastoMut = useQuitarGastoRendicionMutation();
  const [tab, setTab] = useState(0);
  const [dialogAdelanto, setDialogAdelanto] = useState(false);
  const [dialogGasto, setDialogGasto] = useState(false);
  const [dialogCierre, setDialogCierre] = useState(false);
  const [pdfOpen, setPdfOpen] = useState(false);
  const fetchPDF = useCallback(() => getRendicionPDF(id), [id]);
  const { data: config } = useConfigViaticosQuery();

  const monedaCodigo = rendicion?.moneda?.codigo || "PYG";
  // Lo que falta saldar (0 si la devolución o el reintegro ya se hicieron).
  const saldoVista = saldoRendicion(rendicion, monedaCodigo);
  const estadoInfo = useMemo(() => (rendicion ? getEstadoRendicion(rendicion.estado) : null), [rendicion]);

  const { can } = usePermission("RRHH");
  const canCrear = can("RH_VIA_RENDICION_CREAR");
  const canAprobar = can("RH_VIA_RENDICION_APROBAR");
  const canAnular = can("RH_VIA_RENDICION_ANULAR");
  const canCargarGasto = can("RH_VIA_GASTO_CARGAR");
  const canCerrar = can("RH_VIA_CIERRE_EJECUTAR");

  const puedeAgregarAdelanto = useMemo(() => {
    return canCrear && rendicion && ["ADELANTO_PAGADO", "SIN_ADELANTO"].includes(rendicion.estado);
  }, [rendicion, canCrear]);
  const puedeAgregarGasto = useMemo(() => {
    return canCargarGasto && rendicion && ["ADELANTO_PAGADO", "SIN_ADELANTO", "RENDIDA"].includes(rendicion.estado);
  }, [rendicion, canCargarGasto]);
  const puedeCerrar = useMemo(() => {
    return canCerrar && rendicion && ["ADELANTO_PAGADO", "SIN_ADELANTO", "RENDIDA"].includes(rendicion.estado);
  }, [rendicion, canCerrar]);

  const puedeAprobar = canAprobar && rendicion?.estado === "PENDIENTE_APROBACION";
  const puedeAnular = canAnular && rendicion && !["CERRADA", "ANULADA"].includes(rendicion.estado);

  const handleQuitarGasto = async (gasto) => {
    const ok = await confirm({
      title: "Anular gasto",
      message: `Se anulará el gasto ${gasto.numero_factura || gasto.descripcion || "sin número"}. Los asientos contables se revertirán y se recalculará el saldo.`,
      confirmText: "Anular gasto",
      confirmColor: "error",
    });
    if (ok) {
      quitarGastoMut.mutate({ id: rendicion.id, gastoId: gasto.id, motivo: "Anulado desde rendición" });
    }
  };

  const handleAprobar = async () => {
    const ok = await confirm({
      title: "Aprobar rendición",
      message: "Al aprobar, se ejecutará el pago del adelanto y se generarán asientos contables + movimientos de tesorería.",
      confirmText: "Aprobar",
    });
    if (ok) aprobarMut.mutate(id);
  };

  const handleRechazar = async () => {
    const ok = await confirm({
      title: "Rechazar rendición",
      message: "Al rechazar, la rendición pasa a estado ANULADA y no se ejecuta el adelanto.",
      confirmText: "Rechazar",
      confirmColor: "warning",
    });
    if (ok) rechazarMut.mutate({ id, motivo: "Rechazada por supervisor" });
  };

  const handleAnular = async () => {
    const ok = await confirm({
      title: "Anular rendición",
      message: "Se anularán todos los adelantos ejecutados, revirtiendo asientos contables y movimientos de tesorería. Esta acción no se puede deshacer.",
      confirmText: "Anular",
      confirmColor: "error",
    });
    if (ok) anularMut.mutate({ id, motivo: "Anulada manualmente" });
  };

  if (isLoading) {
    return (
      <Box p={2}>
        <Skeleton height={60} />
        <Skeleton height={200} />
        <Skeleton height={400} />
      </Box>
    );
  }

  if (!rendicion) {
    return (
      <Box p={2}>
        <EmptyState
          icon="mdi:alert"
          title="Rendición no encontrada"
          description="Puede que haya sido anulada o no tengas permiso para verla."
          actionLabel="Volver al listado"
          onAction={() => navigate("/rendicion-viaticos")}
        />
      </Box>
    );
  }

  return (
    <Box p={2}>
      <Stack direction="row" alignItems="center" spacing={1} mb={1.5}>
        <Button
          size="small"
          variant="outlined"
          startIcon={<Icon icon="mdi:arrow-left" />}
          onClick={() => navigate("/rendicion-viaticos")}
        >
          Volver
        </Button>
        <Typography variant="h6" sx={{ ml: 1 }}>
          Rendición {rendicion.numero_rendicion}
        </Typography>
        <Chip
          size="small"
          color={estadoInfo?.color}
          variant="outlined"
          icon={<Icon icon={estadoInfo?.icon} />}
          label={estadoInfo?.label}
          sx={{ ml: 1 }}
        />
      </Stack>

      {/* Info del empleado + KPIs */}
      <Grid container spacing={2} sx={{ mb: 2 }}>
        <Grid size={{ xs: 12, md: 4 }}>
          <Card variant="outlined" sx={{ height: "100%" }}>
            <CardContent>
              <Typography variant="caption" color="text.secondary" sx={{ display: "flex", alignItems: "center", gap: 0.5 }}>
                <Icon icon="mdi:account" width={16} /> EMPLEADO
              </Typography>
              <Typography variant="body1" fontWeight={700} sx={{ mt: 0.5 }}>
                {rendicion.empleado?.nombres} {rendicion.empleado?.apellidos}
              </Typography>
              <Typography variant="caption" color="text.secondary">
                CI {rendicion.empleado?.cedula_identidad}
              </Typography>
            </CardContent>
          </Card>
        </Grid>
        <Grid size={{ xs: 6, md: 2 }}>
          <Card variant="outlined" sx={{ height: "100%" }}>
            <CardContent>
              <Typography variant="caption" color="text.secondary" sx={{ display: "flex", alignItems: "center", gap: 0.5 }}>
                <Icon icon="mdi:cash-plus" width={16} /> ADELANTADO
              </Typography>
              <Typography variant="h6" fontWeight={700} color="info.main">
                {fmtMoneda(Number(rendicion.monto_adelanto_total || 0), monedaCodigo)}
              </Typography>
            </CardContent>
          </Card>
        </Grid>
        <Grid size={{ xs: 6, md: 2 }}>
          <Card variant="outlined" sx={{ height: "100%" }}>
            <CardContent>
              <Typography variant="caption" color="text.secondary" sx={{ display: "flex", alignItems: "center", gap: 0.5 }}>
                <Icon icon="mdi:receipt" width={16} /> RENDIDO
              </Typography>
              <Typography variant="h6" fontWeight={700} color="primary.main">
                {fmtMoneda(Number(rendicion.monto_rendido_total || 0), monedaCodigo)}
              </Typography>
            </CardContent>
          </Card>
        </Grid>
        <Grid size={{ xs: 12, md: 4 }}>
          <Card variant="outlined" sx={{ height: "100%", borderColor: saldoVista.borde }}>
            <CardContent>
              <Typography variant="caption" color="text.secondary" sx={{ display: "flex", alignItems: "center", gap: 0.5 }}>
                <Icon icon="mdi:scale-balance" width={16} /> SALDO PENDIENTE
              </Typography>
              <Typography variant="h5" fontWeight={700} color={saldoVista.color}>
                {fmtMoneda(Math.abs(saldoVista.pendiente), monedaCodigo)}
              </Typography>
              <Typography variant="caption" color="text.secondary">
                {saldoVista.texto}
              </Typography>
            </CardContent>
          </Card>
        </Grid>
      </Grid>

      {/* Metadatos del viaje */}
      <Paper variant="outlined" sx={{ p: 2, mb: 2, borderRadius: 2 }}>
        <Grid container spacing={2}>
          <Grid size={{ xs: 12, md: 6 }}>
            <Typography variant="caption" color="text.secondary">
              Concepto
            </Typography>
            <Typography variant="body2" fontWeight={600}>
              {rendicion.concepto}
            </Typography>
          </Grid>
          <Grid size={{ xs: 6, md: 2 }}>
            <Typography variant="caption" color="text.secondary">
              Fecha inicio
            </Typography>
            <Typography variant="body2">{fmtFechaCalendario(rendicion.fecha_inicio)}</Typography>
          </Grid>
          <Grid size={{ xs: 6, md: 2 }}>
            <Typography variant="caption" color="text.secondary">
              Fecha fin
            </Typography>
            <Typography variant="body2">{fmtFechaCalendario(rendicion.fecha_fin)}</Typography>
          </Grid>
          <Grid size={{ xs: 6, md: 2 }}>
            <Typography variant="caption" color="text.secondary">
              Moneda
            </Typography>
            <Typography variant="body2">
              {monedaCodigo}
              {Number(rendicion.cotizacion) !== 1 && ` · TC ${rendicion.cotizacion}`}
            </Typography>
          </Grid>
          {rendicion.observaciones && (
            <Grid size={12}>
              <Typography variant="caption" color="text.secondary">
                Observaciones
              </Typography>
              <Typography variant="body2">{rendicion.observaciones}</Typography>
            </Grid>
          )}
        </Grid>
      </Paper>

      {/* Acciones */}
      <Stack direction="row" spacing={1} mb={2} sx={{ flexWrap: "wrap", gap: 1 }}>
        {puedeAprobar && (
          <>
            <Button
              variant="contained"
              color="success"
              startIcon={<Icon icon="mdi:check" />}
              onClick={handleAprobar}
              disabled={aprobarMut.isPending}
            >
              Aprobar
            </Button>
            <Button
              variant="outlined"
              color="warning"
              startIcon={<Icon icon="mdi:close" />}
              onClick={handleRechazar}
              disabled={rechazarMut.isPending}
            >
              Rechazar
            </Button>
          </>
        )}
        {puedeAgregarAdelanto && (
          <Button
            variant="outlined"
            startIcon={<Icon icon="mdi:plus" />}
            onClick={() => setDialogAdelanto(true)}
          >
            Agregar adelanto
          </Button>
        )}
        {puedeCerrar && (
          <Button
            variant="contained"
            color="success"
            startIcon={<Icon icon="mdi:check-circle" />}
            onClick={() => setDialogCierre(true)}
          >
            Cerrar rendición
          </Button>
        )}
        <Button
          variant="outlined"
          startIcon={<Icon icon="mdi:file-pdf-box" />}
          onClick={() => setPdfOpen(true)}
          sx={{ ml: "auto" }}
        >
          PDF
        </Button>
        {puedeAnular && (
          <Button
            variant="outlined"
            color="error"
            startIcon={<Icon icon="mdi:cancel" />}
            onClick={handleAnular}
            disabled={anularMut.isPending}
          >
            Anular
          </Button>
        )}
      </Stack>

      {/* Tabs */}
      <Paper variant="outlined" sx={{ borderRadius: 2 }}>
        <Tabs value={tab} onChange={(_, v) => setTab(v)} sx={{ borderBottom: 1, borderColor: "divider" }}>
          <Tab icon={<Icon icon="mdi:cash-plus" />} iconPosition="start" label={`Anticipos (${rendicion.adelantos?.length || 0})`} />
          <Tab icon={<Icon icon="mdi:receipt-text" />} iconPosition="start" label={`Gastos (${rendicion.gastos?.length || 0})`} />
          <Tab icon={<Icon icon="mdi:check-circle-outline" />} iconPosition="start" label={rendicion.estado === "CERRADA" ? "Cierre ✓" : "Cierre"} />
        </Tabs>

        {tab === 0 && (
          <Box sx={{ p: 2 }}>
            {rendicion.adelantos?.length === 0 ? (
              <EmptyState
                icon="mdi:cash-plus"
                title="Sin adelantos registrados"
                description={
                  rendicion.sin_adelanto
                    ? "Esta rendición se marcó como sin adelanto previo. La empresa reembolsará al cerrar."
                    : "Agregá el primer adelanto para arrancar."
                }
                actionLabel={puedeAgregarAdelanto ? "Agregar adelanto" : undefined}
                onAction={puedeAgregarAdelanto ? () => setDialogAdelanto(true) : undefined}
              />
            ) : (
              <TableContainer>
                <Table size="small">
                  <TableHead>
                    <TableRow>
                      <TableCell sx={{ fontWeight: 600 }}>Fecha</TableCell>
                      <TableCell sx={{ fontWeight: 600 }}>Medio de pago</TableCell>
                      <TableCell sx={{ fontWeight: 600 }}>Cuenta origen</TableCell>
                      <TableCell sx={{ fontWeight: 600 }}>N° operación</TableCell>
                      <TableCell sx={{ fontWeight: 600 }} align="right">Monto</TableCell>
                      <TableCell sx={{ fontWeight: 600 }} align="center">Ejecutado</TableCell>
                    </TableRow>
                  </TableHead>
                  <TableBody>
                    {rendicion.adelantos.map((ade) => (
                      <TableRow key={ade.id} hover>
                        <TableCell>{fmtFechaCalendario(ade.fecha)}</TableCell>
                        <TableCell>{ade.medio_pago?.descripcion || "—"}</TableCell>
                        <TableCell>{ade.tes_cuenta?.nombre || "—"}</TableCell>
                        <TableCell>{ade.numero_operacion || "—"}</TableCell>
                        <TableCell align="right">
                          <Typography fontWeight={700} color="success.main">
                            {fmtMoneda(Number(ade.monto), monedaCodigo)}
                          </Typography>
                        </TableCell>
                        <TableCell align="center">
                          {ade.tes_movimiento_id ? (
                            <Tooltip title="Asiento contable + movimiento de tesorería generados" enterDelay={300}>
                              <Icon icon="mdi:check-circle" color="green" />
                            </Tooltip>
                          ) : (
                            <Tooltip title="Pendiente de ejecución (esperando aprobación)" enterDelay={300}>
                              <Icon icon="mdi:clock-outline" color="orange" />
                            </Tooltip>
                          )}
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </TableContainer>
            )}
          </Box>
        )}

        {tab === 1 && (
          <Box sx={{ p: 2 }}>
            <Stack direction="row" justifyContent="space-between" alignItems="center" mb={2}>
              <Typography variant="body2" color="text.secondary">
                {rendicion.gastos?.length || 0} gasto(s) registrado(s) · Total{" "}
                <strong>{fmtMoneda(Number(rendicion.monto_rendido_total || 0), monedaCodigo)}</strong>
              </Typography>
              {puedeAgregarGasto && (
                <Button
                  variant="contained"
                  size="small"
                  startIcon={<Icon icon="mdi:plus" />}
                  onClick={() => setDialogGasto(true)}
                >
                  Nuevo gasto
                </Button>
              )}
            </Stack>

            {(!rendicion.gastos || rendicion.gastos.length === 0) ? (
              <EmptyState
                icon="mdi:receipt-text-outline"
                title="Sin gastos registrados"
                description="Cargá el primer gasto de la rendición. Podés elegir si tiene factura legal (IVA crédito) o solo comprobante interno."
                actionLabel={puedeAgregarGasto ? "Nuevo gasto" : undefined}
                onAction={puedeAgregarGasto ? () => setDialogGasto(true) : undefined}
              />
            ) : (
              <TableContainer>
                <Table size="small">
                  <TableHead>
                    <TableRow>
                      <TableCell sx={{ fontWeight: 600 }}>Fecha</TableCell>
                      <TableCell sx={{ fontWeight: 600 }}>Proveedor / Descripción</TableCell>
                      <TableCell sx={{ fontWeight: 600 }}>Nº factura</TableCell>
                      <TableCell sx={{ fontWeight: 600 }}>Tipo</TableCell>
                      <TableCell sx={{ fontWeight: 600 }} align="center">Deducible</TableCell>
                      <TableCell sx={{ fontWeight: 600 }} align="right">Total</TableCell>
                      {puedeAgregarGasto && <TableCell align="center" />}
                    </TableRow>
                  </TableHead>
                  <TableBody>
                    {rendicion.gastos.map((g) => {
                      const tipoLabel = g.gasto_det?.[0]?.tipo_gasto?.descripcion || "—";
                      const provNombre = g.proveedores?.personas?.razon_social || g.descripcion || "Sin proveedor";
                      return (
                        <TableRow key={g.id} hover>
                          <TableCell>{fmtFechaCalendario(g.fecha_emision)}</TableCell>
                          <TableCell>
                            <Typography variant="body2" fontWeight={600}>
                              {provNombre}
                            </Typography>
                            {g.descripcion && g.descripcion !== provNombre && (
                              <Typography variant="caption" color="text.secondary">
                                {g.descripcion}
                              </Typography>
                            )}
                          </TableCell>
                          <TableCell>
                            {g.numero_factura ? (
                              <Typography sx={{ fontFamily: "monospace" }}>
                                {g.establecimiento && `${g.establecimiento}-${g.punto_expedicion}-`}
                                {g.numero_factura}
                              </Typography>
                            ) : (
                              <Chip size="small" label="Sin factura" variant="outlined" color="warning" />
                            )}
                          </TableCell>
                          <TableCell>{tipoLabel}</TableCell>
                          <TableCell align="center">
                            {g.deducible ? (
                              <Chip size="small" icon={<Icon icon="mdi:check" />} label="Sí" color="success" variant="outlined" />
                            ) : (
                              <Chip size="small" icon={<Icon icon="mdi:close" />} label="No" color="default" variant="outlined" />
                            )}
                          </TableCell>
                          <TableCell align="right">
                            <Typography fontWeight={700}>
                              {fmtMoneda(Number(g.total || 0), monedaCodigo)}
                            </Typography>
                          </TableCell>
                          {puedeAgregarGasto && (
                            <TableCell align="center">
                              <Tooltip title="Anular gasto" enterDelay={300}>
                                <span>
                                  <IconButton
                                    size="small"
                                    color="error"
                                    onClick={() => handleQuitarGasto(g)}
                                    disabled={quitarGastoMut.isPending}
                                  >
                                    <Icon icon="mdi:delete-outline" width={18} />
                                  </IconButton>
                                </span>
                              </Tooltip>
                            </TableCell>
                          )}
                        </TableRow>
                      );
                    })}
                  </TableBody>
                </Table>
              </TableContainer>
            )}
          </Box>
        )}

        {tab === 2 && (
          <Box sx={{ p: 2 }}>
            {rendicion.estado === "CERRADA" ? (
              <Box>
                <Alert severity="success" sx={{ mb: 2 }} icon={<Icon icon="mdi:check-circle" />}>
                  Rendición <strong>cerrada</strong> el {fmtFechaHora(rendicion.fecha_cierre)}.
                  {rendicion.tipo_cierre_reintegro && (
                    <> Modo de reintegro: <strong>{rendicion.tipo_cierre_reintegro}</strong>.</>
                  )}
                </Alert>
                {rendicion.devoluciones?.length > 0 && (
                  <TableContainer>
                    <Table size="small">
                      <TableHead>
                        <TableRow>
                          <TableCell sx={{ fontWeight: 600 }}>Tipo</TableCell>
                          <TableCell sx={{ fontWeight: 600 }}>Fecha</TableCell>
                          <TableCell sx={{ fontWeight: 600 }}>Medio de pago</TableCell>
                          <TableCell sx={{ fontWeight: 600 }}>Cuenta</TableCell>
                          <TableCell sx={{ fontWeight: 600 }} align="right">Monto</TableCell>
                          <TableCell sx={{ fontWeight: 600 }} align="center">Modo</TableCell>
                        </TableRow>
                      </TableHead>
                      <TableBody>
                        {rendicion.devoluciones.map((d) => (
                          <TableRow key={d.id}>
                            <TableCell>
                              <Chip
                                size="small"
                                label={d.tipo}
                                color={d.tipo === "DEVOLUCION" ? "warning" : "error"}
                                variant="outlined"
                              />
                            </TableCell>
                            <TableCell>{fmtFechaCalendario(d.fecha)}</TableCell>
                            <TableCell>{d.medio_pago?.descripcion || "—"}</TableCell>
                            <TableCell>{d.tes_cuenta?.nombre || "—"}</TableCell>
                            <TableCell align="right">
                              <Typography fontWeight={700}>
                                {fmtMoneda(Number(d.monto), monedaCodigo)}
                              </Typography>
                            </TableCell>
                            <TableCell align="center">
                              {d.diferido ? (
                                <Chip size="small" label="Diferido (CxP)" color="warning" variant="outlined" />
                              ) : (
                                <Chip size="small" label="Inmediato" color="success" variant="outlined" />
                              )}
                            </TableCell>
                          </TableRow>
                        ))}
                      </TableBody>
                    </Table>
                  </TableContainer>
                )}
              </Box>
            ) : (
              <Box sx={{ textAlign: "center", py: 3 }}>
                <Icon icon="mdi:check-circle-outline" width={48} style={{ opacity: 0.5 }} />
                <Typography variant="h6" sx={{ mt: 1 }}>
                  Listo para cerrar
                </Typography>
                <Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
                  Al cerrar se calcula el saldo y se registra la devolución (si sobra) o el
                  reintegro (si faltó). Una vez cerrada, la rendición es inmutable.
                </Typography>
                <Button
                  variant="contained"
                  color="success"
                  size="large"
                  startIcon={<Icon icon="mdi:check" />}
                  onClick={() => setDialogCierre(true)}
                  disabled={!puedeCerrar}
                >
                  Cerrar rendición
                </Button>
              </Box>
            )}
          </Box>
        )}
      </Paper>

      {/* Auditoría al pie */}
      <Box sx={{ mt: 2, display: "flex", flexDirection: "column", gap: 0.5 }}>
        <Typography variant="caption" color="text.secondary">
          Creada el {fmtFechaHora(rendicion.created_at)}
        </Typography>
        {rendicion.fecha_aprobacion && (
          <Typography variant="caption" color="text.secondary">
            Aprobada el {fmtFechaHora(rendicion.fecha_aprobacion)}
          </Typography>
        )}
        {rendicion.fecha_cierre && (
          <Typography variant="caption" color="text.secondary">
            Cerrada el {fmtFechaHora(rendicion.fecha_cierre)}
          </Typography>
        )}
        {rendicion.fecha_anulacion && (
          <Typography variant="caption" color="error.main">
            Anulada el {fmtFechaHora(rendicion.fecha_anulacion)} · {rendicion.motivo_anulacion}
          </Typography>
        )}
      </Box>

      <AgregarAdelantoDialog
        open={dialogAdelanto}
        onClose={() => setDialogAdelanto(false)}
        rendicion={rendicion}
      />

      <AgregarGastoRendicionDialog
        open={dialogGasto}
        onClose={() => setDialogGasto(false)}
        rendicion={rendicion}
      />

      <CerrarRendicionDialog
        open={dialogCierre}
        onClose={() => setDialogCierre(false)}
        rendicion={rendicion}
        defaultReintegro={config?.reintegro_viatico_default ?? "INMEDIATO"}
      />

      <PDFPreviewDialog
        open={pdfOpen}
        onClose={() => setPdfOpen(false)}
        title={`Comprobante ${rendicion?.numero_rendicion || ""}`}
        fetchBlob={fetchPDF}
        downloadFilename={`rendicion-viatico-${rendicion?.numero_rendicion || "sin-numero"}.pdf`}
      />

      {dialogs}

      {(aprobarMut.isPending || rechazarMut.isPending || anularMut.isPending) && (
        <Box sx={{ position: "fixed", bottom: 20, right: 20 }}>
          <CircularProgress size={24} />
        </Box>
      )}
    </Box>
  );
}

export default RendicionViaticoDetallePage;
