import { Icon } from "@iconify/react";
import {
  Box,
  Button,
  Chip,
  Dialog,
  DialogContent,
  Divider,
  FormControl,
  IconButton,
  InputAdornment,
  InputLabel,
  MenuItem,
  Pagination,
  Paper,
  Select,
  Skeleton,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  TextField,
  Tooltip,
  Typography,
} from "@mui/material";
import { useQuery } from "@tanstack/react-query";
import { useCallback, useMemo, useState } from "react";
import { useNavigate } from "react-router-dom";
import { toast } from "sonner";
import styled from "styled-components";
import api from "../api/api.config";
import { ArqueoPdfModal } from "../components/tesoreria/ArqueoPdfModal";
import { AccesoRestringido } from "../components/common/AccesoRestringido";
import { usePermission } from "../hooks/usePermission";
import { sanitizeCell } from "../components/_standards";
import { SearchableSelect } from "../components/ui/SearchableSelect";
import { hoyISO } from "../utils/fecha";

// ==================== API ====================

const getMovimientosReporte = async (params) => {
  const query = new URLSearchParams();
  if (params.sesion_id) query.set("sesion_id", params.sesion_id);
  if (params.caja_id) query.set("caja_id", params.caja_id);
  if (params.page) query.set("page", String(params.page));
  if (params.limit) query.set("limit", String(params.limit));
  if (params.desde) query.set("desde", params.desde);
  if (params.hasta) query.set("hasta", params.hasta);
  if (params.search) query.set("search", params.search);
  if (params.medio_pago_id) query.set("medio_pago_id", params.medio_pago_id);
  const res = await api.get(`/tesoreria/movimientos?${query.toString()}`);
  return res.data;
};

const getMediosPago = async () => {
  const res = await api.get("/medio-pago/activos");
  return res.data;
};

const getSesionesHistorial = async (page, limit, caja_id) => {
  const query = new URLSearchParams({
    page: String(page),
    limit: String(limit),
  });
  if (caja_id) query.set("caja_id", caja_id);
  const res = await api.get(`/tesoreria/caja/historial?${query.toString()}`);
  return res.data;
};

const getSesionDetalle = async (sesionId) => {
  const res = await api.get(`/tesoreria/caja/sesion/${sesionId}`);
  return res.data;
};

const getArqueoDetalle = async (arqueoId) => {
  const res = await api.get(`/tesoreria/arqueo/${arqueoId}/detalle`);
  return res.data;
};

const getCajasDisponibles = async () => {
  const res = await api.get("/tesoreria/cajas-disponibles");
  return res.data;
};

// ==================== HELPERS ====================

const formatMoney = (num) => new Intl.NumberFormat("es-PY").format(num || 0);

const formatFecha = (fecha) => {
  if (!fecha) return "-";
  const d = new Date(fecha);
  if (isNaN(d.getTime())) return "-";
  const day = String(d.getDate()).padStart(2, "0");
  const month = String(d.getMonth() + 1).padStart(2, "0");
  const year = d.getFullYear();
  const hours = String(d.getHours()).padStart(2, "0");
  const minutes = String(d.getMinutes()).padStart(2, "0");
  return `${day}/${month}/${year} ${hours}:${minutes}`;
};

const formatFechaCorta = (fecha) => {
  if (!fecha) return "-";
  const d = new Date(fecha);
  if (isNaN(d.getTime())) return "-";
  return `${String(d.getDate()).padStart(2, "0")}/${String(d.getMonth() + 1).padStart(2, "0")}/${d.getFullYear()}`;
};

// Etiqueta de una sesión en el filtro. Incluye caja, apertura y estado para que
// el buscador del selector matchee tanto por nombre de caja como por fecha.
const labelSesion = (s) =>
  [
    s?.cajas?.descripcion || "Caja",
    formatFecha(s?.fecha_apertura),
    s?.estado === "CERRADA" ? "Cerrada" : "Abierta",
  ].join(" · ");

const getHoy = () => hoyISO();

const esEntradaTipo = (tipo) => {
  const t = (tipo || "").toLowerCase();
  return t.includes("entrada") || t.includes("venta") || t.includes("apertura");
};

const getUsuarioNombre = (mov) =>
  mov.usuario?.nombres || mov.sesiones_caja?.usuario?.nombres || "-";

const esUUID = (s) => /^[0-9a-f]{8}-[0-9a-f]{4}-/i.test(s);

// El backend traduce las referencias que son ids (factura, recibo) a su número.
// Un id nunca se muestra: si no se pudo traducir, queda en blanco.
const referenciaDe = (mov) => mov.referencia_legible ?? (mov.referencia && !esUUID(mov.referencia) ? mov.referencia : null);

// ==================== CSV EXPORT ====================

const exportCSV = (movimientos, filename = "movimientos_caja") => {
  if (!movimientos?.length) {
    toast.error("No hay datos para exportar");
    return;
  }
  const headers = [
    "Fecha",
    "Caja",
    "Tipo",
    "Concepto",
    "Medio",
    "Referencia",
    "Usuario",
    "Monto",
  ];
  const rows = movimientos.map((m) => [
    formatFecha(m.fecha_mov),
    m.sesiones_caja?.cajas?.descripcion || "-",
    m.tipo_movimiento_cajas?.descripcion || "Movimiento",
    `"${(m.descripcion || "-").replace(/"/g, '""')}"`,
    m.medio_pago_descripcion || "-",
    referenciaDe(m) || "-",
    getUsuarioNombre(m),
    m.monto || 0,
  ]);

  // Sin estas filas el archivo salía con todos los movimientos pero sin ningún
  // total, y había que sumarlo a mano en la planilla.
  const entradas = movimientos
    .filter((m) => esEntradaTipo(m.tipo_movimiento_cajas?.descripcion || ""))
    .reduce((acc, m) => acc + (Number(m.monto) || 0), 0);
  const salidas = movimientos
    .filter((m) => !esEntradaTipo(m.tipo_movimiento_cajas?.descripcion || ""))
    .reduce((acc, m) => acc + (Number(m.monto) || 0), 0);
  // 7 celdas vacías: Caja, Tipo, Concepto, Medio, Referencia y Usuario.
  rows.push([]);
  rows.push(["TOTAL ENTRADAS", "", "", "", "", "", "", entradas]);
  rows.push(["TOTAL SALIDAS", "", "", "", "", "", "", salidas]);
  rows.push(["NETO", "", "", "", "", "", "", entradas - salidas]);

  const csv = [headers.join(";"), ...rows.map((r) => r.map(sanitizeCell).join(";"))].join("\n");
  const BOM = "\uFEFF";
  const blob = new Blob([BOM + csv], { type: "text/csv;charset=utf-8;" });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = `${filename}_${getHoy()}.csv`;
  a.click();
  URL.revokeObjectURL(url);
  toast.success("Reporte exportado correctamente");
};

// ==================== COMPONENT ====================

export function ReporteMovimientosCaja() {
  const navigate = useNavigate();
  const { canRead } = usePermission("REPORTES");

  // Filtros
  const [selectedCaja, setSelectedCaja] = useState("");
  const [selectedSesion, setSelectedSesion] = useState("");
  const [selectedMedio, setSelectedMedio] = useState("");
  const [search, setSearch] = useState("");
  const [searchDebounced, setSearchDebounced] = useState("");
  const [desde, setDesde] = useState("");
  const [hasta, setHasta] = useState("");
  const [page, setPage] = useState(1);
  const limit = 20;

  // Modales
  const [sesionDetalleId, setSesionDetalleId] = useState(null);
  const [arqueoDetalleId, setArqueoDetalleId] = useState(null);
  const [pdfSesionId, setPdfSesionId] = useState(null);
  const [pdfArqueoId, setPdfArqueoId] = useState(null);

  // Debounce search
  const handleSearchChange = useCallback((e) => {
    setSearch(e.target.value);
    clearTimeout(window._movSearchTimer);
    window._movSearchTimer = setTimeout(() => {
      setSearchDebounced(e.target.value);
      setPage(1);
    }, 400);
  }, []);

  // Queries
  const { data: cajas = [] } = useQuery({
    queryKey: ["cajas-reporte"],
    queryFn: getCajasDisponibles,
  });

  const { data: mediosPago = [] } = useQuery({
    queryKey: ["medios-pago-reporte"],
    queryFn: getMediosPago,
  });

  const { data: sesionesData } = useQuery({
    queryKey: ["sesiones-historial-reporte", selectedCaja],
    queryFn: () => getSesionesHistorial(1, 100, selectedCaja || undefined),
  });

  const sesiones = useMemo(() => sesionesData?.items || [], [sesionesData]);

  const { data: movData, isLoading: loadingMovimientos } = useQuery({
    queryKey: [
      "movimientos-reporte",
      selectedCaja,
      selectedSesion,
      selectedMedio,
      page,
      searchDebounced,
      desde,
      hasta,
    ],
    queryFn: () =>
      getMovimientosReporte({
        sesion_id: selectedSesion || undefined,
        caja_id: !selectedSesion ? selectedCaja || undefined : undefined,
        page,
        limit,
        desde: desde || undefined,
        hasta: hasta || undefined,
        search: searchDebounced || undefined,
        medio_pago_id: selectedMedio || undefined,
      }),
  });

  const movimientos = useMemo(() => movData?.items || [], [movData]);
  const totalItems = movData?.total || 0;
  const totalPages = movData?.totalPages || 1;

  // Query para exportar todo (sin paginación)
  const handleExport = async () => {
    try {
      const all = await getMovimientosReporte({
        sesion_id: selectedSesion || undefined,
        caja_id: !selectedSesion ? selectedCaja || undefined : undefined,
        limit: 10000,
        desde: desde || undefined,
        hasta: hasta || undefined,
        search: searchDebounced || undefined,
        medio_pago_id: selectedMedio || undefined,
      });
      exportCSV(all?.items || all || []);
    } catch {
      toast.error("Error al exportar");
    }
  };

  // Sesion detalle query
  const { data: sesionDetalle, isLoading: loadingSesionDetalle } = useQuery({
    queryKey: ["sesion-detalle-reporte", sesionDetalleId],
    queryFn: () => getSesionDetalle(sesionDetalleId),
    enabled: !!sesionDetalleId,
  });

  // Arqueo detalle query
  const { data: arqueoDetalle, isLoading: loadingArqueoDetalle } = useQuery({
    queryKey: ["arqueo-detalle-reporte", arqueoDetalleId],
    queryFn: () => getArqueoDetalle(arqueoDetalleId),
    enabled: !!arqueoDetalleId,
  });

  // Totales de TODO lo filtrado, calculados por el backend.
  //
  // Antes se sumaban acá sobre los 20 registros de la página, así que "Total
  // salidas" mostraba 75.000 en una hoja y 130.000 en la otra y el usuario tenía
  // que sumar las hojas a mano para cerrar el día. El fallback local queda por si
  // la API todavía no devuelve `totales` (deploy a medias).
  const totales = useMemo(() => {
    if (movData?.totales) return movData.totales;
    let entradas = 0;
    let salidas = 0;
    movimientos.forEach((m) => {
      const tipo = m.tipo_movimiento_cajas?.descripcion || "";
      if (esEntradaTipo(tipo)) {
        entradas += Number(m.monto) || 0;
      } else {
        salidas += Number(m.monto) || 0;
      }
    });
    return { entradas, salidas, neto: entradas - salidas };
  }, [movData, movimientos]);

  // Subtotales por medio de pago (página actual)
  const subtotalesPorMedio = useMemo(() => {
    const map = new Map();
    movimientos.forEach((m) => {
      const key = m.medio_pago_descripcion || "Sin medio";
      const tipo = m.tipo_movimiento_cajas?.descripcion || "";
      const monto = Number(m.monto) || 0;
      const signo = esEntradaTipo(tipo) ? 1 : -1;
      const prev = map.get(key) || { medio: key, total: 0, cantidad: 0 };
      prev.total += signo * monto;
      prev.cantidad += 1;
      map.set(key, prev);
    });
    return Array.from(map.values()).sort((a, b) => b.total - a.total);
  }, [movimientos]);

  const handleClearFilters = () => {
    setSelectedCaja("");
    setSelectedSesion("");
    setSelectedMedio("");
    setSearch("");
    setSearchDebounced("");
    setDesde("");
    setHasta("");
    setPage(1);
  };

  if (!canRead) return <AccesoRestringido modulo="REPORTES" />;

  return (
    <Container>
      <Header>
        <HeaderContent>
          <BackBtn onClick={() => navigate("/reportes")}>
            <Icon icon="lucide:arrow-left" />
          </BackBtn>
          <TitleSection>
            <MainTitle>
              <Icon icon="lucide:receipt" />
              Movimientos de Caja
            </MainTitle>
            <Subtitle>
              Reporte detallado de entradas y salidas por caja
            </Subtitle>
          </TitleSection>
          <Box sx={{ display: "flex", gap: 1, ml: "auto" }}>
            <Tooltip title="Exportar CSV">
              <Button
                variant="outlined"
                size="small"
                startIcon={<Icon icon="lucide:download" />}
                onClick={handleExport}
                sx={{
                  textTransform: "none",
                  borderColor: "#f88533",
                  color: "#f88533",
                  "&:hover": { borderColor: "#e07429", background: "#fff3e0" },
                }}
              >
                Exportar
              </Button>
            </Tooltip>
          </Box>
        </HeaderContent>
      </Header>

      <Content>
        {/* Filtros */}
        <Paper sx={{ p: 2, mb: 2 }}>
          <Box
            sx={{
              display: "flex",
              gap: 2,
              flexWrap: "wrap",
              alignItems: "center",
            }}
          >
            <TextField
              size="small"
              placeholder="Buscar por concepto o referencia..."
              value={search}
              onChange={handleSearchChange}
              sx={{ minWidth: 260, flex: 1 }}
              InputProps={{
                startAdornment: (
                  <InputAdornment position="start">
                    <Icon icon="lucide:search" width={18} color="#999" />
                  </InputAdornment>
                ),
                endAdornment: search && (
                  <InputAdornment position="end">
                    <IconButton
                      size="small"
                      onClick={() => {
                        setSearch("");
                        setSearchDebounced("");
                        setPage(1);
                      }}
                    >
                      <Icon icon="lucide:x" width={16} />
                    </IconButton>
                  </InputAdornment>
                ),
              }}
            />

            <FormControl size="small" sx={{ minWidth: 180 }}>
              <InputLabel>Caja</InputLabel>
              <Select
                value={selectedCaja}
                label="Caja"
                onChange={(e) => {
                  setSelectedCaja(e.target.value);
                  setSelectedSesion("");
                  setPage(1);
                }}
              >
                <MenuItem value="">Todas</MenuItem>
                {cajas.map((c) => (
                  <MenuItem key={c.id} value={c.id}>
                    {c.descripcion}
                  </MenuItem>
                ))}
              </Select>
            </FormControl>

            <Box sx={{ minWidth: 260, flex: "0 1 320px" }}>
              <SearchableSelect
                label="Sesión"
                placeholder="Todas las sesiones"
                options={sesiones}
                value={selectedSesion || null}
                getOptionLabel={labelSesion}
                noOptionsText="Sin sesiones para esa caja"
                onChange={(id) => {
                  setSelectedSesion(id || "");
                  setPage(1);
                }}
              />
            </Box>

            <FormControl size="small" sx={{ minWidth: 180 }}>
              <InputLabel>Medio de pago</InputLabel>
              <Select
                value={selectedMedio}
                label="Medio de pago"
                onChange={(e) => {
                  setSelectedMedio(e.target.value);
                  setPage(1);
                }}
              >
                <MenuItem value="">Todos</MenuItem>
                {mediosPago.map((mp) => (
                  <MenuItem key={mp.id} value={mp.id}>
                    {mp.descripcion}
                  </MenuItem>
                ))}
              </Select>
            </FormControl>

            <TextField
              size="small"
              type="date"
              label="Desde"
              value={desde}
              onChange={(e) => {
                setDesde(e.target.value);
                setPage(1);
              }}
              InputLabelProps={{ shrink: true }}
              sx={{ width: 155 }}
            />
            <TextField
              size="small"
              type="date"
              label="Hasta"
              value={hasta}
              onChange={(e) => {
                setHasta(e.target.value);
                setPage(1);
              }}
              InputLabelProps={{ shrink: true }}
              sx={{ width: 155 }}
            />

            {(selectedCaja || selectedSesion || selectedMedio || search || desde || hasta) && (
              <Tooltip title="Limpiar filtros">
                <IconButton
                  size="small"
                  onClick={handleClearFilters}
                  sx={{ color: "#f88533" }}
                >
                  <Icon icon="lucide:filter-x" width={20} />
                </IconButton>
              </Tooltip>
            )}
          </Box>
        </Paper>

        {/* Totales */}
        <Box
          sx={{
            display: "grid",
            gridTemplateColumns: "repeat(auto-fit, minmax(180px, 1fr))",
            gap: 1.5,
            mb: 2,
          }}
        >
          <StatCard>
            <StatIcon $color="#22c55e">
              <Icon icon="lucide:arrow-down-circle" />
            </StatIcon>
            <StatInfo>
              <StatLabel>Total Entradas (período)</StatLabel>
              <StatValue $color="#22c55e">
                Gs. {formatMoney(totales.entradas)}
              </StatValue>
            </StatInfo>
          </StatCard>
          <StatCard>
            <StatIcon $color="#ef4444">
              <Icon icon="lucide:arrow-up-circle" />
            </StatIcon>
            <StatInfo>
              <StatLabel>Total Salidas (período)</StatLabel>
              <StatValue $color="#ef4444">
                Gs. {formatMoney(totales.salidas)}
              </StatValue>
            </StatInfo>
          </StatCard>
          <StatCard>
            <StatIcon $color="#3b82f6">
              <Icon icon="lucide:wallet" />
            </StatIcon>
            <StatInfo>
              <StatLabel>Neto (período)</StatLabel>
              <StatValue $color="#3b82f6">
                Gs. {formatMoney(totales.neto)}
              </StatValue>
            </StatInfo>
          </StatCard>
          <StatCard>
            <StatIcon $color="#8b5cf6">
              <Icon icon="lucide:hash" />
            </StatIcon>
            <StatInfo>
              <StatLabel>Movimientos</StatLabel>
              <StatValue $color="#8b5cf6">{totalItems}</StatValue>
            </StatInfo>
          </StatCard>
        </Box>

        {/* Subtotales por medio de pago */}
        {subtotalesPorMedio.length > 0 && (
          <Paper sx={{ p: 1.5, mb: 2 }}>
            <Typography
              variant="caption"
              fontWeight={700}
              sx={{ display: "block", mb: 1, color: "text.secondary" }}
            >
              <Icon
                icon="lucide:credit-card"
                width={14}
                style={{ marginRight: 4, verticalAlign: "text-bottom" }}
              />
              Subtotales por medio de pago (página actual)
            </Typography>
            <Box
              sx={{
                display: "grid",
                gridTemplateColumns: "repeat(auto-fit, minmax(160px, 1fr))",
                gap: 1,
              }}
            >
              {subtotalesPorMedio.map((s) => (
                <Box
                  key={s.medio}
                  sx={{
                    p: 1,
                    borderRadius: 1.5,
                    border: "1px solid",
                    borderColor: "divider",
                    bgcolor: "action.hover",
                  }}
                >
                  <Typography
                    variant="caption"
                    sx={{ display: "block", color: "text.secondary" }}
                  >
                    {s.medio} ({s.cantidad})
                  </Typography>
                  <Typography
                    variant="body2"
                    fontWeight={700}
                    color={s.total >= 0 ? "success.main" : "error.main"}
                  >
                    Gs. {formatMoney(s.total)}
                  </Typography>
                </Box>
              ))}
            </Box>
          </Paper>
        )}

        {/* Tabla */}
        <Paper sx={{ overflow: "hidden" }}>
          <TableContainer sx={{ maxHeight: "calc(100vh - 420px)" }}>
            <Table size="small" stickyHeader>
              <TableHead>
                <TableRow>
                  <TableCell sx={{ fontWeight: 700, whiteSpace: "nowrap" }}>
                    Fecha
                  </TableCell>
                  <TableCell sx={{ fontWeight: 700 }}>Caja</TableCell>
                  <TableCell sx={{ fontWeight: 700 }}>Tipo</TableCell>
                  <TableCell sx={{ fontWeight: 700 }}>Concepto</TableCell>
                  <TableCell sx={{ fontWeight: 700 }}>Medio</TableCell>
                  <TableCell sx={{ fontWeight: 700 }}>Referencia</TableCell>
                  <TableCell sx={{ fontWeight: 700 }}>Usuario</TableCell>
                  <TableCell align="right" sx={{ fontWeight: 700 }}>
                    Monto
                  </TableCell>
                  <TableCell align="center" sx={{ fontWeight: 700, width: 50 }}>
                    Ver
                  </TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {loadingMovimientos ? (
                  Array.from({ length: 8 }).map((_, i) => (
                    <TableRow key={i}>
                      {Array.from({ length: 9 }).map((__, j) => (
                        <TableCell key={j}>
                          <Skeleton variant="text" />
                        </TableCell>
                      ))}
                    </TableRow>
                  ))
                ) : movimientos.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={9} align="center" sx={{ py: 6 }}>
                      <Icon
                        icon="lucide:inbox"
                        style={{ fontSize: 40, color: "#666", marginBottom: 8 }}
                      />
                      <Typography color="text.secondary">
                        No hay movimientos para mostrar
                      </Typography>
                    </TableCell>
                  </TableRow>
                ) : (
                  movimientos.map((mov) => {
                    const tipo =
                      mov.tipo_movimiento_cajas?.descripcion || "Movimiento";
                    const entrada = esEntradaTipo(tipo);
                    return (
                      <TableRow
                        key={mov.id}
                        hover
                        sx={{ "&:hover": { opacity: 0.85 } }}
                      >
                        <TableCell
                          sx={{ whiteSpace: "nowrap", fontSize: "0.8rem" }}
                        >
                          {formatFecha(mov.fecha_mov)}
                        </TableCell>
                        <TableCell sx={{ fontSize: "0.8rem" }}>
                          {mov.sesiones_caja?.cajas?.descripcion || "-"}
                        </TableCell>
                        <TableCell>
                          <Chip
                            label={tipo}
                            size="small"
                            color={entrada ? "success" : "error"}
                            variant="outlined"
                            sx={{ fontWeight: 600, fontSize: "0.7rem" }}
                          />
                        </TableCell>
                        <TableCell
                          sx={{
                            fontSize: "0.8rem",
                            maxWidth: 200,
                            overflow: "hidden",
                            textOverflow: "ellipsis",
                            whiteSpace: "nowrap",
                          }}
                        >
                          {mov.descripcion || "-"}
                        </TableCell>
                        <TableCell sx={{ fontSize: "0.8rem" }}>
                          {mov.medio_pago_descripcion ? (
                            <Chip
                              label={mov.medio_pago_descripcion}
                              size="small"
                              variant="outlined"
                              sx={{ fontSize: "0.7rem" }}
                            />
                          ) : (
                            <span style={{ color: "#999" }}>—</span>
                          )}
                        </TableCell>
                        <TableCell
                          sx={{ fontSize: "0.8rem", color: "text.secondary" }}
                        >
                          {referenciaDe(mov) || "-"}
                        </TableCell>
                        <TableCell sx={{ fontSize: "0.8rem" }}>
                          {getUsuarioNombre(mov)}
                        </TableCell>
                        <TableCell align="right">
                          <Typography
                            fontWeight={600}
                            fontSize="0.85rem"
                            color={entrada ? "success.main" : "error.main"}
                          >
                            {entrada ? "+" : "-"} Gs. {formatMoney(mov.monto)}
                          </Typography>
                        </TableCell>
                        <TableCell align="center">
                          {mov.sesiones_caja?.id && (
                            <Tooltip title="Ver sesión">
                              <IconButton
                                size="small"
                                onClick={() =>
                                  setSesionDetalleId(mov.sesiones_caja.id)
                                }
                              >
                                <Icon
                                  icon="lucide:eye"
                                  width={16}
                                  color="#f88533"
                                />
                              </IconButton>
                            </Tooltip>
                          )}
                        </TableCell>
                      </TableRow>
                    );
                  })
                )}
              </TableBody>
            </Table>
          </TableContainer>

          {/* Paginación */}
          {totalPages > 1 && (
            <Box
              sx={{
                display: "flex",
                justifyContent: "space-between",
                alignItems: "center",
                px: 2,
                py: 1.5,
                borderTop: "1px solid",
                borderColor: "divider",
              }}
            >
              <Typography variant="body2" color="text.secondary">
                Mostrando {(page - 1) * limit + 1}-
                {Math.min(page * limit, totalItems)} de {totalItems}
              </Typography>
              <Pagination
                count={totalPages}
                page={page}
                onChange={(_, v) => setPage(v)}
                size="small"
                color="primary"
                sx={{
                  "& .Mui-selected": {
                    background: "#f88533 !important",
                    color: "#fff",
                  },
                }}
              />
            </Box>
          )}
        </Paper>
      </Content>

      {/* ==================== MODAL DETALLE SESIÓN ==================== */}
      <Dialog
        open={!!sesionDetalleId}
        onClose={() => setSesionDetalleId(null)}
        maxWidth="md"
        fullWidth
        PaperProps={{ sx: { borderRadius: 3, bgcolor: "background.paper" } }}
      >
        <Box
          sx={{
            background: "linear-gradient(135deg, #8b5cf6 0%, #6366f1 100%)",
            p: 2.5,
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
          }}
        >
          <Box sx={{ display: "flex", alignItems: "center", gap: 1.5 }}>
            <Icon icon="lucide:file-text" width={24} color="white" />
            <Typography variant="h6" fontWeight={700} color="white">
              Detalle de Sesión
            </Typography>
          </Box>
          <Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
            {sesionDetalleId && (
              <Tooltip title="Imprimir arqueo (PDF)">
                <IconButton
                  onClick={() => setPdfSesionId(sesionDetalleId)}
                  sx={{ color: "white" }}
                >
                  <Icon icon="lucide:printer" width={20} />
                </IconButton>
              </Tooltip>
            )}
            <IconButton
              onClick={() => setSesionDetalleId(null)}
              sx={{ color: "white" }}
            >
              <Icon icon="lucide:x" width={20} />
            </IconButton>
          </Box>
        </Box>
        <DialogContent sx={{ p: 3 }}>
          {loadingSesionDetalle ? (
            <Box sx={{ py: 4, textAlign: "center" }}>
              <Skeleton
                variant="rectangular"
                height={200}
                sx={{ borderRadius: 2 }}
              />
            </Box>
          ) : sesionDetalle ? (
            <>
              {/* Info general */}
              <Box
                sx={{
                  display: "grid",
                  gridTemplateColumns: { xs: "1fr", sm: "1fr 1fr" },
                  gap: 2,
                  mb: 3,
                }}
              >
                <InfoItem>
                  <InfoLabel>Caja</InfoLabel>
                  <InfoValue>
                    {sesionDetalle.cajas?.descripcion || "-"}
                  </InfoValue>
                </InfoItem>
                <InfoItem>
                  <InfoLabel>Sucursal</InfoLabel>
                  <InfoValue>
                    {sesionDetalle.empresas_sucursales?.punto_establecimiento ||
                      "-"}
                  </InfoValue>
                </InfoItem>
                <InfoItem>
                  <InfoLabel>Operador</InfoLabel>
                  <InfoValue>{sesionDetalle.usuario?.nombres || "-"}</InfoValue>
                </InfoItem>
                <InfoItem>
                  <InfoLabel>Estado</InfoLabel>
                  <Chip
                    label={sesionDetalle.estado}
                    size="small"
                    color={
                      sesionDetalle.estado === "ABIERTA"
                        ? "success"
                        : sesionDetalle.estado === "CERRADA"
                          ? "default"
                          : "warning"
                    }
                    sx={{ fontWeight: 600 }}
                  />
                </InfoItem>
                <InfoItem>
                  <InfoLabel>Apertura</InfoLabel>
                  <InfoValue>
                    {formatFecha(sesionDetalle.fecha_apertura)}
                  </InfoValue>
                </InfoItem>
                <InfoItem>
                  <InfoLabel>Cierre</InfoLabel>
                  <InfoValue>
                    {formatFecha(sesionDetalle.fecha_cierre)}
                  </InfoValue>
                </InfoItem>
              </Box>

              {/* Montos */}
              <Typography variant="subtitle2" fontWeight={700} sx={{ mb: 1.5 }}>
                <Icon
                  icon="lucide:banknote"
                  width={16}
                  style={{ marginRight: 6, verticalAlign: "text-bottom" }}
                />
                Resumen de Montos
              </Typography>
              <Box
                sx={{
                  display: "grid",
                  gridTemplateColumns: { xs: "1fr 1fr", sm: "1fr 1fr 1fr 1fr" },
                  gap: 1.5,
                  mb: 3,
                }}
              >
                <MiniStat>
                  <MiniStatLabel>Apertura</MiniStatLabel>
                  <MiniStatVal $c="#3b82f6">
                    Gs. {formatMoney(sesionDetalle.monto_apertura)}
                  </MiniStatVal>
                </MiniStat>
                <MiniStat>
                  <MiniStatLabel>Ventas Efectivo</MiniStatLabel>
                  <MiniStatVal $c="#22c55e">
                    Gs. {formatMoney(sesionDetalle.monto_ventas_efectivo)}
                  </MiniStatVal>
                </MiniStat>
                <MiniStat>
                  <MiniStatLabel>Entradas Manual</MiniStatLabel>
                  <MiniStatVal $c="#22c55e">
                    Gs. {formatMoney(sesionDetalle.monto_entradas_manual)}
                  </MiniStatVal>
                </MiniStat>
                <MiniStat>
                  <MiniStatLabel>Salidas Manual</MiniStatLabel>
                  <MiniStatVal $c="#ef4444">
                    Gs. {formatMoney(sesionDetalle.monto_salidas_manual)}
                  </MiniStatVal>
                </MiniStat>
                {sesionDetalle.monto_cierre != null && (
                  <MiniStat>
                    <MiniStatLabel>Cierre</MiniStatLabel>
                    <MiniStatVal $c="#8b5cf6">
                      Gs. {formatMoney(sesionDetalle.monto_cierre)}
                    </MiniStatVal>
                  </MiniStat>
                )}
              </Box>

              {/* Arqueos */}
              {sesionDetalle.arqueo_cajas?.length > 0 && (
                <>
                  <Divider sx={{ my: 2 }} />
                  <Typography
                    variant="subtitle2"
                    fontWeight={700}
                    sx={{ mb: 1.5 }}
                  >
                    <Icon
                      icon="lucide:calculator"
                      width={16}
                      style={{ marginRight: 6, verticalAlign: "text-bottom" }}
                    />
                    Arqueos ({sesionDetalle.arqueo_cajas.length})
                  </Typography>
                  <TableContainer>
                    <Table size="small">
                      <TableHead>
                        <TableRow>
                          <TableCell sx={{ fontWeight: 600 }}>Fecha</TableCell>
                          <TableCell sx={{ fontWeight: 600 }}>Tipo</TableCell>
                          <TableCell align="right" sx={{ fontWeight: 600 }}>
                            Sistema
                          </TableCell>
                          <TableCell align="right" sx={{ fontWeight: 600 }}>
                            Contado
                          </TableCell>
                          <TableCell align="right" sx={{ fontWeight: 600 }}>
                            Diferencia
                          </TableCell>
                          <TableCell sx={{ fontWeight: 600 }}>Estado</TableCell>
                          <TableCell
                            align="center"
                            sx={{ fontWeight: 600, width: 50 }}
                          >
                            Ver
                          </TableCell>
                        </TableRow>
                      </TableHead>
                      <TableBody>
                        {sesionDetalle.arqueo_cajas.map((arq) => {
                          const dif = Number(arq.diferencia) || 0;
                          return (
                            <TableRow key={arq.id} hover>
                              <TableCell sx={{ fontSize: "0.8rem" }}>
                                {formatFechaCorta(arq.fecha)}
                              </TableCell>
                              <TableCell>
                                <Chip
                                  label={arq.tipo_arqueo || "cierre"}
                                  size="small"
                                  variant="outlined"
                                  sx={{ fontSize: "0.7rem" }}
                                />
                              </TableCell>
                              <TableCell
                                align="right"
                                sx={{ fontSize: "0.8rem" }}
                              >
                                Gs. {formatMoney(arq.total_sistema)}
                              </TableCell>
                              <TableCell
                                align="right"
                                sx={{ fontSize: "0.8rem" }}
                              >
                                Gs. {formatMoney(arq.total_contado)}
                              </TableCell>
                              <TableCell align="right">
                                <Typography
                                  fontSize="0.8rem"
                                  fontWeight={600}
                                  color={
                                    dif === 0 ? "success.main" : "error.main"
                                  }
                                >
                                  {dif >= 0 ? "+" : ""}Gs. {formatMoney(dif)}
                                </Typography>
                              </TableCell>
                              <TableCell>
                                <Chip
                                  label={arq.estado || "-"}
                                  size="small"
                                  color={
                                    arq.estado === "finalizado"
                                      ? "success"
                                      : arq.estado === "con_diferencia"
                                        ? "warning"
                                        : "default"
                                  }
                                  sx={{ fontSize: "0.7rem", fontWeight: 600 }}
                                />
                              </TableCell>
                              <TableCell align="center">
                                <Box sx={{ display: "flex", justifyContent: "center", gap: 0.5 }}>
                                  <Tooltip title="Ver detalle arqueo">
                                    <IconButton
                                      size="small"
                                      onClick={() => setArqueoDetalleId(arq.id)}
                                    >
                                      <Icon
                                        icon="lucide:list-tree"
                                        width={16}
                                        color="#f88533"
                                      />
                                    </IconButton>
                                  </Tooltip>
                                  <Tooltip title="Imprimir arqueo (PDF)">
                                    <IconButton
                                      size="small"
                                      onClick={() => setPdfArqueoId(arq.id)}
                                    >
                                      <Icon
                                        icon="lucide:printer"
                                        width={16}
                                        color="#1976d2"
                                      />
                                    </IconButton>
                                  </Tooltip>
                                </Box>
                              </TableCell>
                            </TableRow>
                          );
                        })}
                      </TableBody>
                    </Table>
                  </TableContainer>
                </>
              )}

              {/* Observaciones cierre */}
              {sesionDetalle.observaciones && (
                <Box
                  sx={{
                    mt: 2,
                    p: 1.5,
                    borderRadius: 2,
                    bgcolor: "action.hover",
                  }}
                >
                  <Typography variant="body2" fontWeight={600} sx={{ mb: 0.5 }}>
                    <Icon
                      icon="lucide:message-square"
                      width={14}
                      style={{ marginRight: 4 }}
                    />
                    Observaciones de cierre
                  </Typography>
                  <Typography variant="body2" color="text.secondary">
                    {sesionDetalle.observaciones}
                  </Typography>
                </Box>
              )}
            </>
          ) : (
            <Typography color="text.secondary">
              No se encontró la sesión
            </Typography>
          )}
        </DialogContent>
      </Dialog>

      {/* ==================== MODAL DETALLE ARQUEO ==================== */}
      <Dialog
        open={!!arqueoDetalleId}
        onClose={() => setArqueoDetalleId(null)}
        maxWidth="sm"
        fullWidth
        PaperProps={{ sx: { borderRadius: 3, bgcolor: "background.paper" } }}
      >
        <Box
          sx={{
            background: "linear-gradient(135deg, #8b5cf6 0%, #6366f1 100%)",
            p: 2.5,
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
          }}
        >
          <Box sx={{ display: "flex", alignItems: "center", gap: 1.5 }}>
            <Icon icon="lucide:calculator" width={24} color="white" />
            <Typography variant="h6" fontWeight={700} color="white">
              Detalle de Arqueo
            </Typography>
          </Box>
          <IconButton
            onClick={() => setArqueoDetalleId(null)}
            sx={{ color: "white" }}
          >
            <Icon icon="lucide:x" width={20} />
          </IconButton>
        </Box>
        <DialogContent sx={{ p: 3 }}>
          {loadingArqueoDetalle ? (
            <Box sx={{ py: 4 }}>
              <Skeleton
                variant="rectangular"
                height={150}
                sx={{ borderRadius: 2 }}
              />
            </Box>
          ) : arqueoDetalle ? (
            <>
              <Box
                sx={{
                  display: "grid",
                  gridTemplateColumns: "1fr 1fr",
                  gap: 2,
                  mb: 3,
                }}
              >
                <InfoItem>
                  <InfoLabel>Total Sistema</InfoLabel>
                  <InfoValue>
                    Gs. {formatMoney(arqueoDetalle.total_sistema)}
                  </InfoValue>
                </InfoItem>
                <InfoItem>
                  <InfoLabel>Total Contado</InfoLabel>
                  <InfoValue>
                    Gs. {formatMoney(arqueoDetalle.total_contado)}
                  </InfoValue>
                </InfoItem>
                <InfoItem>
                  <InfoLabel>Diferencia</InfoLabel>
                  <InfoValue
                    style={{
                      color:
                        Number(arqueoDetalle.diferencia) === 0
                          ? "#22c55e"
                          : "#ef4444",
                      fontWeight: 700,
                    }}
                  >
                    Gs. {formatMoney(arqueoDetalle.diferencia)}
                  </InfoValue>
                </InfoItem>
                <InfoItem>
                  <InfoLabel>Estado</InfoLabel>
                  <Chip
                    label={arqueoDetalle.estado || "-"}
                    size="small"
                    color={
                      arqueoDetalle.estado === "finalizado"
                        ? "success"
                        : "warning"
                    }
                    sx={{ fontWeight: 600 }}
                  />
                </InfoItem>
              </Box>

              {/* Detalle denominaciones */}
              {arqueoDetalle.arqueo_caja_detalle?.length > 0 && (
                <>
                  <Typography
                    variant="subtitle2"
                    fontWeight={700}
                    sx={{ mb: 1.5 }}
                  >
                    Detalle por denominación / medio
                  </Typography>
                  <TableContainer>
                    <Table size="small">
                      <TableHead>
                        <TableRow>
                          <TableCell sx={{ fontWeight: 600 }}>Tipo</TableCell>
                          <TableCell sx={{ fontWeight: 600 }}>
                            Descripción
                          </TableCell>
                          <TableCell align="right" sx={{ fontWeight: 600 }}>
                            Denominación
                          </TableCell>
                          <TableCell align="right" sx={{ fontWeight: 600 }}>
                            Cantidad
                          </TableCell>
                          <TableCell align="right" sx={{ fontWeight: 600 }}>
                            Subtotal
                          </TableCell>
                          <TableCell sx={{ fontWeight: 600 }}>Obs.</TableCell>
                        </TableRow>
                      </TableHead>
                      <TableBody>
                        {arqueoDetalle.arqueo_caja_detalle.map((d, i) => {
                          const denom = Number(d.denominacion) || 0;
                          const descDenom = denom
                            ? d.tipo === "efectivo"
                              ? `Billete de ${formatMoney(denom)}`
                              : `${formatMoney(denom)}`
                            : d.moneda?.descripcion || "-";
                          return (
                            <TableRow key={i} hover>
                              <TableCell
                                sx={{
                                  fontSize: "0.8rem",
                                  textTransform: "capitalize",
                                }}
                              >
                                <Chip
                                  label={d.tipo}
                                  size="small"
                                  variant="outlined"
                                  sx={{ fontSize: "0.7rem" }}
                                />
                              </TableCell>
                              <TableCell sx={{ fontSize: "0.8rem" }}>
                                {descDenom}
                              </TableCell>
                              <TableCell
                                align="right"
                                sx={{ fontSize: "0.8rem" }}
                              >
                                {denom ? formatMoney(denom) : "-"}
                              </TableCell>
                              <TableCell
                                align="right"
                                sx={{ fontSize: "0.8rem", fontWeight: 600 }}
                              >
                                {d.cantidad}
                              </TableCell>
                              <TableCell
                                align="right"
                                sx={{ fontSize: "0.8rem", fontWeight: 600 }}
                              >
                                Gs. {formatMoney(d.subtotal)}
                              </TableCell>
                              <TableCell
                                sx={{
                                  fontSize: "0.75rem",
                                  color: "text.secondary",
                                  maxWidth: 120,
                                  overflow: "hidden",
                                  textOverflow: "ellipsis",
                                  whiteSpace: "nowrap",
                                }}
                              >
                                {d.observacion || "-"}
                              </TableCell>
                            </TableRow>
                          );
                        })}
                      </TableBody>
                    </Table>
                  </TableContainer>
                </>
              )}

              {arqueoDetalle.observacion && (
                <Box
                  sx={{
                    mt: 2,
                    p: 1.5,
                    borderRadius: 2,
                    bgcolor: "action.hover",
                  }}
                >
                  <Typography variant="body2" fontWeight={600} sx={{ mb: 0.5 }}>
                    Observación
                  </Typography>
                  <Typography variant="body2" color="text.secondary">
                    {arqueoDetalle.observacion}
                  </Typography>
                </Box>
              )}
            </>
          ) : (
            <Typography color="text.secondary">
              No se encontró el arqueo
            </Typography>
          )}
        </DialogContent>
      </Dialog>

      {/* ==================== MODAL PDF ARQUEO ==================== */}
      <ArqueoPdfModal
        open={!!pdfSesionId}
        sesionId={pdfSesionId}
        onClose={() => setPdfSesionId(null)}
        titulo="Arqueo de Sesión"
      />
      <ArqueoPdfModal
        open={!!pdfArqueoId}
        arqueoId={pdfArqueoId}
        onClose={() => setPdfArqueoId(null)}
        titulo="Arqueo de Caja"
      />
    </Container>
  );
}

// ==================== STYLED ====================

const Container = styled.div`
  background: ${({ theme }) => theme.body};
  min-height: calc(100vh - 80px);
  margin-top: 50px;
  @media (max-width: 600px) {
    margin-top: 40px;
  }
`;

const Header = styled.div`
  background: linear-gradient(
    135deg,
    ${({ theme }) => theme.bg3} 0%,
    ${({ theme }) => theme.bg4} 100%
  );
  border-bottom: 1px solid ${({ theme }) => theme.bg4};
  padding: 0.6rem 1.5rem;
  @media (max-width: 768px) {
    padding: 0.5rem 1rem;
  }
`;

const HeaderContent = styled.div`
  max-width: 1400px;
  margin: 0 auto;
  display: flex;
  align-items: center;
  gap: 0.75rem;
`;

const BackBtn = styled.button`
  display: flex;
  align-items: center;
  justify-content: center;
  width: 2rem;
  height: 2rem;
  border-radius: 8px;
  border: 1px solid ${({ theme }) => theme.bg4};
  background: transparent;
  color: ${({ theme }) => theme.text};
  cursor: pointer;
  transition: all 0.15s;
  &:hover {
    background: ${({ theme }) => theme.bg4};
  }
  svg {
    width: 1rem;
    height: 1rem;
  }
`;

const TitleSection = styled.div`
  flex: 1;
`;

const MainTitle = styled.h1`
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-size: 1.3rem;
  font-weight: 700;
  color: ${({ theme }) => theme.text};
  margin: 0 0 0.1rem 0;
  svg {
    color: #f88533;
    width: 1.3rem;
    height: 1.3rem;
  }
  @media (max-width: 768px) {
    font-size: 1.1rem;
  }
`;

const Subtitle = styled.p`
  font-size: 0.78rem;
  color: ${({ theme }) => theme.text}cc;
  margin: 0;
`;

const Content = styled.div`
  max-width: 1400px;
  margin: 0 auto;
  padding: 1rem 1.5rem;
  @media (max-width: 768px) {
    padding: 0.75rem 1rem;
  }
`;

const StatCard = styled.div`
  display: flex;
  align-items: center;
  gap: 0.75rem;
  padding: 0.85rem 1rem;
  background: ${({ theme }) => theme.bg3}60;
  border: 1px solid ${({ theme }) => theme.bg4};
  border-radius: 10px;
`;

const StatIcon = styled.div`
  display: flex;
  align-items: center;
  justify-content: center;
  width: 2.2rem;
  height: 2.2rem;
  border-radius: 8px;
  background: ${({ $color }) => $color}18;
  svg {
    width: 1.15rem;
    height: 1.15rem;
    color: ${({ $color }) => $color};
  }
`;

const StatInfo = styled.div`
  display: flex;
  flex-direction: column;
`;

const StatLabel = styled.span`
  font-size: 0.7rem;
  font-weight: 500;
  color: ${({ theme }) => theme.text}90;
`;

const StatValue = styled.span`
  font-size: 0.95rem;
  font-weight: 700;
  color: ${({ $color }) => $color};
`;

const InfoItem = styled.div`
  padding: 0.6rem 0.8rem;
  background: ${({ theme }) => theme.bg3}40;
  border: 1px solid ${({ theme }) => theme.bg4};
  border-radius: 8px;
`;

const InfoLabel = styled.div`
  font-size: 0.7rem;
  font-weight: 500;
  color: ${({ theme }) => theme.text}90;
  margin-bottom: 0.2rem;
`;

const InfoValue = styled.div`
  font-size: 0.88rem;
  font-weight: 600;
  color: ${({ theme }) => theme.text};
`;

const MiniStat = styled.div`
  padding: 0.6rem 0.8rem;
  background: ${({ theme }) => theme.bg3}40;
  border: 1px solid ${({ theme }) => theme.bg4};
  border-radius: 8px;
  text-align: center;
`;

const MiniStatLabel = styled.div`
  font-size: 0.65rem;
  font-weight: 500;
  color: ${({ theme }) => theme.text}90;
  margin-bottom: 0.15rem;
`;

const MiniStatVal = styled.div`
  font-size: 0.82rem;
  font-weight: 700;
  color: ${({ $c }) => $c};
`;
