import { Icon } from "@iconify/react/dist/iconify.js";
import {
  Alert,
  Box,
  Button,
  Chip,
  CircularProgress,
  Dialog,
  DialogContent,
  DialogTitle,
  Divider,
  Grid,
  IconButton,
  Paper,
  Skeleton,
  Stack,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  TextField,
  Tooltip,
  Typography,
  alpha,
  useMediaQuery,
  useTheme,
} from "@mui/material";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { toast } from "sonner";
import { useEmpresa } from "../../context/EmpresaContext";
import { useConfirmDialog } from "../../hooks/useConfirmDialog";
import {
  aprobarOrdenVenta,
  cancelarOrdenVenta,
  confirmarOrdenVenta,
  getOrdenVenta,
  getOrdenVentaItemsFacturados,
  iniciarOrdenVenta,
} from "../../api/ordenes.service";
import { formatMoney } from "../../utils/formatMoney";

// ─── Config de estados ────────────────────────────────────────────────────────

const ESTADOS = {
  borrador:          { label: "Borrador",      color: "default",   icon: "mdi:file-edit-outline",           muiColor: "text.secondary",  bannerColor: "info" },
  confirmada:        { label: "Confirmada",    color: "primary",   icon: "mdi:check-circle-outline",        muiColor: "primary.main",    bannerColor: "info" },
  aprobada:          { label: "Aprobada",      color: "info",      icon: "mdi:thumb-up-outline",            muiColor: "info.main",       bannerColor: "info" },
  en_proceso:        { label: "En proceso",    color: "warning",   icon: "mdi:progress-clock",              muiColor: "warning.main",    bannerColor: "warning" },
  facturada_parcial: { label: "Fact. parcial", color: "secondary", icon: "mdi:receipt-text-clock-outline",  muiColor: "secondary.main",  bannerColor: "warning" },
  facturada:         { label: "Facturada",     color: "success",   icon: "mdi:receipt-text-check-outline",  muiColor: "success.main",    bannerColor: "success" },
  cancelada:         { label: "Cancelada",     color: "error",     icon: "mdi:close-circle-outline",        muiColor: "error.main",      bannerColor: "error" },
  vencida:           { label: "Vencida",       color: "error",     icon: "mdi:calendar-remove-outline",     muiColor: "error.main",      bannerColor: "error" },
};

const BANNER_MSG = {
  borrador:          "La orden está en borrador. Podés editarla y luego confirmarla para asignarle número.",
  confirmada:        "Confirmada y con número asignado. Está esperando la aprobación de un supervisor.",
  aprobada:          "Aprobada administrativamente. Al iniciar el proceso, el equipo de depósito/logística comienza la preparación y despacho de los productos.",
  en_proceso:        "En ejecución — el depósito está preparando o despachando los productos. Próximamente podrás emitir la factura desde aquí.",
  facturada_parcial: "Al menos una factura emitida. Quedan ítems o montos pendientes de facturar.",
  facturada:         "Completamente facturada. Esta orden se cerró exitosamente.",
  cancelada:         "Esta orden fue cancelada. El stock reservado fue liberado.",
  vencida:           "La orden superó su fecha de vencimiento y fue cerrada automáticamente.",
};

// ─── Helpers ──────────────────────────────────────────────────────────────────

function fmt(str, withTime = false) {
  if (!str) return null;
  const d = new Date(str);
  if (isNaN(d)) return null;
  const fecha = d.toLocaleDateString("es-PY");
  if (!withTime) return fecha;
  const hora = d.toLocaleTimeString("es-PY", { hour: "2-digit", minute: "2-digit" });
  return `${fecha} — ${hora}`;
}

function getNombreCliente(orden) {
  return orden.cliente?.personas?.razon_social || orden.cliente?.nombre_fantasia || "—";
}

function getOrigenOrdenLabel(orden) {
  const tipo = String(orden?.origen_tipo || "").toLowerCase();
  if (tipo === "presupuesto" || orden?.presupuesto_id) return "Presupuesto";
  if (tipo === "solicitud_credito") return "Solicitud de crédito";
  if (tipo === "importacion") return "Importación";
  if (tipo === "otro") return "Otro";
  return "Manual";
}

// ─── Sub-componentes ──────────────────────────────────────────────────────────

function LabelValue({ label, value, mono = false }) {
  if (!value && value !== 0) return null;
  return (
    <Box sx={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", gap: 1, py: 0.35 }}>
      <Typography variant="caption" color="text.secondary" sx={{ flexShrink: 0 }}>
        {label}
      </Typography>
      <Typography
        variant="body2"
        fontWeight={500}
        textAlign="right"
        fontFamily={mono ? "monospace" : undefined}
        sx={{ wordBreak: "break-word" }}
      >
        {value}
      </Typography>
    </Box>
  );
}

function SectionHeader({ icon, title }) {
  return (
    <Box sx={{ display: "flex", alignItems: "center", gap: 0.75, mb: 1 }}>
      <Icon icon={icon} width={15} style={{ opacity: 0.6 }} />
      <Typography variant="caption" fontWeight={700} color="text.secondary" letterSpacing={0.5} textTransform="uppercase">
        {title}
      </Typography>
    </Box>
  );
}

function TimelineItem({ entry, isLast }) {
  const info = ESTADOS[entry.estado] ?? {};
  return (
    <Box sx={{ display: "flex", gap: 1.5 }}>
      {/* dot + line */}
      <Box sx={{ display: "flex", flexDirection: "column", alignItems: "center", width: 20, flexShrink: 0 }}>
        <Box sx={{
          width: 20, height: 20, borderRadius: "50%",
          bgcolor: (t) => {
            const map = { default: t.palette.action.disabled, primary: t.palette.primary.main, info: t.palette.info.main, warning: t.palette.warning.main, success: t.palette.success.main, error: t.palette.error.main, secondary: t.palette.secondary.main };
            return map[info.color] ?? t.palette.action.disabled;
          },
          display: "flex", alignItems: "center", justifyContent: "center",
        }}>
          <Icon icon={info.icon ?? "mdi:circle"} width={11} color="#fff" />
        </Box>
        {!isLast && <Box sx={{ width: 2, flex: 1, bgcolor: "divider", my: 0.5, minHeight: 14 }} />}
      </Box>
      {/* content */}
      <Box sx={{ pb: isLast ? 0 : 1.5, flex: 1 }}>
        <Typography variant="body2" fontWeight={500} lineHeight={1.3}>
          {entry.descripcion || info.label}
        </Typography>
        <Typography variant="caption" color="text.disabled">
          {fmt(entry.created_at, true)} · {entry.usuario?.username ?? "Sistema"}
        </Typography>
      </Box>
    </Box>
  );
}

// ─── Stepper de flujo de estados ─────────────────────────────────────────────

const PASO_APROBACION = {
  key: "aprobada", label: "Aprobada", icon: "mdi:thumb-up-outline",
  desc: "Un supervisor autoriza el inicio del proceso de entrega",
};
const PASO_FACT_PARCIAL = {
  key: "facturada_parcial", label: "Fact. parcial", icon: "mdi:receipt-text-clock-outline",
  desc: "Al menos una factura emitida — quedan ítems o montos pendientes",
};

function buildPasos(requiereAprobacion, tipoFacturacion) {
  const base = [
    { key: "borrador",   label: "Borrador",   icon: "mdi:file-edit-outline" },
    { key: "confirmada", label: "Confirmada", icon: "mdi:check-circle-outline" },
  ];
  if (requiereAprobacion) base.push(PASO_APROBACION);
  base.push({ key: "en_proceso", label: "En proceso", icon: "mdi:progress-clock", desc: "El depósito prepara y despacha los productos" });
  if (tipoFacturacion && tipoFacturacion !== "total") base.push(PASO_FACT_PARCIAL);
  base.push({ key: "facturada", label: "Facturada", icon: "mdi:receipt-text-check-outline" });
  return base;
}

function EstadoStepper({ estadoActual, requiereAprobacion, tipoFacturacion }) {
  const theme = useTheme();
  const pasos = buildPasos(requiereAprobacion, tipoFacturacion);

  const ORDER = ["borrador", "confirmada", "aprobada", "en_proceso", "facturada_parcial", "facturada"];
  const estadoIdx = ORDER.indexOf(estadoActual);
  const esCancelada = ["cancelada", "vencida"].includes(estadoActual);

  return (
    <Box sx={{
      px: 2.5, py: 1.25,
      bgcolor: alpha(theme.palette.background.paper, 0.5),
      borderBottom: 1, borderColor: "divider",
      display: "flex", alignItems: "center", gap: 0,
      overflowX: "auto",
    }}>
      {pasos.map((paso, i) => {
        const pasoOrdIdx = ORDER.indexOf(paso.key);
        const done    = !esCancelada && pasoOrdIdx < estadoIdx;
        const current = !esCancelada && pasoOrdIdx === estadoIdx;
        const pending = esCancelada || pasoOrdIdx > estadoIdx;

        const dotColor = done    ? theme.palette.success.main
                        : current ? (ESTADOS[paso.key]?.muiColor
                            ? theme.palette[ESTADOS[paso.key].muiColor.split(".")[0]]?.[ESTADOS[paso.key].muiColor.split(".")[1]] ?? theme.palette.warning.main
                            : theme.palette.primary.main)
                        : theme.palette.action.disabled;

        return (
          <Box key={paso.key} sx={{ display: "flex", alignItems: "center", flexShrink: 0 }}>
            <Tooltip title={paso.desc ?? ""} arrow placement="bottom" disableHoverListener={!paso.desc}>
              <Box sx={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 0.25, px: 1 }}>
                <Box sx={{
                  width: 28, height: 28, borderRadius: "50%",
                  bgcolor: done ? alpha(theme.palette.success.main, 0.15) : current ? alpha(dotColor, 0.15) : "transparent",
                  border: `2px solid ${done ? theme.palette.success.main : current ? dotColor : theme.palette.divider}`,
                  display: "flex", alignItems: "center", justifyContent: "center",
                  transition: "all 0.2s",
                }}>
                  <Icon
                    icon={done ? "mdi:check" : paso.icon}
                    width={14}
                    color={done ? theme.palette.success.main : current ? dotColor : theme.palette.text.disabled}
                  />
                </Box>
                <Typography
                  variant="caption"
                  fontWeight={current ? 700 : 400}
                  color={done ? "success.main" : current ? undefined : "text.disabled"}
                  sx={{ color: current ? dotColor : undefined, whiteSpace: "nowrap", fontSize: "0.68rem" }}
                >
                  {paso.label}
                </Typography>
              </Box>
            </Tooltip>
            {i < pasos.length - 1 && (
              <Box sx={{ width: { xs: 16, sm: 28 }, height: 2, bgcolor: done ? theme.palette.success.main : "divider", flexShrink: 0, mx: -0.5 }} />
            )}
          </Box>
        );
      })}
      {esCancelada && (
        <Typography variant="caption" color="error" fontWeight={600} sx={{ ml: "auto" }}>
          <Icon icon="mdi:close-circle" width={13} style={{ verticalAlign: "middle", marginRight: 3 }} />
          {ESTADOS[estadoActual]?.label}
        </Typography>
      )}
    </Box>
  );
}

// ─── Dialog de cancelación ────────────────────────────────────────────────────

function CancelarDialog({ open, onClose, onConfirm, loading }) {
  const [motivo, setMotivo] = useState("");
  return (
    <Dialog open={open} onClose={onClose} maxWidth="xs" fullWidth>
      <DialogTitle sx={{ display: "flex", alignItems: "center", gap: 1 }}>
        <Icon icon="mdi:alert-circle" width={20} color="var(--mui-palette-error-main)" />
        Cancelar orden de venta
      </DialogTitle>
      <DialogContent>
        <Alert severity="warning" sx={{ mb: 2 }}>
          Esta acción no se puede deshacer. El stock reservado será liberado automáticamente.
        </Alert>
        <TextField
          label="Motivo de cancelación"
          placeholder="Ej: Cliente solicitó cancelar, stock insuficiente…"
          fullWidth multiline rows={3} size="small"
          value={motivo}
          onChange={(e) => setMotivo(e.target.value)}
          helperText="Opcional — quedará registrado en el historial."
        />
      </DialogContent>
      <Box sx={{ display: "flex", gap: 1, justifyContent: "flex-end", px: 3, pb: 2.5 }}>
        <Button onClick={onClose} disabled={loading} variant="outlined">Volver</Button>
        <Button
          variant="contained" color="error"
          onClick={() => onConfirm(motivo)}
          disabled={loading}
          startIcon={loading ? <CircularProgress size={14} /> : <Icon icon="mdi:close-circle" width={16} />}
        >
          Confirmar cancelación
        </Button>
      </Box>
    </Dialog>
  );
}

// ─── Componente principal ─────────────────────────────────────────────────────

export function OrdenVentaDetalleDialog({ open, onClose, ordenId }) {
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down("sm"));
  const isMd = useMediaQuery(theme.breakpoints.down("md"));
  const { empresa } = useEmpresa();
  const requiereAprobacion = empresa?.orden_requiere_aprobacion ?? true;
  const [cancelarOpen, setCancelarOpen] = useState(false);
  const { confirm, dialogs } = useConfirmDialog();

  const handleFacturar = async () => {
    const ok = await confirm({
      title: "¿Facturar esta orden?",
      message:
        "Se abrirá el POS con la orden precargada (cliente, ítems y descuentos) para que emitas la factura. Podés revisar y ajustar antes de confirmar.",
      confirmText: "Sí, facturar",
      confirmColor: "success",
    });
    if (!ok) return;
    onClose();
    navigate(`/pos?orden=${ordenId}`);
  };

  const { data: orden, isLoading } = useQuery({
    queryKey: ["ordenes-venta", "detalle", ordenId],
    queryFn: () => getOrdenVenta(ordenId),
    select: (r) => r?.data ?? r,
    enabled: open && !!ordenId,
  });

  const { data: itemsFacturados } = useQuery({
    queryKey: ["ordenes-venta", "items-facturados", ordenId],
    queryFn: () => getOrdenVentaItemsFacturados(ordenId),
    enabled: open && !!ordenId && ["aprobada", "en_proceso", "facturada_parcial", "facturada"].includes(orden?.estado_orden ?? ""),
    refetchOnWindowFocus: false,
  });

  const invalidar = () => {
    queryClient.invalidateQueries({ queryKey: ["ordenes-venta", "detalle", ordenId] });
    queryClient.invalidateQueries({ queryKey: ["ordenes-venta", "items-facturados", ordenId] });
    queryClient.invalidateQueries({ queryKey: ["ordenes-venta", "list"] });
    queryClient.invalidateQueries({ queryKey: ["ordenes-venta", "stats"] });
  };

  const mk = (fn, msg) => ({
    mutationFn: fn,
    onSuccess: (res) => { toast.success(res?.message ?? msg); invalidar(); },
    onError: (e) => toast.error(e?.response?.data?.message ?? `Error: ${msg.toLowerCase()}`),
  });

  const confirmarMut = useMutation(mk(() => confirmarOrdenVenta(ordenId), "Orden confirmada"));
  const aprobarMut   = useMutation(mk(() => aprobarOrdenVenta(ordenId),   "Orden aprobada"));
  const iniciarMut   = useMutation(mk(() => iniciarOrdenVenta(ordenId),   "Orden en proceso"));
  const cancelarMut  = useMutation({
    mutationFn: (motivo) => cancelarOrdenVenta(ordenId, motivo),
    onSuccess: () => { toast.success("Orden cancelada"); invalidar(); setCancelarOpen(false); },
    onError: (e) => toast.error(e?.response?.data?.message ?? "Error al cancelar"),
  });

  const anyPending = [confirmarMut, aprobarMut, iniciarMut, cancelarMut].some((m) => m.isPending);
  const estado = orden?.estado_orden;
  const estadoInfo = ESTADOS[estado] ?? {};
  const items = orden?.detalle ?? [];
  const historial = orden?.historial ?? [];
  const total = Number(orden?.total ?? 0);
  const totalIva = Number(orden?.total_iva ?? 0);
  const totalDesc = Number(orden?.total_descuento ?? 0);
  const subtotal = Number(orden?.subtotal ?? 0);
  const montoFact = Number(orden?.monto_facturado ?? 0);
  const moneda = orden?.moneda?.simbolo ?? "Gs.";

  return (
    <>
      <Dialog
        open={open}
        onClose={onClose}
        maxWidth="lg"
        fullWidth
        fullScreen={isMobile}
        PaperProps={{ sx: { height: isMobile ? "100%" : "88vh", display: "flex", flexDirection: "column" } }}
      >
        {/* ══ Barra de título ═══════════════════════════════════════ */}
        <DialogTitle
          sx={{
            display: "flex", alignItems: "center", gap: 1.5,
            borderBottom: 1, borderColor: "divider",
            py: 1.5, px: 2.5, flexShrink: 0,
          }}
        >
          {isLoading ? (
            <Skeleton width={200} height={28} />
          ) : (
            <>
              <Typography variant="h6" fontFamily="monospace" fontWeight={700} sx={{ flexShrink: 0 }}>
                {orden?.numero_pedido ?? (
                  <Box component="span" sx={{ fontStyle: "italic", color: "text.disabled", fontSize: "0.9rem" }}>
                    Sin número
                  </Box>
                )}
              </Typography>
              <Chip
                size="small"
                label={estadoInfo.label}
                color={estadoInfo.color ?? "default"}
                icon={estadoInfo.icon ? <Icon icon={estadoInfo.icon} width={13} /> : undefined}
              />
              {orden?.stock_reservado && (
                <Tooltip title="Stock reservado para esta orden">
                  <Chip size="small" label="Stock res." icon={<Icon icon="mdi:package-variant-closed" width={12} />} variant="outlined" />
                </Tooltip>
              )}
            </>
          )}

          <Box sx={{ flex: 1 }} />

          {/* Acciones primarias */}
          {!isLoading && orden && (
            <Stack direction="row" spacing={1} sx={{ flexWrap: "nowrap" }}>
              {estado === "borrador" && (
                <Tooltip title="Editar datos de la orden">
                  <Button size="small" variant="outlined"
                    startIcon={<Icon icon="mdi:pencil" width={15} />}
                    onClick={() => { onClose(); navigate(`/ordenes-venta/${ordenId}/editar`); }}
                  >
                    {!isMobile && "Editar"}
                  </Button>
                </Tooltip>
              )}
              {estado === "borrador" && (
                <Tooltip title="Asigna número y envía a revisión">
                  <Button size="small" variant="contained" color="primary"
                    startIcon={anyPending ? <CircularProgress size={14} color="inherit" /> : <Icon icon="mdi:check-circle" width={15} />}
                    onClick={() => confirmarMut.mutate()} disabled={anyPending}
                  >
                    Confirmar
                  </Button>
                </Tooltip>
              )}
              {estado === "confirmada" && (
                <Tooltip title="Autoriza el inicio del proceso de entrega">
                  <Button size="small" variant="contained" color="success"
                    startIcon={anyPending ? <CircularProgress size={14} color="inherit" /> : <Icon icon="mdi:thumb-up" width={15} />}
                    onClick={() => aprobarMut.mutate()} disabled={anyPending}
                  >
                    Aprobar
                  </Button>
                </Tooltip>
              )}
              {estado === "aprobada" && (
                <Tooltip title="Pone la orden en ejecución activa">
                  <Button size="small" variant="contained" color="warning"
                    sx={{ color: "warning.contrastText" }}
                    startIcon={anyPending ? <CircularProgress size={14} color="inherit" /> : <Icon icon="mdi:progress-clock" width={15} />}
                    onClick={() => iniciarMut.mutate()} disabled={anyPending}
                  >
                    Iniciar proceso
                  </Button>
                </Tooltip>
              )}
              {["en_proceso", "facturada_parcial"].includes(estado) && (
                <Tooltip title="Abre el POS con esta orden precargada para emitir la factura">
                  <Button size="small" variant="contained" color="success"
                    startIcon={<Icon icon="mdi:receipt-text-plus" width={15} />}
                    onClick={handleFacturar}
                  >
                    Facturar
                  </Button>
                </Tooltip>
              )}
              {["borrador", "confirmada", "aprobada", "en_proceso"].includes(estado) && (
                <Tooltip title="Cancela la orden y libera el stock reservado">
                  <Button size="small" variant="outlined" color="error"
                    startIcon={<Icon icon="mdi:close-circle" width={15} />}
                    onClick={() => setCancelarOpen(true)} disabled={anyPending}
                  >
                    {!isMobile && "Cancelar"}
                  </Button>
                </Tooltip>
              )}
            </Stack>
          )}

          <IconButton size="small" onClick={onClose} sx={{ ml: 0.5, flexShrink: 0 }}>
            <Icon icon="mdi:close" width={18} />
          </IconButton>
        </DialogTitle>

        {/* ══ Contenido ═════════════════════════════════════════════ */}
        <DialogContent sx={{ p: 0, flex: 1, overflow: "hidden", display: "flex", flexDirection: "column" }}>

          {/* Stepper de flujo */}
          {!isLoading && estado && (
            <EstadoStepper estadoActual={estado} requiereAprobacion={requiereAprobacion} tipoFacturacion={orden?.tipo_facturacion} />
          )}

          {/* Banner de estado */}
          {!isLoading && estado && BANNER_MSG[estado] && (
            <Alert
              severity={estadoInfo.bannerColor ?? "info"}
              icon={<Icon icon={estadoInfo.icon ?? "mdi:information"} width={18} />}
              sx={{ borderRadius: 0, py: 0.75, px: 2.5 }}
            >
              <Typography variant="body2">{BANNER_MSG[estado]}</Typography>
            </Alert>
          )}

          <Box sx={{ flex: 1, overflow: "auto", p: { xs: 1.5, sm: 2.5 } }}>
            {isLoading ? (
              <Grid container spacing={2.5}>
                <Grid item xs={12} md={7}>
                  <Skeleton variant="rectangular" height={180} sx={{ borderRadius: 1, mb: 2 }} />
                  <Skeleton variant="rectangular" height={120} sx={{ borderRadius: 1 }} />
                </Grid>
                <Grid item xs={12} md={5}>
                  <Skeleton variant="rectangular" height={320} sx={{ borderRadius: 1 }} />
                </Grid>
              </Grid>
            ) : !orden ? (
              <Alert severity="error">No se pudo cargar la orden.</Alert>
            ) : (
              <Grid container spacing={2.5}>

                {/* ─── Columna izquierda: items + historial ─────── */}
                <Grid item xs={12} md={7}>

                  {/* Tabla de ítems */}
                  <Paper variant="outlined" sx={{ mb: 2.5, overflow: "hidden" }}>
                    <Box sx={{
                      px: 2, py: 1.25,
                      bgcolor: (t) => alpha(t.palette.action.hover, 0.04),
                      borderBottom: 1, borderColor: "divider",
                      display: "flex", alignItems: "center", gap: 1,
                    }}>
                      <Icon icon="mdi:format-list-bulleted" width={15} style={{ opacity: 0.6 }} />
                      <Typography variant="subtitle2">
                        Ítems
                        <Box component="span" sx={{ ml: 0.75, color: "text.disabled", fontWeight: 400 }}>
                          ({items.length})
                        </Box>
                      </Typography>
                    </Box>

                    {items.length === 0 ? (
                      <Box sx={{ py: 4, textAlign: "center" }}>
                        <Icon icon="mdi:package-variant-remove" width={32} style={{ opacity: 0.2 }} />
                        <Typography color="text.disabled" variant="body2" mt={0.5}>Sin ítems registrados</Typography>
                      </Box>
                    ) : (
                      <TableContainer>
                        <Table size="small">
                          <TableHead>
                            <TableRow sx={{ "& th": { fontWeight: 600, fontSize: "0.75rem", color: "text.secondary", bgcolor: (t) => alpha(t.palette.action.hover, 0.03) } }}>
                              <TableCell sx={{ width: 32 }}>#</TableCell>
                              <TableCell>Producto</TableCell>
                              {!isMd && <TableCell>Presentación</TableCell>}
                              <TableCell align="right">Cant.</TableCell>
                              {itemsFacturados?.facturas?.length > 0 && <>
                                <TableCell align="right" sx={{ color: "success.main" }}>Fact.</TableCell>
                                <TableCell align="right" sx={{ color: "warning.main" }}>Pend.</TableCell>
                              </>}
                              <TableCell align="right">Precio unit.</TableCell>
                              {!isMd && <TableCell align="right">Desc.</TableCell>}
                              <TableCell align="right">Total</TableCell>
                            </TableRow>
                          </TableHead>
                          <TableBody>
                            {items.map((it) => {
                              const progreso = itemsFacturados?.items?.find((f) => f.pedido_detalle_id === it.id);
                              return (
                              <TableRow key={it.id ?? it.item} hover sx={{ "&:last-child td": { border: 0 } }}>
                                <TableCell>
                                  <Typography variant="caption" color="text.disabled">{it.item}</Typography>
                                </TableCell>
                                <TableCell>
                                  <Typography variant="body2" fontWeight={500}>{it.producto?.descripcion ?? "—"}</Typography>
                                  {it.producto?.codigo_barra && (
                                    <Typography variant="caption" color="text.disabled">{it.producto.codigo_barra}</Typography>
                                  )}
                                </TableCell>
                                {!isMd && (
                                  <TableCell>
                                    <Typography variant="caption" color="text.secondary">{it.presentacion?.abreviatura ?? it.presentacion?.nombre ?? "—"}</Typography>
                                  </TableCell>
                                )}
                                <TableCell align="right">
                                  <Typography variant="body2">{Number(it.cantidad ?? it.cantidad_base ?? 0).toLocaleString("es-PY")}</Typography>
                                </TableCell>
                                {itemsFacturados?.facturas?.length > 0 && <>
                                  <TableCell align="right">
                                    <Typography variant="body2" color={progreso?.cantidad_facturada > 0 ? "success.main" : "text.disabled"} fontWeight={progreso?.cantidad_facturada > 0 ? 600 : 400}>
                                      {progreso ? progreso.cantidad_facturada.toLocaleString("es-PY") : "—"}
                                    </Typography>
                                  </TableCell>
                                  <TableCell align="right">
                                    <Typography variant="body2" color={progreso?.cantidad_pendiente === 0 ? "text.disabled" : "warning.main"} fontWeight={progreso?.cantidad_pendiente > 0 ? 600 : 400}>
                                      {progreso ? progreso.cantidad_pendiente.toLocaleString("es-PY") : "—"}
                                    </Typography>
                                  </TableCell>
                                </>}
                                <TableCell align="right">
                                  <Typography variant="body2">{formatMoney(Number(it.precio_negociado ?? it.precio_unitario ?? 0))}</Typography>
                                </TableCell>
                                {!isMd && (
                                  <TableCell align="right">
                                    {Number(it.descuento_porcentaje) > 0 ? (
                                      <Chip size="small" label={`${it.descuento_porcentaje}%`} color="warning" variant="outlined" sx={{ height: 18, fontSize: "0.7rem" }} />
                                    ) : (
                                      <Typography variant="caption" color="text.disabled">—</Typography>
                                    )}
                                  </TableCell>
                                )}
                                <TableCell align="right">
                                  <Typography variant="body2" fontWeight={700}>{formatMoney(Number(it.total_item ?? it.subtotal ?? 0))}</Typography>
                                </TableCell>
                              </TableRow>
                              );
                            })}
                          </TableBody>
                        </Table>
                      </TableContainer>
                    )}
                  </Paper>

                  {/* Progreso de Facturación */}
                  {itemsFacturados?.facturas?.length > 0 && (
                    <Paper variant="outlined" sx={{ overflow: "hidden" }}>
                      <Box sx={{
                        px: 2, py: 1.25,
                        bgcolor: (t) => alpha(t.palette.action.hover, 0.04),
                        borderBottom: 1, borderColor: "divider",
                        display: "flex", alignItems: "center", gap: 1,
                        justifyContent: "space-between",
                      }}>
                        <Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
                          <Icon icon="mdi:invoice-check-outline" width={15} style={{ opacity: 0.6 }} />
                          <Typography variant="subtitle2">Progreso de Facturación</Typography>
                        </Box>
                        <Chip
                          size="small"
                          label={itemsFacturados.completamente_facturada ? "Completamente facturada" : `${itemsFacturados.facturas.length} factura(s)`}
                          color={itemsFacturados.completamente_facturada ? "success" : "warning"}
                          variant="outlined"
                          sx={{ height: 18, fontSize: "0.68rem" }}
                        />
                      </Box>
                      <TableContainer>
                        <Table size="small">
                          <TableHead>
                            <TableRow sx={{ "& th": { fontWeight: 600, fontSize: "0.72rem", color: "text.secondary" } }}>
                              <TableCell>Producto</TableCell>
                              <TableCell align="right">Ordenado</TableCell>
                              <TableCell align="right">Facturado</TableCell>
                              <TableCell align="right">Pendiente</TableCell>
                            </TableRow>
                          </TableHead>
                          <TableBody>
                            {(itemsFacturados.items ?? []).map((it) => (
                              <TableRow key={it.pedido_detalle_id} sx={{ "&:last-child td": { border: 0 } }}>
                                <TableCell>
                                  <Typography variant="body2" sx={{ fontSize: "0.8rem" }}>{it.descripcion}</Typography>
                                  {it.cod_producto && <Typography variant="caption" color="text.disabled">{it.cod_producto}</Typography>}
                                </TableCell>
                                <TableCell align="right">
                                  <Typography variant="body2">{it.cantidad_ordenada.toLocaleString("es-PY")}</Typography>
                                </TableCell>
                                <TableCell align="right">
                                  <Typography variant="body2" color={it.cantidad_facturada > 0 ? "success.main" : "text.disabled"}>
                                    {it.cantidad_facturada.toLocaleString("es-PY")}
                                  </Typography>
                                </TableCell>
                                <TableCell align="right">
                                  <Typography variant="body2" fontWeight={600}
                                    color={it.cantidad_pendiente === 0 ? "text.disabled" : it.cantidad_pendiente < it.cantidad_ordenada ? "warning.main" : "text.primary"}>
                                    {it.cantidad_pendiente.toLocaleString("es-PY")}
                                  </Typography>
                                </TableCell>
                              </TableRow>
                            ))}
                          </TableBody>
                        </Table>
                      </TableContainer>
                    </Paper>
                  )}

                  {/* Historial */}
                  {historial.length > 0 && (
                    <Paper variant="outlined" sx={{ overflow: "hidden" }}>
                      <Box sx={{
                        px: 2, py: 1.25,
                        bgcolor: (t) => alpha(t.palette.action.hover, 0.04),
                        borderBottom: 1, borderColor: "divider",
                        display: "flex", alignItems: "center", gap: 1,
                      }}>
                        <Icon icon="mdi:timeline-clock-outline" width={15} style={{ opacity: 0.6 }} />
                        <Typography variant="subtitle2">Historial de cambios</Typography>
                      </Box>
                      <Box sx={{ px: 2, py: 1.5 }}>
                        {historial.map((h, i) => (
                          <TimelineItem key={i} entry={h} isLast={i === historial.length - 1} />
                        ))}
                      </Box>
                    </Paper>
                  )}
                </Grid>

                {/* ─── Columna derecha: info + totales ──────────── */}
                <Grid item xs={12} md={5}>
                  <Stack spacing={2}>

                    {/* Info del cliente */}
                    <Paper variant="outlined" sx={{ p: 2 }}>
                      <SectionHeader icon="mdi:account-outline" title="Cliente" />
                      <LabelValue label="Nombre" value={getNombreCliente(orden)} />
                      {orden.cliente?.personas?.ruc && (
                        <LabelValue label="RUC" value={orden.cliente.personas.ruc} mono />
                      )}
                      <LabelValue label="Vendedor" value={orden.vendedor ? `${orden.vendedor.nombre} ${orden.vendedor.apellido}` : null} />
                    </Paper>

                    {/* Logística */}
                    <Paper variant="outlined" sx={{ p: 2 }}>
                      <SectionHeader icon="mdi:warehouse" title="Logística" />
                      <LabelValue label="Origen" value={getOrigenOrdenLabel(orden)} />
                      <LabelValue label="Sucursal" value={orden.sucursal?.descripcion} />
                      <LabelValue label="Depósito" value={orden.deposito?.descripcion} />
                      <LabelValue label="Moneda" value={orden.moneda ? `${orden.moneda.descripcion} (${orden.moneda.codigo})` : null} />
                      <LabelValue label="Lista de precios" value={orden.lista_precios?.nombre} />
                    </Paper>

                    {/* Fechas */}
                    <Paper variant="outlined" sx={{ p: 2 }}>
                      <SectionHeader icon="mdi:calendar-outline" title="Fechas" />
                      <LabelValue label="Creación" value={fmt(orden.fecha_pedido, true)} />
                      <LabelValue label="Confirmación" value={fmt(orden.fecha_confirmacion)} />
                      <Box sx={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", gap: 1, py: 0.35 }}>
                        <Typography variant="caption" color="text.secondary">Vencimiento</Typography>
                        {orden.fecha_venc_orden ? (
                          <Typography
                            variant="body2" fontWeight={500}
                            color={new Date(orden.fecha_venc_orden) < new Date() && !["facturada","cancelada","vencida"].includes(estado) ? "error.main" : undefined}
                          >
                            {fmt(orden.fecha_venc_orden)}
                          </Typography>
                        ) : (
                          <Typography variant="body2" color="text.disabled" fontStyle="italic">Sin fecha</Typography>
                        )}
                      </Box>
                      <LabelValue label="Creado por" value={orden.creador?.username} />
                    </Paper>

                    {/* Totales */}
                    <Paper
                      variant="outlined"
                      sx={{ p: 2, borderColor: (t) => alpha(t.palette.success.main, 0.3) }}
                    >
                      <SectionHeader icon="mdi:cash-multiple" title="Totales" />
                      {subtotal > 0 && subtotal !== total && (
                        <LabelValue label="Subtotal" value={`${moneda} ${subtotal.toLocaleString("es-PY")}`} />
                      )}
                      {totalDesc > 0 && (
                        <LabelValue label="Descuento" value={`− ${moneda} ${totalDesc.toLocaleString("es-PY")}`} />
                      )}
                      {totalIva > 0 && (
                        <LabelValue label="IVA" value={`${moneda} ${totalIva.toLocaleString("es-PY")}`} />
                      )}
                      <Divider sx={{ my: 1 }} />
                      <Box sx={{ display: "flex", justifyContent: "space-between", alignItems: "center", mt: 0.5 }}>
                        <Typography variant="body1" fontWeight={700}>Total</Typography>
                        <Typography variant="h5" fontWeight={800} color="success.main" lineHeight={1}>
                          {formatMoney(total)}
                        </Typography>
                      </Box>
                      {montoFact > 0 && (
                        <>
                          <Divider sx={{ my: 1 }} />
                          <LabelValue label="Facturado" value={`${moneda} ${montoFact.toLocaleString("es-PY")}`} />
                          <Box sx={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", gap: 1, py: 0.35 }}>
                            <Typography variant="caption" color="warning.main" fontWeight={600}>Pendiente</Typography>
                            <Typography variant="body2" fontWeight={700} color="warning.main">
                              {formatMoney(total - montoFact)}
                            </Typography>
                          </Box>
                        </>
                      )}
                    </Paper>

                  </Stack>
                </Grid>
              </Grid>
            )}
          </Box>
        </DialogContent>
      </Dialog>

      <CancelarDialog
        open={cancelarOpen}
        onClose={() => setCancelarOpen(false)}
        onConfirm={(motivo) => cancelarMut.mutate(motivo)}
        loading={cancelarMut.isPending}
      />
      {dialogs}
    </>
  );
}

export default OrdenVentaDetalleDialog;
