import { Icon } from "@iconify/react";
import { useCallback, useRef, useState } from "react";
import { toast } from "sonner";
import styled, { keyframes } from "styled-components";
import { searchClientes } from "../../api/clientes.service";
import {
  useAvanzarEstadoCAMutation,
  useCancelarCAMutation,
  useCompraAsistidaQuery,
  useComprasAsistidasQuery,
  useCreateCompraAsistidaMutation,
  useIniciarPagoCAMutation,
  useUpdateCompraAsistidaMutation,
} from "../../tanstack/CompraAsistidaStack.jsx";

// ─── Helpers ──────────────────────────────────────────────────────────────────
const fmtGs = (v) =>
  v != null
    ? `₲ ${Number(v).toLocaleString("es-PY", { maximumFractionDigits: 0 })}`
    : "—";

const fmtUsd = (v) =>
  v != null
    ? `$ ${Number(v).toLocaleString("es-PY", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`
    : "—";

const calcTotalGs = (pedido) => {
  const cotiz = Number(pedido?.cotizacion_usd_gs ?? 0);
  const prod = Number(pedido?.monto_producto_usd ?? 0);
  const serv = Number(pedido?.monto_servicio_gs ?? 0);
  const log = Number(pedido?.monto_logistica_gs ?? 0);
  const com = Number(pedido?.monto_comision_gs ?? 0);
  return prod * cotiz + serv + log + com;
};

const ESTADOS = [
  { value: "borrador",        label: "Borrador",        color: "#9e9e9e", icon: "mdi:pencil-outline" },
  { value: "cotizado",        label: "Cotizado",        color: "#2196f3", icon: "mdi:file-document-outline" },
  { value: "confirmado",      label: "Confirmado",      color: "#ff9800", icon: "mdi:check-circle-outline" },
  { value: "pago_recibido",   label: "Pago Recibido",   color: "#4caf50", icon: "mdi:cash-check" },
  { value: "en_compra_china", label: "En Compra China", color: "#9c27b0", icon: "mdi:store-outline" },
  { value: "en_transito",     label: "En Tránsito",     color: "#00bcd4", icon: "mdi:airplane" },
  { value: "en_aduana",       label: "En Aduana",       color: "#ff5722", icon: "mdi:office-building-outline" },
  { value: "entregado",       label: "Entregado",       color: "#8bc34a", icon: "mdi:package-variant-closed-check" },
  { value: "facturado",       label: "Facturado",       color: "#607d8b", icon: "mdi:receipt-text-outline" },
  { value: "cancelado",       label: "Cancelado",       color: "#f44336", icon: "mdi:close-circle-outline" },
];

const NEXT = {
  borrador:        ["cotizado", "cancelado"],
  cotizado:        ["confirmado", "cancelado"],
  confirmado:      ["pago_recibido", "cancelado"],
  pago_recibido:   ["en_compra_china", "cancelado"],
  en_compra_china: ["en_transito"],
  en_transito:     ["en_aduana"],
  en_aduana:       ["entregado"],
  entregado:       ["facturado"],
  facturado:       [],
  cancelado:       [],
};

const getEstado = (v) => ESTADOS.find((e) => e.value === v) ?? ESTADOS[0];

const clienteNombre = (c) =>
  c?.personas?.razon_social || c?.nombre_fantasia || "Sin nombre";

// ─── Animations ───────────────────────────────────────────────────────────────
const fadeIn = keyframes`from { opacity:0; transform:translateY(6px); } to { opacity:1; transform:none; }`;
const spin   = keyframes`to { transform: rotate(360deg); }`;

// ─── Layout ───────────────────────────────────────────────────────────────────
const Layout = styled.div`
  display: flex;
  height: calc(100vh - 160px);
  background: ${({ theme }) => theme.bg1};
  border-radius: 12px;
  overflow: hidden;
  border: 1px solid ${({ theme }) => theme.color2};
`;

// ─── Panel izquierdo ──────────────────────────────────────────────────────────
const LeftPanel = styled.div`
  width: 300px;
  min-width: 300px;
  border-right: 1px solid ${({ theme }) => theme.color2};
  background: ${({ theme }) => theme.bg2};
  display: flex;
  flex-direction: column;
  overflow: hidden;
`;

const LeftHeader = styled.div`
  padding: 12px;
  border-bottom: 1px solid ${({ theme }) => theme.color2};
  display: flex;
  flex-direction: column;
  gap: 8px;
`;

const SearchRow = styled.div`
  display: flex;
  gap: 6px;
`;

const SearchBox = styled.div`
  flex: 1;
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 6px 10px;
  border: 1px solid ${({ $focused, theme }) => $focused ? theme.primary : theme.color2};
  border-radius: 8px;
  background: ${({ theme }) => theme.bg3};
  box-shadow: ${({ $focused, theme }) => $focused ? `0 0 0 2px ${theme.primary}22` : "none"};
  transition: all 0.15s;
`;

const SearchInput = styled.input`
  flex: 1;
  border: none;
  background: transparent;
  color: ${({ theme }) => theme.color1};
  font-size: 13px;
  outline: none;
  &::placeholder { color: ${({ theme }) => theme.textSecondary}; }
`;

const FilterSelect = styled.select`
  padding: 6px 8px;
  border: 1px solid ${({ theme }) => theme.color2};
  border-radius: 8px;
  background: ${({ theme }) => theme.bg3};
  color: ${({ theme }) => theme.color1};
  font-size: 12px;
  outline: none;
`;

const NewBtn = styled.button`
  padding: 7px 12px;
  border-radius: 8px;
  border: none;
  background: ${({ theme }) => theme.primary};
  color: #fff;
  font-size: 13px;
  font-weight: 600;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 4px;
  white-space: nowrap;
  transition: opacity 0.15s;
  &:hover { opacity: 0.88; }
`;

const ListContainer = styled.div`
  flex: 1;
  overflow-y: auto;
`;

const ListEmpty = styled.div`
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 8px;
  height: 100%;
  color: ${({ theme }) => theme.textSecondary};
  font-size: 13px;
  opacity: 0.6;
`;

const ListItem = styled.div`
  padding: 10px 14px;
  border-bottom: 1px solid ${({ theme }) => theme.color2}28;
  cursor: pointer;
  border-left: 3px solid ${({ $selected, theme }) =>
    $selected ? theme.primary : "transparent"};
  background: ${({ $selected, theme }) =>
    $selected ? `${theme.primary}12` : "transparent"};
  transition: background 0.12s;
  animation: ${fadeIn} 0.2s ease;
  &:hover { background: ${({ theme }) => theme.bg3}; }
`;

const ListItemTop = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 6px;
  margin-bottom: 3px;
`;

const ListItemName = styled.div`
  font-size: 13px;
  font-weight: 600;
  color: ${({ theme }) => theme.color1};
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  flex: 1;
`;

const ListItemDesc = styled.div`
  font-size: 11px;
  color: ${({ theme }) => theme.textSecondary};
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
`;

const ListItemAmount = styled.div`
  font-size: 11px;
  color: ${({ theme }) => theme.textSecondary};
  margin-top: 1px;
`;

const Badge = styled.span`
  display: inline-flex;
  align-items: center;
  gap: 3px;
  padding: 2px 7px;
  border-radius: 10px;
  font-size: 10px;
  font-weight: 600;
  background: ${({ $color }) => $color}1a;
  color: ${({ $color }) => $color};
  border: 1px solid ${({ $color }) => $color}33;
  white-space: nowrap;
  flex-shrink: 0;
`;

// ─── Panel derecho ────────────────────────────────────────────────────────────
const RightPanel = styled.div`
  flex: 1;
  overflow-y: auto;
  padding: 24px;
  animation: ${fadeIn} 0.2s ease;
`;

const EmptyRight = styled.div`
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 12px;
  color: ${({ theme }) => theme.textSecondary};
  opacity: 0.5;
`;

// ─── Form styles ──────────────────────────────────────────────────────────────
const FormHeader = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
  flex-wrap: wrap;
  gap: 10px;
`;

const FormTitle = styled.h2`
  margin: 0;
  font-size: 18px;
  font-weight: 700;
  color: ${({ theme }) => theme.color1};
`;

const BtnGroup = styled.div`
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
`;

const Btn = styled.button`
  padding: 7px 14px;
  border-radius: 8px;
  border: 1px solid ${({ $variant, theme }) =>
    $variant === "primary" ? "transparent"
    : $variant === "danger" ? "#f4433644"
    : theme.color2};
  font-size: 13px;
  font-weight: 500;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 5px;
  background: ${({ $variant, theme }) =>
    $variant === "primary" ? theme.primary
    : $variant === "danger" ? "#f4433618"
    : theme.bg3};
  color: ${({ $variant }) =>
    $variant === "primary" ? "#fff"
    : $variant === "danger" ? "#f44336"
    : "inherit"};
  transition: opacity 0.15s;
  &:hover:not(:disabled) { opacity: 0.82; }
  &:disabled { opacity: 0.45; cursor: not-allowed; }
`;

const Section = styled.div`
  margin-bottom: 22px;
`;

const SectionLabel = styled.div`
  font-size: 11px;
  font-weight: 700;
  letter-spacing: 0.8px;
  text-transform: uppercase;
  color: ${({ theme }) => theme.textSecondary};
  margin-bottom: 12px;
  padding-bottom: 6px;
  border-bottom: 1px solid ${({ theme }) => theme.color2};
`;

const Grid = styled.div`
  display: grid;
  grid-template-columns: ${({ $cols }) => `repeat(${$cols ?? 2}, 1fr)`};
  gap: 14px;
  @media (max-width: 700px) { grid-template-columns: 1fr; }
`;

const Field = styled.div`
  display: flex;
  flex-direction: column;
  gap: 5px;
  ${({ $full }) => $full && "grid-column: 1 / -1;"}
`;

const FieldLabel = styled.label`
  font-size: 12px;
  font-weight: 500;
  color: ${({ theme }) => theme.textSecondary};
`;

const Input = styled.input`
  padding: 8px 11px;
  border: 1px solid ${({ theme }) => theme.color2};
  border-radius: 8px;
  background: ${({ theme }) => theme.bg3};
  color: ${({ theme }) => theme.color1};
  font-size: 13px;
  outline: none;
  transition: border-color 0.15s;
  &:focus { border-color: ${({ theme }) => theme.primary}; }
  &:read-only { opacity: 0.6; cursor: default; }
`;

const Textarea = styled.textarea`
  padding: 8px 11px;
  border: 1px solid ${({ theme }) => theme.color2};
  border-radius: 8px;
  background: ${({ theme }) => theme.bg3};
  color: ${({ theme }) => theme.color1};
  font-size: 13px;
  outline: none;
  resize: vertical;
  min-height: 72px;
  font-family: inherit;
  transition: border-color 0.15s;
  &:focus { border-color: ${({ theme }) => theme.primary}; }
`;

// ─── Cliente card ──────────────────────────────────────────────────────────────
const ClienteCard = styled.div`
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 14px;
  border: 1px solid ${({ theme }) => theme.primary}44;
  border-radius: 10px;
  background: ${({ theme }) => theme.primary}0a;
`;

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

const ClienteName = styled.div`
  font-size: 15px;
  font-weight: 700;
  color: ${({ theme }) => theme.color1};
`;

const ClienteMeta = styled.div`
  font-size: 12px;
  color: ${({ theme }) => theme.textSecondary};
  margin-top: 2px;
`;

// ─── Inline cliente search ─────────────────────────────────────────────────────
const DropdownList = styled.div`
  position: absolute;
  top: calc(100% + 4px);
  left: 0;
  right: 0;
  background: ${({ theme }) => theme.bg2};
  border: 1px solid ${({ theme }) => theme.color2};
  border-radius: 10px;
  box-shadow: 0 8px 24px rgba(0,0,0,0.2);
  z-index: 200;
  max-height: 240px;
  overflow-y: auto;
`;

const DropdownItem = styled.div`
  padding: 10px 14px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 10px;
  transition: background 0.1s;
  &:hover { background: ${({ theme }) => theme.bg3}; }
`;

const DropdownEmpty = styled.div`
  padding: 14px;
  text-align: center;
  font-size: 13px;
  color: ${({ theme }) => theme.textSecondary};
`;

function ClienteSearchInline({ value, onChange, onSelect }) {
  const [results, setResults] = useState([]);
  const [loading, setLoading] = useState(false);
  const [focused, setFocused] = useState(false);
  const debounceRef = useRef(null);

  const buscar = useCallback(async (term) => {
    if (!term || term.length < 2) { setResults([]); return; }
    setLoading(true);
    try {
      const data = await searchClientes(term, 10);
      setResults(data || []);
    } catch { setResults([]); }
    finally { setLoading(false); }
  }, []);

  const handleChange = (e) => {
    onChange(e.target.value);
    clearTimeout(debounceRef.current);
    debounceRef.current = setTimeout(() => buscar(e.target.value), 280);
  };

  const open = focused && value.length >= 2;

  return (
    <div style={{ position: "relative" }}>
      <SearchBox $focused={focused}>
        <Icon icon="mdi:account-search-outline" width={16} style={{ color: "inherit", flexShrink: 0 }} />
        <SearchInput
          value={value}
          onChange={handleChange}
          onFocus={() => setFocused(true)}
          onBlur={() => setTimeout(() => setFocused(false), 180)}
          placeholder="Buscar por nombre, RUC o documento…"
          autoComplete="off"
        />
        {loading && <Icon icon="mdi:loading" width={16} style={{ animation: `${spin.getName?.() ?? "spin"} 1s linear infinite`, flexShrink: 0 }} />}
      </SearchBox>

      {open && (
        <DropdownList>
          {results.length === 0 && !loading && (
            <DropdownEmpty>No se encontraron clientes</DropdownEmpty>
          )}
          {results.map((c) => (
            <DropdownItem
              key={c.id}
              onMouseDown={() => { onSelect(c); setResults([]); }}
            >
              <Icon icon="mdi:account-circle-outline" width={20} style={{ color: "#2196f3", flexShrink: 0 }} />
              <div>
                <div style={{ fontSize: 13, fontWeight: 600 }}>
                  {clienteNombre(c)}
                </div>
                {c.personas?.ruc && (
                  <div style={{ fontSize: 11, opacity: 0.6 }}>RUC: {c.personas.ruc}</div>
                )}
              </div>
            </DropdownItem>
          ))}
        </DropdownList>
      )}
    </div>
  );
}

// ─── Totales card ──────────────────────────────────────────────────────────────
const TotalCard = styled.div`
  background: ${({ theme }) => theme.primary}0d;
  border: 1px solid ${({ theme }) => theme.primary}33;
  border-radius: 10px;
  padding: 14px 18px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 16px;
  flex-wrap: wrap;
`;

const TotalLabel = styled.span`
  font-size: 13px;
  color: ${({ theme }) => theme.textSecondary};
  font-weight: 500;
`;

const TotalValue = styled.span`
  font-size: 20px;
  font-weight: 700;
  color: ${({ theme }) => theme.primary};
`;

// ─── Estado stepper ────────────────────────────────────────────────────────────
const Stepper = styled.div`
  display: flex;
  align-items: center;
  gap: 0;
  overflow-x: auto;
  padding-bottom: 4px;
  margin-bottom: 20px;
`;

const StepItem = styled.div`
  display: flex;
  align-items: center;
  gap: 0;
  flex-shrink: 0;
`;

const StepDot = styled.div`
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  background: ${({ $active, $done, $color, theme }) =>
    $active ? $color
    : $done ? $color + "33"
    : theme.bg3};
  color: ${({ $active, $done, $color, theme }) =>
    $active || $done ? $color : theme.textSecondary};
  border: 2px solid ${({ $active, $done, $color, theme }) =>
    $active || $done ? $color : theme.color2};
  transition: all 0.2s;
`;

const StepLine = styled.div`
  width: 28px;
  height: 2px;
  background: ${({ $done, $color, theme }) =>
    $done ? $color + "66" : theme.color2};
`;

// ─── Panel izquierdo: lista ────────────────────────────────────────────────────
function ListaPanel({ selectedId, onSelect, onNew }) {
  const [busqueda, setBusqueda] = useState("");
  const [estadoFiltro, setEstadoFiltro] = useState("");
  const [focused, setFocused] = useState(false);

  const { data, isLoading } = useComprasAsistidasQuery({
    page: 1,
    limit: 100,
    ...(estadoFiltro ? { estado_ca: estadoFiltro } : {}),
  });

  const items = data?.data ?? [];
  const filtered = busqueda.trim()
    ? items.filter((i) => {
        const q = busqueda.toLowerCase();
        return (
          clienteNombre(i.cliente).toLowerCase().includes(q) ||
          (i.descripcion_libre ?? "").toLowerCase().includes(q)
        );
      })
    : items;

  return (
    <LeftPanel>
      <LeftHeader>
        <SearchRow>
          <SearchBox $focused={focused} style={{ flex: 1 }}>
            <Icon icon="mdi:magnify" width={15} style={{ flexShrink: 0 }} />
            <SearchInput
              placeholder="Buscar…"
              value={busqueda}
              onChange={(e) => setBusqueda(e.target.value)}
              onFocus={() => setFocused(true)}
              onBlur={() => setFocused(false)}
            />
            {busqueda && (
              <Icon
                icon="mdi:close"
                width={14}
                onClick={() => setBusqueda("")}
                style={{ cursor: "pointer", flexShrink: 0 }}
              />
            )}
          </SearchBox>
          <NewBtn onClick={onNew} title="Nueva compra asistida">
            <Icon icon="mdi:plus" width={16} />
            Nueva
          </NewBtn>
        </SearchRow>

        <FilterSelect value={estadoFiltro} onChange={(e) => setEstadoFiltro(e.target.value)}>
          <option value="">Todos los estados</option>
          {ESTADOS.map((e) => (
            <option key={e.value} value={e.value}>{e.label}</option>
          ))}
        </FilterSelect>
      </LeftHeader>

      <ListContainer>
        {isLoading ? (
          <ListEmpty>
            <Icon icon="mdi:loading" width={28} style={{ animation: "spin 1s linear infinite" }} />
            <span>Cargando…</span>
          </ListEmpty>
        ) : filtered.length === 0 ? (
          <ListEmpty>
            <Icon icon="mdi:package-variant-outline" width={36} />
            <span>{busqueda ? "Sin coincidencias" : "Sin compras asistidas"}</span>
          </ListEmpty>
        ) : (
          filtered.map((item) => {
            const est = getEstado(item.estado_ca);
            const total = calcTotalGs(item);
            return (
              <ListItem
                key={item.id}
                $selected={item.id === selectedId}
                onClick={() => onSelect(item.id)}
              >
                <ListItemTop>
                  <ListItemName>{clienteNombre(item.cliente)}</ListItemName>
                  <Badge $color={est.color}>
                    <Icon icon={est.icon} width={10} />
                    {est.label}
                  </Badge>
                </ListItemTop>
                {item.descripcion_libre && (
                  <ListItemDesc>{item.descripcion_libre}</ListItemDesc>
                )}
                {total > 0 && (
                  <ListItemAmount>{fmtGs(total)}</ListItemAmount>
                )}
              </ListItem>
            );
          })
        )}
      </ListContainer>
    </LeftPanel>
  );
}

// ─── Detalle de compra asistida ───────────────────────────────────────────────
function DetallePanel({ id }) {
  const { data: pedido, isLoading } = useCompraAsistidaQuery(id);
  const [editMode, setEditMode] = useState(false);
  const [form, setForm] = useState(null);

  const update   = useUpdateCompraAsistidaMutation();
  const avanzar  = useAvanzarEstadoCAMutation();
  const pago     = useIniciarPagoCAMutation();
  const cancelar = useCancelarCAMutation();

  if (isLoading) return (
    <RightPanel>
      <ListEmpty style={{ height: "100%" }}>
        <Icon icon="mdi:loading" width={32} style={{ animation: "spin 1s linear infinite" }} />
      </ListEmpty>
    </RightPanel>
  );
  if (!pedido) return (
    <RightPanel>
      <EmptyRight><span>No encontrado</span></EmptyRight>
    </RightPanel>
  );

  const est = getEstado(pedido.estado_ca);
  const nextEstados = NEXT[pedido.estado_ca] ?? [];
  const canPay = pedido.estado_ca === "confirmado" && !pedido.pago_bancard_id;
  const total = calcTotalGs(pedido);
  const estadoIdx = ESTADOS.findIndex((e) => e.value === pedido.estado_ca);

  const startEdit = () => {
    setForm({
      descripcion_libre: pedido.descripcion_libre ?? "",
      url_producto_china: pedido.url_producto_china ?? "",
      proveedor_china: pedido.proveedor_china ?? "",
      cotizacion_usd_gs: pedido.cotizacion_usd_gs ?? "",
      monto_producto_usd: pedido.monto_producto_usd ?? "",
      monto_servicio_gs: pedido.monto_servicio_gs ?? "",
      monto_logistica_gs: pedido.monto_logistica_gs ?? "",
      monto_comision_gs: pedido.monto_comision_gs ?? "",
      link_seguimiento: pedido.link_seguimiento ?? "",
    });
    setEditMode(true);
  };

  const set = (k, v) => setForm((f) => ({ ...f, [k]: v }));

  const handleSave = () => {
    update.mutate(
      { id: pedido.id, data: {
        descripcion_libre: form.descripcion_libre || undefined,
        url_producto_china: form.url_producto_china || undefined,
        proveedor_china: form.proveedor_china || undefined,
        cotizacion_usd_gs: form.cotizacion_usd_gs ? +form.cotizacion_usd_gs : undefined,
        monto_producto_usd: form.monto_producto_usd ? +form.monto_producto_usd : undefined,
        monto_servicio_gs: form.monto_servicio_gs ? +form.monto_servicio_gs : undefined,
        monto_logistica_gs: form.monto_logistica_gs ? +form.monto_logistica_gs : undefined,
        monto_comision_gs: form.monto_comision_gs ? +form.monto_comision_gs : undefined,
        link_seguimiento: form.link_seguimiento || undefined,
      }},
      { onSuccess: () => setEditMode(false) }
    );
  };

  const d = editMode ? form : pedido;

  return (
    <RightPanel>
      {/* Header */}
      <FormHeader>
        <div>
          <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 6 }}>
            <FormTitle>{clienteNombre(pedido.cliente)}</FormTitle>
            <Badge $color={est.color}>
              <Icon icon={est.icon} width={11} />
              {est.label}
            </Badge>
          </div>
          {pedido.descripcion_libre && (
            <div style={{ fontSize: 13, color: "var(--text-secondary)", maxWidth: 480 }}>
              {pedido.descripcion_libre}
            </div>
          )}
        </div>
        <BtnGroup>
          {editMode ? (
            <>
              <Btn onClick={() => setEditMode(false)}>Cancelar</Btn>
              <Btn $variant="primary" onClick={handleSave} disabled={update.isPending}>
                <Icon icon="mdi:content-save" />
                {update.isPending ? "Guardando…" : "Guardar"}
              </Btn>
            </>
          ) : (
            <Btn onClick={startEdit}>
              <Icon icon="mdi:pencil-outline" />
              Editar
            </Btn>
          )}
        </BtnGroup>
      </FormHeader>

      {/* Stepper de estado (solo estados relevantes del flujo normal) */}
      {pedido.estado_ca !== "cancelado" && (
        <Stepper>
          {ESTADOS.filter((e) => e.value !== "cancelado").map((e, i) => {
            const isActive = e.value === pedido.estado_ca;
            const isDone = ESTADOS.findIndex((x) => x.value === pedido.estado_ca) > i;
            return (
              <StepItem key={e.value}>
                <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 3 }}>
                  <StepDot $active={isActive} $done={isDone} $color={e.color}>
                    <Icon icon={isDone ? "mdi:check" : e.icon} width={15} />
                  </StepDot>
                  <span style={{ fontSize: 9, color: isActive ? e.color : "var(--text-secondary)", fontWeight: isActive ? 700 : 400, whiteSpace: "nowrap" }}>
                    {e.label}
                  </span>
                </div>
                {i < ESTADOS.filter((x) => x.value !== "cancelado").length - 1 && (
                  <StepLine $done={isDone} $color={e.color} style={{ alignSelf: "flex-start", marginTop: 16 }} />
                )}
              </StepItem>
            );
          })}
        </Stepper>
      )}

      {/* Total */}
      {total > 0 && (
        <TotalCard style={{ marginBottom: 20 }}>
          <div>
            <TotalLabel>Total estimado al cliente</TotalLabel>
            <div style={{ fontSize: 11, marginTop: 2, opacity: 0.6 }}>
              Producto + Servicio + Logística + Comisión
            </div>
          </div>
          <TotalValue>{fmtGs(total)}</TotalValue>
        </TotalCard>
      )}

      {/* Producto */}
      <Section>
        <SectionLabel>Producto</SectionLabel>
        <Grid $cols={2}>
          <Field $full>
            <FieldLabel>Descripción</FieldLabel>
            {editMode
              ? <Textarea value={d.descripcion_libre} onChange={(e) => set("descripcion_libre", e.target.value)} />
              : <div style={{ fontSize: 13, lineHeight: 1.5 }}>{pedido.descripcion_libre || "—"}</div>
            }
          </Field>
          <Field>
            <FieldLabel>URL del producto (Alibaba / 1688 / Taobao)</FieldLabel>
            {editMode
              ? <Input value={d.url_producto_china} onChange={(e) => set("url_producto_china", e.target.value)} placeholder="https://…" />
              : pedido.url_producto_china
                ? <a href={pedido.url_producto_china} target="_blank" rel="noreferrer" style={{ fontSize: 13, color: "#2196f3", wordBreak: "break-all" }}>
                    {pedido.url_producto_china}
                  </a>
                : <span style={{ fontSize: 13 }}>—</span>
            }
          </Field>
          <Field>
            <FieldLabel>Proveedor China</FieldLabel>
            {editMode
              ? <Input value={d.proveedor_china} onChange={(e) => set("proveedor_china", e.target.value)} />
              : <span style={{ fontSize: 13 }}>{pedido.proveedor_china || "—"}</span>
            }
          </Field>
        </Grid>
      </Section>

      {/* Montos */}
      <Section>
        <SectionLabel>Desglose de costos</SectionLabel>
        <Grid $cols={2}>
          <Field>
            <FieldLabel>Cotización USD → Gs</FieldLabel>
            {editMode
              ? <Input type="number" value={d.cotizacion_usd_gs} onChange={(e) => set("cotizacion_usd_gs", e.target.value)} placeholder="7500" />
              : <span style={{ fontSize: 13 }}>{pedido.cotizacion_usd_gs ? fmtGs(pedido.cotizacion_usd_gs) : "—"}</span>
            }
          </Field>
          <Field>
            <FieldLabel>Costo del Producto (USD)</FieldLabel>
            {editMode
              ? <Input type="number" value={d.monto_producto_usd} onChange={(e) => set("monto_producto_usd", e.target.value)} placeholder="0.00" />
              : <span style={{ fontSize: 13, fontWeight: 600 }}>{fmtUsd(pedido.monto_producto_usd)}</span>
            }
          </Field>
          <Field>
            <FieldLabel>Honorario de Servicio (Gs)</FieldLabel>
            {editMode
              ? <Input type="number" value={d.monto_servicio_gs} onChange={(e) => set("monto_servicio_gs", e.target.value)} placeholder="0" />
              : <span style={{ fontSize: 13 }}>{fmtGs(pedido.monto_servicio_gs)}</span>
            }
          </Field>
          <Field>
            <FieldLabel>Logística / Flete + Aduana (Gs)</FieldLabel>
            {editMode
              ? <Input type="number" value={d.monto_logistica_gs} onChange={(e) => set("monto_logistica_gs", e.target.value)} placeholder="0" />
              : <span style={{ fontSize: 13 }}>{fmtGs(pedido.monto_logistica_gs)}</span>
            }
          </Field>
          <Field>
            <FieldLabel>Comisión administrativa (Gs)</FieldLabel>
            {editMode
              ? <Input type="number" value={d.monto_comision_gs} onChange={(e) => set("monto_comision_gs", e.target.value)} placeholder="0" />
              : <span style={{ fontSize: 13 }}>{fmtGs(pedido.monto_comision_gs)}</span>
            }
          </Field>
        </Grid>
      </Section>

      {/* Seguimiento */}
      {(pedido.link_seguimiento || editMode || ["en_transito","en_aduana"].includes(pedido.estado_ca)) && (
        <Section>
          <SectionLabel>Seguimiento del envío</SectionLabel>
          <Field>
            <FieldLabel>Link de tracking</FieldLabel>
            {editMode
              ? <Input value={d.link_seguimiento ?? ""} onChange={(e) => set("link_seguimiento", e.target.value)} placeholder="https://…" />
              : pedido.link_seguimiento
                ? <a href={pedido.link_seguimiento} target="_blank" rel="noreferrer" style={{ fontSize: 13, color: "#2196f3" }}>
                    {pedido.link_seguimiento}
                  </a>
                : <span style={{ fontSize: 13, color: "#888" }}>Sin link de tracking aún</span>
            }
          </Field>
        </Section>
      )}

      {/* Estado del pago */}
      {pedido.pago_bancard && (
        <Section>
          <SectionLabel>Pago con Bancard</SectionLabel>
          <div style={{ display: "flex", gap: 16, alignItems: "center", fontSize: 13 }}>
            <Badge $color={pedido.pago_bancard.estado === "aprobado" ? "#4caf50" : "#f44336"}>
              <Icon icon={pedido.pago_bancard.estado === "aprobado" ? "mdi:check-circle" : "mdi:clock-outline"} width={11} />
              {pedido.pago_bancard.estado}
            </Badge>
            <span style={{ fontWeight: 600 }}>{fmtGs(pedido.pago_bancard.monto)}</span>
          </div>
        </Section>
      )}

      {/* Acciones */}
      {!editMode && (nextEstados.length > 0 || canPay) && (
        <Section>
          <SectionLabel>Acciones disponibles</SectionLabel>
          <BtnGroup>
            {canPay && (
              <Btn $variant="primary" onClick={() => pago.mutate(pedido.id)} disabled={pago.isPending}>
                <Icon icon="mdi:credit-card-outline" />
                {pago.isPending ? "Iniciando…" : "Cobrar con Bancard"}
              </Btn>
            )}
            {nextEstados.filter((e) => e !== "cancelado").map((estado) => {
              const e = getEstado(estado);
              return (
                <Btn
                  key={estado}
                  $variant="primary"
                  onClick={() => avanzar.mutate({ id: pedido.id, estado })}
                  disabled={avanzar.isPending}
                  style={{ background: e.color }}
                >
                  <Icon icon={e.icon} />
                  Pasar a: {e.label}
                </Btn>
              );
            })}
            {nextEstados.includes("cancelado") && (
              <Btn
                $variant="danger"
                onClick={() => {
                  if (window.confirm(`¿Cancelar la compra de ${clienteNombre(pedido.cliente)}?`)) {
                    cancelar.mutate(pedido.id);
                  }
                }}
                disabled={cancelar.isPending}
              >
                <Icon icon="mdi:close-circle-outline" />
                Cancelar pedido
              </Btn>
            )}
          </BtnGroup>
        </Section>
      )}
    </RightPanel>
  );
}

// ─── Nueva compra asistida ────────────────────────────────────────────────────
function NuevoPanel({ onCreated, onCancel }) {
  const [step, setStep] = useState(1); // 1=cliente, 2=detalle
  const [cliente, setCliente] = useState(null);
  const [clienteQuery, setClienteQuery] = useState("");
  const [form, setForm] = useState({
    descripcion_libre: "", url_producto_china: "", proveedor_china: "",
    cotizacion_usd_gs: "", monto_producto_usd: "",
    monto_servicio_gs: "", monto_logistica_gs: "", monto_comision_gs: "",
  });

  const create = useCreateCompraAsistidaMutation();
  const set = (k, v) => setForm((f) => ({ ...f, [k]: v }));

  const total = (() => {
    const cotiz = +form.cotizacion_usd_gs || 0;
    const prod  = +form.monto_producto_usd || 0;
    const serv  = +form.monto_servicio_gs || 0;
    const log   = +form.monto_logistica_gs || 0;
    const com   = +form.monto_comision_gs || 0;
    return prod * cotiz + serv + log + com;
  })();

  const handleSubmit = () => {
    if (!cliente) { toast.error("Seleccioná un cliente"); return; }
    create.mutate(
      {
        cliente_id: cliente.id,
        descripcion_libre: form.descripcion_libre || undefined,
        url_producto_china: form.url_producto_china || undefined,
        proveedor_china: form.proveedor_china || undefined,
        cotizacion_usd_gs: form.cotizacion_usd_gs ? +form.cotizacion_usd_gs : undefined,
        monto_producto_usd: form.monto_producto_usd ? +form.monto_producto_usd : undefined,
        monto_servicio_gs: form.monto_servicio_gs ? +form.monto_servicio_gs : undefined,
        monto_logistica_gs: form.monto_logistica_gs ? +form.monto_logistica_gs : undefined,
        monto_comision_gs: form.monto_comision_gs ? +form.monto_comision_gs : undefined,
      },
      { onSuccess: (data) => onCreated(data.id) }
    );
  };

  return (
    <RightPanel>
      <FormHeader>
        <div>
          <FormTitle>Nueva Compra Asistida</FormTitle>
          <div style={{ fontSize: 13, marginTop: 4, opacity: 0.6 }}>
            {step === 1 ? "Paso 1 de 2 — Seleccioná el cliente" : "Paso 2 de 2 — Completá los detalles"}
          </div>
        </div>
        <Btn onClick={onCancel}>
          <Icon icon="mdi:close" />
          Cancelar
        </Btn>
      </FormHeader>

      {/* Paso 1: cliente */}
      <Section>
        <SectionLabel>Cliente</SectionLabel>
        {cliente ? (
          <ClienteCard>
            <Icon icon="mdi:account-check" width={28} style={{ color: "#4caf50", flexShrink: 0 }} />
            <ClienteInfo>
              <ClienteName>{clienteNombre(cliente)}</ClienteName>
              <ClienteMeta>
                {cliente.personas?.ruc && `RUC: ${cliente.personas.ruc}`}
                {cliente.tipo_cliente && ` · ${cliente.tipo_cliente}`}
              </ClienteMeta>
            </ClienteInfo>
            <Btn onClick={() => { setCliente(null); setClienteQuery(""); }}>
              <Icon icon="mdi:pencil-outline" />
              Cambiar
            </Btn>
          </ClienteCard>
        ) : (
          <ClienteSearchInline
            value={clienteQuery}
            onChange={setClienteQuery}
            onSelect={(c) => { setCliente(c); setClienteQuery(clienteNombre(c)); }}
          />
        )}
      </Section>

      {/* Paso 2: detalles (aparece cuando hay cliente) */}
      {cliente && (
        <>
          <Section>
            <SectionLabel>Descripción del producto</SectionLabel>
            <Grid $cols={1}>
              <Field>
                <FieldLabel>Descripción libre</FieldLabel>
                <Textarea
                  value={form.descripcion_libre}
                  onChange={(e) => set("descripcion_libre", e.target.value)}
                  placeholder="Ej: Auriculares inalámbricos Sony WH-1000XM5, color negro…"
                />
              </Field>
              <Field>
                <FieldLabel>URL del producto (Alibaba / 1688 / Taobao)</FieldLabel>
                <Input
                  value={form.url_producto_china}
                  onChange={(e) => set("url_producto_china", e.target.value)}
                  placeholder="https://…"
                />
              </Field>
              <Field>
                <FieldLabel>Proveedor China</FieldLabel>
                <Input
                  value={form.proveedor_china}
                  onChange={(e) => set("proveedor_china", e.target.value)}
                  placeholder="Nombre del vendedor o tienda"
                />
              </Field>
            </Grid>
          </Section>

          <Section>
            <SectionLabel>Montos (opcional — podés completarlo después)</SectionLabel>
            <Grid $cols={2}>
              <Field>
                <FieldLabel>Cotización USD → Gs</FieldLabel>
                <Input type="number" value={form.cotizacion_usd_gs} onChange={(e) => set("cotizacion_usd_gs", e.target.value)} placeholder="7500" />
              </Field>
              <Field>
                <FieldLabel>Costo Producto (USD)</FieldLabel>
                <Input type="number" value={form.monto_producto_usd} onChange={(e) => set("monto_producto_usd", e.target.value)} placeholder="0.00" />
              </Field>
              <Field>
                <FieldLabel>Servicio (Gs)</FieldLabel>
                <Input type="number" value={form.monto_servicio_gs} onChange={(e) => set("monto_servicio_gs", e.target.value)} placeholder="0" />
              </Field>
              <Field>
                <FieldLabel>Logística (Gs)</FieldLabel>
                <Input type="number" value={form.monto_logistica_gs} onChange={(e) => set("monto_logistica_gs", e.target.value)} placeholder="0" />
              </Field>
              <Field>
                <FieldLabel>Comisión (Gs)</FieldLabel>
                <Input type="number" value={form.monto_comision_gs} onChange={(e) => set("monto_comision_gs", e.target.value)} placeholder="0" />
              </Field>
            </Grid>

            {total > 0 && (
              <TotalCard style={{ marginTop: 12 }}>
                <TotalLabel>Total al cliente</TotalLabel>
                <TotalValue>{fmtGs(total)}</TotalValue>
              </TotalCard>
            )}
          </Section>

          <Btn
            $variant="primary"
            onClick={handleSubmit}
            disabled={create.isPending}
            style={{ minWidth: 180, justifyContent: "center" }}
          >
            <Icon icon={create.isPending ? "mdi:loading" : "mdi:plus"} />
            {create.isPending ? "Creando…" : "Crear Compra Asistida"}
          </Btn>
        </>
      )}
    </RightPanel>
  );
}

// ─── Componente principal ─────────────────────────────────────────────────────
export function CompraAsistidaTab() {
  const [selectedId, setSelectedId] = useState(null);
  const [isNew, setIsNew] = useState(false);

  return (
    <Layout>
      <ListaPanel
        selectedId={selectedId}
        onSelect={(id) => { setSelectedId(id); setIsNew(false); }}
        onNew={() => { setSelectedId(null); setIsNew(true); }}
      />

      {isNew ? (
        <NuevoPanel
          onCreated={(id) => { setSelectedId(id); setIsNew(false); }}
          onCancel={() => setIsNew(false)}
        />
      ) : selectedId ? (
        <DetallePanel id={selectedId} />
      ) : (
        <RightPanel>
          <EmptyRight>
            <Icon icon="mdi:package-variant" style={{ fontSize: 56, opacity: 0.25 }} />
            <span style={{ fontSize: 14 }}>Seleccioná una compra o creá una nueva</span>
            <Btn $variant="primary" onClick={() => setIsNew(true)}>
              <Icon icon="mdi:plus" />
              Nueva Compra Asistida
            </Btn>
          </EmptyRight>
        </RightPanel>
      )}
    </Layout>
  );
}
