import {
  Block,
  CheckCircle,
  CreditCard,
  ExpandLess,
  ExpandMore,
  Inventory,
  Link,
  LinkOff,
  Payments,
  Schedule,
  Search,
} from "@mui/icons-material";
import {
  Alert,
  Box,
  Button,
  Chip,
  CircularProgress,
  Collapse,
  Dialog,
  DialogActions,
  DialogContent,
  DialogContentText,
  DialogTitle,
  Divider,
  InputAdornment,
  List,
  ListItem,
  ListItemButton,
  ListItemText,
  Paper,
  Skeleton,
  Stack,
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableRow,
  TextField,
  Tooltip,
  Typography,
} from "@mui/material";
import { useCallback, useRef, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { buscarProductos } from "../../api/productos.service";
import { getCondicionesPago } from "../../api/pagos.service";
import {
  useCambiarCondicionCompraMutation,
  useConfirmarCompraMutation,
  usePendientesQuery,
  useRechazarCompraMutation,
  useVincularProductoMutation,
} from "../../tanstack/MarangatuStack";

const fmtGs = (n) => Number(n ?? 0).toLocaleString("es-PY");

const CondicionChip = ({ pago_info, plazo_credito }) => {
  const condicion = pago_info?.condicion ?? (plazo_credito > 0 ? "credito" : "contado");
  if (condicion === "credito") {
    const cuotas = pago_info?.cuotas;
    const plazo = pago_info?.plazo ?? plazo_credito;
    const label = cuotas > 0
      ? `Crédito · ${cuotas} cuota${cuotas !== 1 ? "s" : ""}`
      : plazo > 0
        ? `Crédito · ${plazo}d`
        : "Crédito";
    return <Chip size="small" label={label} color="warning" variant="outlined" icon={<CreditCard sx={{ fontSize: "13px !important" }} />} sx={{ fontSize: "0.7rem" }} />;
  }
  const medios = pago_info?.medios ?? [];
  const label = medios.length === 1
    ? medios[0].desc
    : medios.length > 1
      ? `Contado · ${medios.length} medios`
      : "Contado";
  return <Chip size="small" label={label} color="success" variant="outlined" icon={<Payments sx={{ fontSize: "13px !important" }} />} sx={{ fontSize: "0.7rem" }} />;
};

const PagoInfoSection = ({ pago_info, total }) => {
  if (!pago_info) return null;
  const { condicion, plazo, cuotas, iCondCred, cuotasDetalle = [], medios = [] } = pago_info;

  return (
    <Box sx={{ px: 2, py: 1.5, bgcolor: "background.paper", borderTop: "1px solid", borderColor: "divider" }}>
      <Typography variant="caption" fontWeight={600} color="text.secondary" sx={{ textTransform: "uppercase", letterSpacing: 0.5, display: "block", mb: 1 }}>
        Condición de pago
      </Typography>

      {condicion === "contado" && (
        <Stack direction="row" spacing={1} flexWrap="wrap">
          {medios.length > 0 ? medios.map((m, i) => (
            <Box key={i} sx={{ display: "flex", alignItems: "center", gap: 0.5, bgcolor: "action.hover", px: 1.5, py: 0.5, borderRadius: 1 }}>
              <Typography variant="caption" fontWeight={600}>{m.desc}</Typography>
              {m.monto > 0 && (
                <Typography variant="caption" color="text.secondary">· {fmtGs(m.monto)} Gs.</Typography>
              )}
            </Box>
          )) : (
            <Typography variant="caption" color="text.secondary">Contado</Typography>
          )}
        </Stack>
      )}

      {condicion === "credito" && (
        <Box>
          <Stack direction="row" spacing={2} sx={{ mb: cuotasDetalle.length > 0 ? 1.5 : 0 }}>
            {plazo > 0 && (
              <Box sx={{ display: "flex", alignItems: "center", gap: 0.5 }}>
                <Schedule sx={{ fontSize: 14, color: "warning.main" }} />
                <Typography variant="caption">Plazo: <strong>{plazo} días</strong></Typography>
              </Box>
            )}
            {cuotas > 0 && (
              <Typography variant="caption">Cuotas: <strong>{cuotas}</strong></Typography>
            )}
            {iCondCred === 2 && cuotas > 0 && Number(total) > 0 && (
              <Typography variant="caption">
                Cuota aprox.: <strong>{fmtGs(Number(total) / cuotas)} Gs.</strong>
              </Typography>
            )}
          </Stack>

          {cuotasDetalle.length > 0 && (
            <Table size="small" sx={{ maxWidth: 500 }}>
              <TableHead>
                <TableRow sx={{ bgcolor: "action.hover" }}>
                  <TableCell sx={{ py: 0.4, fontSize: "0.7rem", fontWeight: 600 }}>Cuota</TableCell>
                  <TableCell sx={{ py: 0.4, fontSize: "0.7rem", fontWeight: 600 }} align="right">Monto</TableCell>
                  <TableCell sx={{ py: 0.4, fontSize: "0.7rem", fontWeight: 600 }}>Vencimiento</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {cuotasDetalle.map((q, i) => (
                  <TableRow key={i}>
                    <TableCell sx={{ py: 0.4, fontSize: "0.75rem" }}>{q.nro || i + 1}</TableCell>
                    <TableCell sx={{ py: 0.4, fontSize: "0.75rem" }} align="right">{fmtGs(q.monto)} Gs.</TableCell>
                    <TableCell sx={{ py: 0.4, fontSize: "0.75rem" }}>
                      {q.vencimiento ? new Date(q.vencimiento).toLocaleDateString() : "—"}
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          )}
        </Box>
      )}
    </Box>
  );
};

const VincularDialog = ({ det, onClose }) => {
  const yaVinculado = !!det.producto_id;
  const [query, setQuery] = useState("");
  const [results, setResults] = useState([]);
  const [searching, setSearching] = useState(false);
  const [selected, setSelected] = useState(null);
  const vincular = useVincularProductoMutation();
  const timerRef = useRef(null);

  const handleDesvincular = () => {
    vincular.mutate(
      { detId: det.id, productoId: null },
      { onSuccess: () => onClose() },
    );
  };

  const handleSearch = useCallback((q) => {
    setQuery(q);
    setSelected(null);
    clearTimeout(timerRef.current);
    if (q.length < 2) { setResults([]); return; }
    timerRef.current = setTimeout(async () => {
      setSearching(true);
      try {
        const data = await buscarProductos(q, 15, null, null, true);
        setResults(data);
      } catch { setResults([]); }
      finally { setSearching(false); }
    }, 300);
  }, []);

  const handleConfirm = () => {
    if (!selected) return;
    vincular.mutate(
      { detId: det.id, productoId: selected.id },
      { onSuccess: () => onClose() },
    );
  };

  return (
    <Dialog open onClose={onClose} maxWidth="sm" fullWidth>
      <DialogTitle>
        {yaVinculado ? "Cambiar vinculación de producto" : "Vincular producto ERP"}
        <Typography variant="body2" color="text.secondary" sx={{ mt: 0.5 }}>
          Ítem del XML: <strong>{det.descripcion}</strong>{det.codigo_producto ? ` · Cód. ${det.codigo_producto}` : ""}
        </Typography>
      </DialogTitle>
      <DialogContent sx={{ pb: 1 }}>
        {yaVinculado && (
          <Alert severity="success" sx={{ mb: 2 }} icon={<Inventory />}>
            <Typography variant="body2" fontWeight={600} sx={{ mb: 0.5 }}>
              Vinculado actualmente a:
            </Typography>
            <Typography variant="body2">
              {det.producto_nombre}{det.producto_cod ? ` · Cód. ${det.producto_cod}` : ""}
            </Typography>
            <Typography variant="caption" color="text.secondary" sx={{ display: "block", mt: 0.5 }}>
              Buscá abajo si querés cambiarlo por otro producto, o presioná
              <strong> Desvincular</strong> para dejarlo como ítem sin producto.
            </Typography>
          </Alert>
        )}
        <TextField
          autoFocus
          fullWidth
          size="small"
          placeholder={yaVinculado ? "Buscar otro producto..." : "Buscar por nombre o código..."}
          value={query}
          onChange={(e) => handleSearch(e.target.value)}
          sx={{ mb: 1.5 }}
          InputProps={{
            startAdornment: (
              <InputAdornment position="start">
                {searching ? <CircularProgress size={16} /> : <Search fontSize="small" />}
              </InputAdornment>
            ),
          }}
        />
        {results.length > 0 && (
          <Paper variant="outlined" sx={{ maxHeight: 260, overflow: "auto" }}>
            <List dense disablePadding>
              {results.map((p) => (
                <ListItem key={p.id} disablePadding>
                  <ListItemButton
                    selected={selected?.id === p.id}
                    onClick={() => setSelected(p)}
                  >
                    <ListItemText
                      primary={
                        <Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
                          <Typography variant="body2">{p.descripcion}</Typography>
                          {p.maneja_inventario && (
                            <Chip size="small" label="Stock" color="info" variant="outlined" sx={{ fontSize: "0.65rem", height: 18 }} />
                          )}
                        </Box>
                      }
                      secondary={
                        <Typography variant="caption" color="text.secondary">
                          {p.cod_producto && `Cód: ${p.cod_producto} · `}
                          {p.precio != null ? `Precio: ${fmtGs(p.precio)} Gs.` : ""}
                        </Typography>
                      }
                    />
                  </ListItemButton>
                </ListItem>
              ))}
            </List>
          </Paper>
        )}
        {query.length >= 2 && !searching && results.length === 0 && (
          <Typography variant="caption" color="text.secondary">Sin resultados para "{query}"</Typography>
        )}
        {selected && (
          <Alert severity="info" sx={{ mt: 1.5, py: 0.5 }}>
            Se vinculará: <strong>{selected.descripcion}</strong>
            {selected.maneja_inventario
              ? " · Al confirmar la compra, se actualizará el stock en el depósito principal."
              : " · Este producto no maneja inventario, no afectará stock."}
          </Alert>
        )}
      </DialogContent>
      <DialogActions>
        <Button onClick={onClose}>Cancelar</Button>
        {yaVinculado && (
          <Button
            color="warning"
            onClick={handleDesvincular}
            disabled={vincular.isPending}
            startIcon={<LinkOff />}
          >
            Desvincular
          </Button>
        )}
        <Button
          variant="contained"
          disabled={!selected || vincular.isPending}
          onClick={handleConfirm}
          startIcon={vincular.isPending ? <CircularProgress size={14} /> : <Link />}
        >
          {yaVinculado ? "Cambiar vinculación" : "Vincular"}
        </Button>
      </DialogActions>
    </Dialog>
  );
};

const ItemsDetalle = ({ detalle, pago_info, total, onVincular }) => (
  <Box sx={{ bgcolor: "action.hover" }}>
    <PagoInfoSection pago_info={pago_info} total={total} />
    <Box sx={{ px: 2, py: 1 }}>
      <Typography variant="caption" fontWeight={600} color="text.secondary" sx={{ textTransform: "uppercase", letterSpacing: 0.5, display: "block", mb: 1 }}>
        Ítems de la factura
      </Typography>
      <Table size="small">
        <TableHead>
          <TableRow>
            <TableCell sx={{ py: 0.5, fontWeight: 600, fontSize: "0.72rem" }}>Descripción</TableCell>
            <TableCell sx={{ py: 0.5, fontWeight: 600, fontSize: "0.72rem" }}>Código</TableCell>
            <TableCell sx={{ py: 0.5, fontWeight: 600, fontSize: "0.72rem" }} align="right">Cant.</TableCell>
            <TableCell sx={{ py: 0.5, fontWeight: 600, fontSize: "0.72rem" }} align="right">P. Unit.</TableCell>
            <TableCell sx={{ py: 0.5, fontWeight: 600, fontSize: "0.72rem" }} align="right">IVA %</TableCell>
            <TableCell sx={{ py: 0.5, fontWeight: 600, fontSize: "0.72rem" }} align="right">Subtotal</TableCell>
            <TableCell sx={{ py: 0.5, fontWeight: 600, fontSize: "0.72rem" }} align="center">Producto ERP</TableCell>
            <TableCell sx={{ py: 0.5, fontWeight: 600, fontSize: "0.72rem" }} align="center">Stock</TableCell>
          </TableRow>
        </TableHead>
        <TableBody>
          {detalle.map((d) => (
            <TableRow key={d.id}>
              <TableCell sx={{ py: 0.5, fontSize: "0.78rem" }}>
                <Typography variant="caption">{d.descripcion ?? "—"}</Typography>
              </TableCell>
              <TableCell sx={{ py: 0.5 }}>
                <Typography variant="caption" fontFamily="monospace" color="text.disabled">
                  {d.codigo_producto ?? "—"}
                </Typography>
              </TableCell>
              <TableCell sx={{ py: 0.5 }} align="right">
                <Typography variant="caption">{d.cantidad}</Typography>
              </TableCell>
              <TableCell sx={{ py: 0.5 }} align="right">
                <Typography variant="caption">{fmtGs(d.precio_unitario)}</Typography>
              </TableCell>
              <TableCell sx={{ py: 0.5 }} align="right">
                <Typography variant="caption">{d.porcentaje_iva}%</Typography>
              </TableCell>
              <TableCell sx={{ py: 0.5 }} align="right">
                <Typography variant="caption" fontWeight={600}>{fmtGs(d.subtotal)}</Typography>
              </TableCell>
              <TableCell sx={{ py: 0.5 }} align="center">
                {d.producto_id ? (
                  <Tooltip title={
                    <Box>
                      <div>{d.producto_nombre}{d.producto_cod ? ` · ${d.producto_cod}` : ""}</div>
                      <div style={{ marginTop: 4, opacity: 0.85 }}>
                        Vinculación sugerida por el sistema · Click para cambiar
                      </div>
                    </Box>
                  }>
                    <Chip
                      size="small"
                      color="success"
                      icon={<Inventory sx={{ fontSize: "12px !important" }} />}
                      label={d.producto_nombre?.slice(0, 20) ?? "Vinculado"}
                      variant="outlined"
                      onClick={() => onVincular(d)}
                      sx={{ fontSize: "0.68rem", maxWidth: 160, cursor: "pointer" }}
                    />
                  </Tooltip>
                ) : (
                  <Tooltip title="Sin producto vinculado — hacer clic para vincular">
                    <Chip
                      size="small"
                      icon={<LinkOff sx={{ fontSize: "12px !important" }} />}
                      label="Vincular"
                      variant="outlined"
                      color="warning"
                      onClick={() => onVincular(d)}
                      sx={{ fontSize: "0.68rem", cursor: "pointer" }}
                    />
                  </Tooltip>
                )}
              </TableCell>
              <TableCell sx={{ py: 0.5 }} align="center">
                {d.producto_id && (
                  <Chip
                    size="small"
                    label={d.afecta_stock ? "Actualiza stock" : "Sin stock"}
                    color={d.afecta_stock ? "info" : "default"}
                    variant="outlined"
                    sx={{ fontSize: "0.65rem" }}
                  />
                )}
              </TableCell>
            </TableRow>
          ))}
        </TableBody>
      </Table>
    </Box>
  </Box>
);

const CambiarCondicionDialog = ({ compra, onClose }) => {
  const { data: condiciones = [] } = useQuery({
    queryKey: ["condiciones-pago"],
    queryFn: getCondicionesPago,
    staleTime: 5 * 60 * 1000,
  });
  const mut = useCambiarCondicionCompraMutation();
  const [condicionId, setCondicionId] = useState("");

  // Estado detectado del XML (para mostrarlo como comparación)
  const xmlPago = compra?.pago_info;
  const xmlEsCredito = xmlPago?.condicion === "credito";
  const xmlPlazo = xmlPago?.plazo ?? compra?.plazo_credito ?? 0;
  const xmlCuotas = xmlPago?.cuotas ?? 0;

  const selected = condiciones.find((c) => c.id === condicionId);
  const selectedEsCredito = selected ? Number(selected.cod_condicion_venta ?? 1) === 2 : false;

  const handleAplicar = () => {
    if (!selected) return;
    mut.mutate(
      { id: compra.id, condicion_pago_id: selected.id },
      { onSuccess: () => onClose() },
    );
  };

  return (
    <Dialog open onClose={onClose} maxWidth="sm" fullWidth>
      <DialogTitle>
        Cambiar condición de pago
        <Typography variant="body2" color="text.secondary" sx={{ mt: 0.5 }}>
          {compra?.proveedor} · {compra?.numero}
        </Typography>
      </DialogTitle>
      <DialogContent>
        <Alert severity="info" sx={{ mb: 2 }}>
          <Typography variant="body2" fontWeight={600} sx={{ mb: 0.5 }}>
            Condición leída del XML:
          </Typography>
          <Typography variant="caption">
            {xmlEsCredito
              ? `Crédito · ${xmlCuotas > 1 ? `${xmlCuotas} cuotas` : `${xmlPlazo}d`}`
              : "Contado"}
          </Typography>
        </Alert>
        <Typography variant="caption" color="text.secondary" sx={{ display: "block", mb: 1 }}>
          Elegí la condición del catálogo del ERP para reemplazar la del XML. Se
          usará para generar las cuotas al confirmar la compra.
        </Typography>
        <TextField
          select
          fullWidth
          size="small"
          label="Condición de pago (catálogo ERP) *"
          value={condicionId}
          onChange={(e) => setCondicionId(e.target.value)}
          SelectProps={{ native: true }}
          InputLabelProps={{ shrink: true }}
        >
          <option value="">— Elegir —</option>
          {condiciones
            .filter((c) => c.activo !== false)
            .map((c) => {
              const esCredito = Number(c.cod_condicion_venta ?? 1) === 2;
              const detalle = esCredito
                ? `${c.cuotas || 1} cuota(s) · ${c.dias_plazo || 0}d`
                : "Contado";
              return (
                <option key={c.id} value={c.id}>
                  {c.descripcion} — {detalle}
                </option>
              );
            })}
        </TextField>
        {selected && (
          <Alert
            severity={selectedEsCredito ? "warning" : "success"}
            sx={{ mt: 2 }}
            icon={selectedEsCredito ? <CreditCard /> : <Payments />}
          >
            Se aplicará:{" "}
            <strong>
              {selectedEsCredito
                ? `Crédito · ${selected.cuotas || 1} cuota(s) · ${selected.dias_plazo || 0}d`
                : "Contado"}
            </strong>
          </Alert>
        )}
      </DialogContent>
      <DialogActions>
        <Button onClick={onClose}>Cancelar</Button>
        <Button
          variant="contained"
          onClick={handleAplicar}
          disabled={!selected || mut.isPending}
          startIcon={mut.isPending ? <CircularProgress size={14} /> : null}
        >
          Aplicar
        </Button>
      </DialogActions>
    </Dialog>
  );
};

const PendienteRow = ({ c }) => {
  const [open, setOpen] = useState(false);
  const [dialogOpen, setDialogOpen] = useState(false);
  const [confirmarOpen, setConfirmarOpen] = useState(false);
  const [vincularDet, setVincularDet] = useState(null);
  const [cambiarCondicion, setCambiarCondicion] = useState(false);
  const confirmar = useConfirmarCompraMutation();
  const rechazar = useRechazarCompraMutation();

  return (
    <>
      <TableRow hover sx={{ cursor: "pointer" }} onClick={() => setOpen((v) => !v)}>
        <TableCell sx={{ width: 32, pr: 0 }}>
          {open ? <ExpandLess fontSize="small" /> : <ExpandMore fontSize="small" />}
        </TableCell>
        <TableCell>
          <Typography variant="body2" fontWeight={500}>{c.proveedor}</Typography>
          {c.proveedor_ruc && (
            <Typography variant="caption" color="text.disabled">RUC {c.proveedor_ruc}</Typography>
          )}
        </TableCell>
        <TableCell>
          <Typography variant="body2" fontFamily="monospace">{c.numero || "—"}</Typography>
          {c.timbrado && (
            <Typography variant="caption" color="text.disabled">Timb. {c.timbrado}</Typography>
          )}
        </TableCell>
        <TableCell>
          <Typography variant="body2">
            {c.fecha_emision ? new Date(c.fecha_emision).toLocaleDateString() : "—"}
          </Typography>
        </TableCell>
        <TableCell align="center" onClick={(e) => e.stopPropagation()}>
          <Tooltip title="Click para cambiar la condición de pago">
            <Box
              component="span"
              sx={{ cursor: "pointer", display: "inline-block" }}
              onClick={() => setCambiarCondicion(true)}
            >
              <CondicionChip pago_info={c.pago_info} plazo_credito={c.plazo_credito} />
            </Box>
          </Tooltip>
        </TableCell>
        <TableCell align="right">
          <Typography variant="body2" fontWeight={600}>{fmtGs(c.total)}</Typography>
          {Number(c.total_iva ?? 0) > 0 && (
            <Typography variant="caption" color="text.disabled">IVA {fmtGs(c.total_iva)}</Typography>
          )}
        </TableCell>
        <TableCell align="center">
          <Typography variant="body2">{c.items}</Typography>
        </TableCell>
        <TableCell align="center" onClick={(e) => e.stopPropagation()}>
          <Tooltip title={c.items_con_producto === c.items ? "Todos los ítems mapeados" : "Algunos ítems sin producto — expandí para vincular"}>
            <Chip
              size="small"
              icon={<Inventory sx={{ fontSize: "14px !important" }} />}
              label={`${c.items_con_producto}/${c.items}`}
              color={c.items_con_producto === c.items ? "success" : c.items_con_producto > 0 ? "warning" : "default"}
              variant="outlined"
            />
          </Tooltip>
        </TableCell>
        <TableCell align="right" sx={{ pr: 2 }} onClick={(e) => e.stopPropagation()}>
          <Stack direction="row" spacing={0.5} justifyContent="flex-end">
            <Tooltip title="Rechazar — no afectará stock ni costos, queda en historial">
              <Button
                size="small"
                variant="outlined"
                color="error"
                startIcon={<Block />}
                onClick={() => setDialogOpen(true)}
                disabled={rechazar.isPending || confirmar.isPending}
                sx={{ whiteSpace: "nowrap" }}
              >
                Rechazar
              </Button>
            </Tooltip>
            <Tooltip title="Confirmar — aplicará stock, costos y generará las cuotas">
              <Button
                size="small"
                variant="contained"
                color="success"
                startIcon={<CheckCircle />}
                onClick={() => setConfirmarOpen(true)}
                disabled={confirmar.isPending || rechazar.isPending}
                sx={{ whiteSpace: "nowrap" }}
              >
                Confirmar
              </Button>
            </Tooltip>
          </Stack>
        </TableCell>
      </TableRow>

      <TableRow>
        <TableCell colSpan={9} sx={{ p: 0, border: 0 }}>
          <Collapse in={open} timeout="auto" unmountOnExit>
            <ItemsDetalle
              detalle={c.detalle ?? []}
              pago_info={c.pago_info}
              total={c.total}
              onVincular={(det) => setVincularDet(det)}
            />
          </Collapse>
        </TableCell>
      </TableRow>

      <Dialog open={dialogOpen} onClose={() => setDialogOpen(false)} maxWidth="xs" fullWidth>
        <DialogTitle>¿Rechazar esta compra?</DialogTitle>
        <DialogContent>
          <DialogContentText>
            <strong>{c.proveedor}</strong> · {c.numero}<br />
            La compra quedará en estado <em>rechazado</em> y no afectará stock ni costos. Se mantendrá en el historial para auditoría.
          </DialogContentText>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setDialogOpen(false)}>Cancelar</Button>
          <Button
            color="error"
            variant="contained"
            onClick={() => { rechazar.mutate({ id: c.id }); setDialogOpen(false); }}
            disabled={rechazar.isPending}
          >
            Sí, rechazar
          </Button>
        </DialogActions>
      </Dialog>

      {/* Confirmación de "Confirmar" */}
      <Dialog open={confirmarOpen} onClose={() => setConfirmarOpen(false)} maxWidth="xs" fullWidth>
        <DialogTitle>¿Confirmar esta compra?</DialogTitle>
        <DialogContent>
          <DialogContentText component="div">
            <Box sx={{ mb: 1.5 }}>
              <Typography variant="body2" fontWeight={600}>
                {c.proveedor}
              </Typography>
              <Typography variant="caption" color="text.secondary">
                {c.numero} · Fecha {c.fecha_emision ? new Date(c.fecha_emision).toLocaleDateString() : "—"}
              </Typography>
            </Box>
            <Box sx={{ p: 1.5, bgcolor: "action.hover", borderRadius: 1, mb: 1.5 }}>
              <Typography variant="caption" fontWeight={600} sx={{ display: "block", mb: 0.5 }}>
                Al confirmar:
              </Typography>
              <Typography variant="caption" component="ul" sx={{ pl: 2, m: 0 }}>
                <li>Se registrará como <strong>factura de compra</strong> por <strong>{fmtGs(c.total)} Gs.</strong></li>
                <li>Se aplicará <strong>{c.pago_info?.condicion === "credito" ? "Crédito" : "Contado"}</strong> con {c.items_con_producto}/{c.items} ítem(s) vinculado(s).</li>
                <li>Los ítems con producto ERP que <strong>manejan inventario</strong> actualizarán stock del depósito principal.</li>
                <li>Se generarán {c.pago_info?.condicion === "credito" ? "las cuotas" : "el asiento contable"} correspondientes.</li>
              </Typography>
            </Box>
            <Typography variant="caption" color="warning.main">
              Esta acción no se puede deshacer desde este panel. Para revertir habrá que anular la factura desde el módulo Compras.
            </Typography>
          </DialogContentText>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setConfirmarOpen(false)}>Cancelar</Button>
          <Button
            color="success"
            variant="contained"
            onClick={() => {
              confirmar.mutate({ id: c.id });
              setConfirmarOpen(false);
            }}
            disabled={confirmar.isPending}
            startIcon={<CheckCircle />}
          >
            Sí, confirmar
          </Button>
        </DialogActions>
      </Dialog>

      {vincularDet && (
        <VincularDialog det={vincularDet} onClose={() => setVincularDet(null)} />
      )}

      {cambiarCondicion && (
        <CambiarCondicionDialog compra={c} onClose={() => setCambiarCondicion(false)} />
      )}
    </>
  );
};

export const MarangatuPendientesPanel = () => {
  const { data: pendientes = [], isLoading, error } = usePendientesQuery();

  if (isLoading) return (
    <Paper variant="outlined" sx={{ p: 2 }}>
      {[...Array(3)].map((_, i) => <Skeleton key={i} height={48} sx={{ mb: 0.5 }} />)}
    </Paper>
  );

  if (error) return (
    <Alert severity="error">Error cargando compras pendientes</Alert>
  );

  if (pendientes.length === 0) return (
    <Paper variant="outlined" sx={{ p: 3, textAlign: "center" }}>
      <CheckCircle color="success" sx={{ fontSize: 40, mb: 1 }} />
      <Typography variant="body2" color="text.secondary">
        No hay compras importadas pendientes de confirmación
      </Typography>
    </Paper>
  );

  return (
    <Paper variant="outlined" sx={{ overflow: "hidden" }}>
      <Box sx={{ px: 2.5, py: 1.5, display: "flex", alignItems: "center", gap: 1.5, bgcolor: "background.default" }}>
        <Typography variant="subtitle2" fontWeight={600}>
          Pendientes de confirmación
        </Typography>
        <Chip size="small" color="warning" label={pendientes.length} sx={{ fontWeight: 700, minWidth: 28 }} />
        <Typography variant="caption" color="text.secondary" sx={{ ml: "auto" }}>
          Expandí una fila para vincular productos · Confirmá para aplicar stock y costos
        </Typography>
      </Box>

      <Divider />

      <Box sx={{ overflow: "auto" }}>
        <Table size="small">
          <TableHead>
            <TableRow sx={{ bgcolor: "action.hover" }}>
              <TableCell sx={{ width: 32 }} />
              <TableCell sx={{ fontWeight: 600 }}>Proveedor</TableCell>
              <TableCell sx={{ fontWeight: 600 }}>Comprobante</TableCell>
              <TableCell sx={{ fontWeight: 600 }}>Fecha</TableCell>
              <TableCell sx={{ fontWeight: 600 }} align="center">Condición</TableCell>
              <TableCell sx={{ fontWeight: 600 }} align="right">Total</TableCell>
              <TableCell sx={{ fontWeight: 600 }} align="center">Ítems</TableCell>
              <TableCell sx={{ fontWeight: 600 }} align="center">Con producto</TableCell>
              <TableCell />
            </TableRow>
          </TableHead>
          <TableBody>
            {pendientes.map((c) => (
              <PendienteRow key={c.id} c={c} />
            ))}
          </TableBody>
        </Table>
      </Box>
    </Paper>
  );
};
