import { useEffect, useMemo, useState } from "react";
import {
  Alert,
  Autocomplete,
  Avatar,
  Box,
  Button,
  Checkbox,
  Chip,
  CircularProgress,
  Collapse,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  Divider,
  Grid,
  IconButton,
  MenuItem,
  Paper,
  Stack,
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableRow,
  TextField,
  Tooltip,
  Typography,
} from "@mui/material";
import { Icon } from "@iconify/react";
import { toast } from "sonner";
import { searchClientes } from "../../../api/clientes.service";
import { getCuotasPendientes } from "../../../api/cobros.service";
import { createGestionMora } from "../../../api/cobranzas.service";
import {
  COB_MORA_ESTADO,
  COB_MORA_ESTADO_META,
} from "../../_standards/enums/estados";
import { fmtFechaCalendario } from "../../../utils/fecha";

const ESTADOS_INICIALES = [
  COB_MORA_ESTADO.GESTION_INTERNA,
  COB_MORA_ESTADO.INFORMCONF,
];

const fmt = (v) =>
  new Intl.NumberFormat("es-PY").format(Math.round(Number(v) || 0));

const pad = (v, n) => String(v ?? "").padStart(n, "0");

const formatNroFactura = (fc) => {
  if (!fc) return "—";
  const est = pad(fc.dest, 3);
  const pun = pad(fc.dpunexp, 3);
  const num = pad(fc.dnumdoc, 7);
  return `${est}-${pun}-${num}`;
};

const diasEntre = (desde, hasta = new Date()) => {
  if (!desde) return 0;
  const d = new Date(desde);
  if (Number.isNaN(d.getTime())) return 0;
  return Math.floor((hasta - d) / (1000 * 60 * 60 * 24));
};

const antiguedadChip = (dias) => {
  if (dias <= 0) return { label: "Al día", color: "success" };
  if (dias <= 30) return { label: `${dias}d`, color: "warning" };
  if (dias <= 60) return { label: `${dias}d`, color: "warning" };
  if (dias <= 90) return { label: `${dias}d`, color: "error" };
  return { label: `${dias}d`, color: "error" };
};

function FacturaRow({ factura, selected, onToggle }) {
  const [expanded, setExpanded] = useState(false);
  const antig = antiguedadChip(factura.dias_vencido);

  return (
    <>
      <TableRow hover sx={{ "& > *": { borderBottom: "unset" } }}>
        <TableCell padding="checkbox">
          <Checkbox checked={selected} onChange={onToggle} />
        </TableCell>
        <TableCell>
          <IconButton size="small" onClick={() => setExpanded((e) => !e)}>
            <Icon
              icon={expanded ? "mdi:chevron-up" : "mdi:chevron-down"}
              width={18}
            />
          </IconButton>
        </TableCell>
        <TableCell>
          <Typography variant="body2" fontFamily="monospace" fontWeight={600}>
            {factura.numero_formateado}
          </Typography>
        </TableCell>
        <TableCell>{fmtFechaCalendario(factura.fecha_emision)}</TableCell>
        <TableCell>{fmtFechaCalendario(factura.vto_mas_viejo)}</TableCell>
        <TableCell align="center">
          <Chip size="small" label={antig.label} color={antig.color} />
        </TableCell>
        <TableCell align="center">
          {factura.cuotas_pendientes}/{factura.cuotas_total}
        </TableCell>
        <TableCell>{factura.moneda || "PYG"}</TableCell>
        <TableCell align="right">{fmt(factura.total_factura)}</TableCell>
        <TableCell align="right">
          <Typography variant="body2" fontWeight={600} color="error.main">
            {fmt(factura.saldo_pendiente)}
          </Typography>
        </TableCell>
        <TableCell align="center">
          {factura.promesas_count > 0 && (
            <Tooltip title={`${factura.promesas_count} promesa(s) registrada(s)`}>
              <Chip
                size="small"
                icon={<Icon icon="mdi:handshake-outline" />}
                label={factura.promesas_count}
                color={factura.promesas_incumplidas > 0 ? "error" : "default"}
              />
            </Tooltip>
          )}
        </TableCell>
      </TableRow>

      <TableRow>
        <TableCell colSpan={11} sx={{ p: 0, border: 0 }}>
          <Collapse in={expanded} unmountOnExit>
            <Box sx={{ p: 2, bgcolor: "action.hover" }}>
              {/* Header de factura estilo Estado de Cuenta */}
              <Paper
                variant="outlined"
                sx={{ p: 1.5, mb: 2, bgcolor: "primary.dark", color: "primary.contrastText" }}
              >
                <Typography variant="body2" fontWeight={700}>
                  Factura {factura.numero_formateado} · Emitida:{" "}
                  {fmtFechaCalendario(factura.fecha_emision)} · Total factura:{" "}
                  {factura.moneda} {fmt(factura.total_factura)}
                </Typography>
                <Typography variant="caption" sx={{ opacity: 0.9 }}>
                  Cuotas: {factura.cuotas_vencidas} vencidas /{" "}
                  {factura.cuotas_pendientes} pendientes / {factura.cuotas_total}{" "}
                  totales · Saldo factura: {factura.moneda}{" "}
                  {fmt(factura.saldo_pendiente)} · Vencido: {factura.moneda}{" "}
                  {fmt(factura.saldo_vencido)}
                </Typography>
              </Paper>

              <Grid container spacing={2}>
                <Grid item xs={12} md={6}>
                  <Typography variant="caption" color="text.secondary">
                    Items de la factura ({factura.items?.length || 0})
                  </Typography>
                  {factura.items?.length ? (
                    <Paper variant="outlined" sx={{ p: 1, mt: 0.5 }}>
                      <Stack spacing={0.5}>
                        {factura.items.map((it) => (
                          <Stack
                            key={it.id}
                            direction="row"
                            spacing={1}
                            alignItems="center"
                          >
                            <Chip
                              size="small"
                              label={fmt(it.dcantproser)}
                              variant="outlined"
                              sx={{ minWidth: 56 }}
                            />
                            <Typography variant="caption">×</Typography>
                            <Typography variant="body2" sx={{ flex: 1 }}>
                              {it.ddesproser}
                            </Typography>
                            <Typography
                              variant="caption"
                              color="text.secondary"
                              sx={{ minWidth: 90, textAlign: "right" }}
                            >
                              {fmt(it.duniproser)} c/u
                            </Typography>
                            <Typography
                              variant="body2"
                              fontWeight={600}
                              sx={{ minWidth: 110, textAlign: "right" }}
                            >
                              {fmt(it.dtotopeitem)}
                            </Typography>
                          </Stack>
                        ))}
                      </Stack>
                    </Paper>
                  ) : (
                    <Typography variant="body2" color="text.secondary">
                      Sin items registrados.
                    </Typography>
                  )}
                </Grid>
                <Grid item xs={12} md={6}>
                  <Typography variant="caption" color="text.secondary">
                    Detalle de cuotas pendientes
                  </Typography>
                  <Table size="small">
                    <TableHead>
                      <TableRow>
                        <TableCell>Cuota</TableCell>
                        <TableCell>Vencimiento</TableCell>
                        <TableCell align="center">Estado</TableCell>
                        <TableCell align="center">Días</TableCell>
                        <TableCell align="right">Monto Orig.</TableCell>
                        <TableCell align="right">Saldo Pend.</TableCell>
                      </TableRow>
                    </TableHead>
                    <TableBody>
                      {factura.cuotas.map((c) => {
                        const d = diasEntre(c.dvenccuo);
                        const a = antiguedadChip(d);
                        const vencida = d > 0;
                        return (
                          <TableRow key={c.id}>
                            <TableCell>#{c.dcuotas ?? "—"}</TableCell>
                            <TableCell>
                              {fmtFechaCalendario(c.dvenccuo)}
                            </TableCell>
                            <TableCell align="center">
                              <Chip
                                size="small"
                                label={vencida ? "Vencida" : "Por vencer"}
                                color={vencida ? "error" : "info"}
                              />
                            </TableCell>
                            <TableCell align="center">
                              {vencida ? (
                                <Chip size="small" label={a.label} color={a.color} />
                              ) : (
                                "—"
                              )}
                            </TableCell>
                            <TableCell align="right">
                              {fmt(c.dmoncuota)}
                            </TableCell>
                            <TableCell
                              align="right"
                              sx={{
                                color: vencida ? "error.main" : "text.primary",
                                fontWeight: 600,
                              }}
                            >
                              {fmt(c.saldo_pendiente ?? c.dmoncuota)}
                            </TableCell>
                          </TableRow>
                        );
                      })}
                    </TableBody>
                  </Table>
                </Grid>
              </Grid>
            </Box>
          </Collapse>
        </TableCell>
      </TableRow>
    </>
  );
}

export function NuevaGestionMoraModal({ open, onClose, onSuccess }) {
  const [clienteQuery, setClienteQuery] = useState("");
  const [clienteOptions, setClienteOptions] = useState([]);
  const [clienteSeleccionado, setClienteSeleccionado] = useState(null);
  const [searchingClientes, setSearchingClientes] = useState(false);

  const [facturas, setFacturas] = useState([]);
  const [loadingFacturas, setLoadingFacturas] = useState(false);
  const [facturasSel, setFacturasSel] = useState({});
  const [ordenar, setOrdenar] = useState("antiguedad");

  const [estado, setEstado] = useState(COB_MORA_ESTADO.GESTION_INTERNA);
  const [observacion, setObservacion] = useState("");
  const [submitting, setSubmitting] = useState(false);

  useEffect(() => {
    if (!open) {
      setClienteQuery("");
      setClienteOptions([]);
      setClienteSeleccionado(null);
      setFacturas([]);
      setFacturasSel({});
      setEstado(COB_MORA_ESTADO.GESTION_INTERNA);
      setObservacion("");
      setOrdenar("antiguedad");
    }
  }, [open]);

  useEffect(() => {
    if (clienteQuery.trim().length < 2) {
      setClienteOptions([]);
      return;
    }
    let cancel = false;
    setSearchingClientes(true);
    const t = setTimeout(async () => {
      try {
        const data = await searchClientes(clienteQuery, 15);
        if (!cancel) setClienteOptions(data || []);
      } finally {
        if (!cancel) setSearchingClientes(false);
      }
    }, 300);
    return () => {
      cancel = true;
      clearTimeout(t);
    };
  }, [clienteQuery]);

  useEffect(() => {
    if (!clienteSeleccionado) {
      setFacturas([]);
      setFacturasSel({});
      return;
    }
    let cancel = false;
    setLoadingFacturas(true);
    (async () => {
      try {
        const cuotas = await getCuotasPendientes(clienteSeleccionado.id);
        if (cancel) return;
        const porFactura = new Map();
        (cuotas || []).forEach((c) => {
          const fid = c.factura_cab_id;
          if (!fid) return;
          const fc = c.factura_cab ?? {};
          const prev = porFactura.get(fid) ?? {
            id: fid,
            numero_formateado: formatNroFactura(fc),
            fecha_emision: fc.dfeemide,
            total_factura: Number(fc.total_factura) || 0,
            moneda:
              typeof fc.moneda === "string"
                ? fc.moneda
                : fc.moneda?.codigo || fc.moneda?.simbolo || "PYG",
            saldo_pendiente: 0,
            saldo_vencido: 0,
            cuotas: [],
            items: fc.factura_det || [],
            promesas_count: 0,
            promesas_incumplidas: 0,
            vto_mas_viejo: null,
            cuotas_total: 0,
            cuotas_pendientes: 0,
            cuotas_vencidas: 0,
          };
          const saldo = Number(c.saldo_pendiente ?? c.dmoncuota ?? 0) || 0;
          prev.saldo_pendiente += saldo;
          prev.cuotas.push(c);
          prev.cuotas_pendientes += 1;
          if (diasEntre(c.dvenccuo) > 0) {
            prev.cuotas_vencidas += 1;
            prev.saldo_vencido += saldo;
          }
          if (!prev.vto_mas_viejo || new Date(c.dvenccuo) < new Date(prev.vto_mas_viejo)) {
            prev.vto_mas_viejo = c.dvenccuo;
          }
          (c.promesas || []).forEach((p) => {
            prev.promesas_count += 1;
            if (p.estado === "incumplida") prev.promesas_incumplidas += 1;
          });
          porFactura.set(fid, prev);
        });
        const list = Array.from(porFactura.values()).map((f) => ({
          ...f,
          cuotas_total: f.cuotas.length,
          dias_vencido: diasEntre(f.vto_mas_viejo),
        }));
        setFacturas(list);
      } catch (e) {
        toast.error("No se pudieron cargar las facturas pendientes");
      } finally {
        if (!cancel) setLoadingFacturas(false);
      }
    })();
    return () => {
      cancel = true;
    };
  }, [clienteSeleccionado]);

  const facturasOrdenadas = useMemo(() => {
    const arr = [...facturas];
    if (ordenar === "antiguedad")
      arr.sort((a, b) => b.dias_vencido - a.dias_vencido);
    if (ordenar === "saldo")
      arr.sort((a, b) => b.saldo_pendiente - a.saldo_pendiente);
    if (ordenar === "numero")
      arr.sort((a, b) =>
        a.numero_formateado.localeCompare(b.numero_formateado),
      );
    return arr;
  }, [facturas, ordenar]);

  const toggleFactura = (id) =>
    setFacturasSel((s) => ({ ...s, [id]: !s[id] }));

  const toggleTodas = () => {
    const allSelected =
      facturas.length > 0 && facturas.every((f) => facturasSel[f.id]);
    const next = {};
    if (!allSelected) facturas.forEach((f) => (next[f.id] = true));
    setFacturasSel(next);
  };

  const seleccionarVencidas = () => {
    const next = { ...facturasSel };
    facturas.forEach((f) => {
      if (f.dias_vencido > 0) next[f.id] = true;
    });
    setFacturasSel(next);
  };

  const facturasElegidas = useMemo(
    () => facturas.filter((f) => facturasSel[f.id]),
    [facturas, facturasSel],
  );

  const montoInvolucrado = useMemo(
    () => facturasElegidas.reduce((acc, f) => acc + f.saldo_pendiente, 0),
    [facturasElegidas],
  );

  const kpis = useMemo(() => {
    const vencidas = facturas.filter((f) => f.dias_vencido > 0);
    const saldoTotal = facturas.reduce((a, f) => a + f.saldo_pendiente, 0);
    const saldoVencido = vencidas.reduce((a, f) => a + f.saldo_pendiente, 0);
    const peorDia = facturas.reduce((m, f) => Math.max(m, f.dias_vencido), 0);
    const promesasIncumplidas = facturas.reduce(
      (a, f) => a + f.promesas_incumplidas,
      0,
    );
    return {
      cantFacturas: facturas.length,
      cantVencidas: vencidas.length,
      saldoTotal,
      saldoVencido,
      peorDia,
      promesasIncumplidas,
    };
  }, [facturas]);

  const persona = clienteSeleccionado?.personas || {};
  const cobrador = clienteSeleccionado?.cobrador;
  const nombreCliente =
    clienteSeleccionado?.nombre_fantasia ||
    persona.razon_social ||
    [persona.nombres, persona.apellidos].filter(Boolean).join(" ") ||
    "—";

  const handleSubmit = async () => {
    if (!clienteSeleccionado) return toast.error("Seleccioná un cliente");
    if (facturasElegidas.length === 0)
      return toast.error("Seleccioná al menos una factura");

    setSubmitting(true);
    try {
      await createGestionMora({
        cliente_id: clienteSeleccionado.id,
        estado_inicial: estado,
        monto_involucrado: montoInvolucrado,
        factura_ids: facturasElegidas.map((f) => f.id),
        observacion: observacion.trim() || undefined,
      });
      toast.success("Gestión de mora creada");
      onSuccess?.();
      onClose();
    } catch (e) {
      toast.error(e?.response?.data?.message || "No se pudo crear la gestión");
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <Dialog open={open} onClose={onClose} maxWidth="lg" fullWidth>
      <DialogTitle sx={{ display: "flex", alignItems: "center", gap: 1 }}>
        <Icon icon="mdi:gavel" width={22} />
        Nueva gestión de mora
      </DialogTitle>
      <DialogContent dividers>
        <Stack spacing={2} sx={{ pt: 1 }}>
          {/* ── Cliente search ──────────────────────────── */}
          <Autocomplete
            value={clienteSeleccionado}
            onChange={(_, val) => setClienteSeleccionado(val)}
            inputValue={clienteQuery}
            onInputChange={(_, val) => setClienteQuery(val)}
            options={clienteOptions}
            loading={searchingClientes}
            filterOptions={(x) => x}
            getOptionLabel={(o) => {
              const p = o?.personas ?? {};
              return (
                o?.nombre_fantasia ||
                p.razon_social ||
                [p.nombres, p.apellidos].filter(Boolean).join(" ") ||
                p.ruc ||
                ""
              );
            }}
            renderOption={(props, o) => {
              const p = o?.personas ?? {};
              const nombre =
                o?.nombre_fantasia ||
                p.razon_social ||
                [p.nombres, p.apellidos].filter(Boolean).join(" ") ||
                "—";
              const doc = p.ruc
                ? `RUC ${p.ruc}${p.dv ? `-${p.dv}` : ""}`
                : p.nro_documento || "";
              return (
                <li {...props} key={o.id}>
                  <Box>
                    <Typography variant="body2">{nombre}</Typography>
                    {doc && (
                      <Typography variant="caption" color="text.secondary">
                        {doc}
                      </Typography>
                    )}
                  </Box>
                </li>
              );
            }}
            isOptionEqualToValue={(o, v) => o?.id === v?.id}
            renderInput={(params) => (
              <TextField
                {...params}
                label="Cliente"
                size="small"
                placeholder="Buscar por nombre, RUC o documento..."
                InputProps={{
                  ...params.InputProps,
                  endAdornment: (
                    <>
                      {searchingClientes && <CircularProgress size={16} />}
                      {params.InputProps.endAdornment}
                    </>
                  ),
                }}
              />
            )}
          />

          {/* ── Ficha del cliente ──────────────────────── */}
          {clienteSeleccionado && (
            <Paper variant="outlined" sx={{ p: 2 }}>
              <Stack direction="row" spacing={2} alignItems="flex-start">
                <Avatar sx={{ bgcolor: "primary.main" }}>
                  <Icon icon="mdi:account-cash" />
                </Avatar>
                <Box flex={1}>
                  <Typography variant="subtitle1" fontWeight={700}>
                    {nombreCliente}
                  </Typography>
                  <Stack direction="row" spacing={1} flexWrap="wrap" mt={0.5}>
                    {persona.ruc && (
                      <Chip
                        size="small"
                        icon={<Icon icon="mdi:identifier" />}
                        label={`RUC ${persona.ruc}${persona.dv ? `-${persona.dv}` : ""}`}
                      />
                    )}
                    {persona.telefono && (
                      <Chip
                        size="small"
                        icon={<Icon icon="mdi:phone" />}
                        label={persona.telefono}
                      />
                    )}
                    {persona.email && (
                      <Chip
                        size="small"
                        icon={<Icon icon="mdi:email-outline" />}
                        label={persona.email}
                      />
                    )}
                    {clienteSeleccionado.zona && (
                      <Chip
                        size="small"
                        icon={<Icon icon="mdi:map-marker" />}
                        label={clienteSeleccionado.zona}
                      />
                    )}
                    {cobrador && (
                      <Chip
                        size="small"
                        icon={<Icon icon="mdi:account-tie" />}
                        label={`Cobrador: ${cobrador.nombre} ${cobrador.apellido ?? ""}`}
                      />
                    )}
                  </Stack>
                  {persona.direccion && (
                    <Typography variant="caption" color="text.secondary" mt={1} display="block">
                      <Icon icon="mdi:map-marker-outline" /> {persona.direccion}
                    </Typography>
                  )}
                </Box>
              </Stack>

              {/* KPIs */}
              <Divider sx={{ my: 2 }} />
              <Grid container spacing={2}>
                <Grid item xs={6} sm={3}>
                  <Typography variant="caption" color="text.secondary">
                    Facturas pendientes
                  </Typography>
                  <Typography variant="h6">
                    {kpis.cantFacturas}
                    <Typography component="span" variant="caption" color="error.main" ml={0.5}>
                      ({kpis.cantVencidas} venc.)
                    </Typography>
                  </Typography>
                </Grid>
                <Grid item xs={6} sm={3}>
                  <Typography variant="caption" color="text.secondary">
                    Saldo total
                  </Typography>
                  <Typography variant="h6">Gs. {fmt(kpis.saldoTotal)}</Typography>
                </Grid>
                <Grid item xs={6} sm={3}>
                  <Typography variant="caption" color="text.secondary">
                    Saldo vencido
                  </Typography>
                  <Typography variant="h6" color="error.main">
                    Gs. {fmt(kpis.saldoVencido)}
                  </Typography>
                </Grid>
                <Grid item xs={6} sm={3}>
                  <Typography variant="caption" color="text.secondary">
                    Peor antigüedad
                  </Typography>
                  <Typography variant="h6">
                    {kpis.peorDia > 0 ? `${kpis.peorDia} días` : "—"}
                  </Typography>
                </Grid>
              </Grid>
              {kpis.promesasIncumplidas > 0 && (
                <Alert severity="warning" icon={<Icon icon="mdi:alert" />} sx={{ mt: 1 }}>
                  Cliente con <b>{kpis.promesasIncumplidas} promesa(s) incumplida(s)</b> previamente. Considerar escalar a Informconf.
                </Alert>
              )}
            </Paper>
          )}

          {/* ── Tabla de facturas ──────────────────────── */}
          {clienteSeleccionado && (
            <Box>
              <Stack direction="row" alignItems="center" spacing={1} mb={1}>
                <Typography variant="subtitle2">Facturas pendientes</Typography>
                <Box flex={1} />
                <TextField
                  select
                  size="small"
                  label="Ordenar por"
                  value={ordenar}
                  onChange={(e) => setOrdenar(e.target.value)}
                  sx={{ minWidth: 160 }}
                >
                  <MenuItem value="antiguedad">Antigüedad</MenuItem>
                  <MenuItem value="saldo">Mayor saldo</MenuItem>
                  <MenuItem value="numero">N° factura</MenuItem>
                </TextField>
                {facturas.length > 0 && (
                  <>
                    <Button size="small" onClick={seleccionarVencidas}>
                      Solo vencidas
                    </Button>
                    <Button size="small" onClick={toggleTodas}>
                      {facturas.every((f) => facturasSel[f.id])
                        ? "Limpiar"
                        : "Todas"}
                    </Button>
                  </>
                )}
              </Stack>

              {loadingFacturas ? (
                <Box display="flex" justifyContent="center" py={3}>
                  <CircularProgress size={24} />
                </Box>
              ) : facturas.length === 0 ? (
                <Alert severity="info">
                  El cliente no tiene facturas pendientes.
                </Alert>
              ) : (
                <Paper variant="outlined" sx={{ maxHeight: 360, overflow: "auto" }}>
                  <Table size="small" stickyHeader>
                    <TableHead>
                      <TableRow>
                        <TableCell padding="checkbox" />
                        <TableCell sx={{ width: 36 }} />
                        <TableCell>N° Factura</TableCell>
                        <TableCell>Emisión</TableCell>
                        <TableCell>Vto. más viejo</TableCell>
                        <TableCell align="center">Días</TableCell>
                        <TableCell align="center">Cuotas</TableCell>
                        <TableCell>Mon.</TableCell>
                        <TableCell align="right">Total</TableCell>
                        <TableCell align="right">Saldo</TableCell>
                        <TableCell align="center">Promesas</TableCell>
                      </TableRow>
                    </TableHead>
                    <TableBody>
                      {facturasOrdenadas.map((f) => (
                        <FacturaRow
                          key={f.id}
                          factura={f}
                          selected={!!facturasSel[f.id]}
                          onToggle={() => toggleFactura(f.id)}
                        />
                      ))}
                    </TableBody>
                  </Table>
                </Paper>
              )}
            </Box>
          )}

          {/* ── Estado + observación ───────────────────── */}
          <Stack direction={{ xs: "column", sm: "row" }} spacing={2}>
            <TextField
              select
              label="Estado inicial"
              value={estado}
              onChange={(e) => setEstado(e.target.value)}
              size="small"
              sx={{ minWidth: 220 }}
            >
              {ESTADOS_INICIALES.map((est) => (
                <MenuItem key={est} value={est}>
                  {COB_MORA_ESTADO_META[est]?.label}
                </MenuItem>
              ))}
            </TextField>
            <TextField
              label="Observación / motivo de apertura"
              value={observacion}
              onChange={(e) => setObservacion(e.target.value)}
              multiline
              minRows={2}
              size="small"
              fullWidth
              placeholder="Resumen del contacto, motivo, próximos pasos..."
            />
          </Stack>
        </Stack>
      </DialogContent>

      {/* ── Footer sticky con totales ─────────────────── */}
      <DialogActions sx={{ justifyContent: "space-between", px: 3 }}>
        <Stack direction="row" spacing={2} alignItems="center">
          <Box>
            <Typography variant="caption" color="text.secondary">
              Monto a gestionar
            </Typography>
            <Typography variant="h6" color="warning.main">
              Gs. {fmt(montoInvolucrado)}
            </Typography>
          </Box>
          <Chip
            size="small"
            label={`${facturasElegidas.length} factura(s)`}
            color={facturasElegidas.length > 0 ? "primary" : "default"}
          />
        </Stack>
        <Stack direction="row" spacing={1}>
          <Button onClick={onClose} disabled={submitting}>
            Cancelar
          </Button>
          <Button
            onClick={handleSubmit}
            variant="contained"
            disabled={submitting || facturasElegidas.length === 0}
            startIcon={<Icon icon="mdi:gavel" />}
          >
            {submitting ? "Guardando..." : "Crear gestión"}
          </Button>
        </Stack>
      </DialogActions>
    </Dialog>
  );
}

export default NuevaGestionMoraModal;
