import { Icon } from "@iconify/react/dist/iconify.js";
import { useQuery } from "@tanstack/react-query";
import { useEffect, useMemo, useRef, useState } from "react";
import { getReferenciales } from "../api/referenciales.service";
import { useNavigate, useParams } from "react-router-dom";
import { toast } from "sonner";
import styled, { ThemeProvider } from "styled-components";
import { getCondicionesPago } from "../api/condiciones-pago.service";
import { getDepositos } from "../api/depositos.service";
import { getEmpresaMonedas } from "../api/monedas.service";
import { getNumeracionesBySucursal } from "../api/numeraciones.service";
import { confirmarOrdenVenta, createOrdenVenta, getOrdenVenta, updateOrdenVenta } from "../api/ordenes.service";
import { getSucursales } from "../api/sucursales.service";
import { getVendedoresActivos } from "../api/vendedores-cobradores.service";
import { ClienteSearch } from "../components/organismos/POSAdmin/ClienteSearch";
import { PresupuestoAceptadoBanner } from "../components/organismos/PresupuestosDesign/PresupuestoAceptadoBanner";
import { ItemsTable } from "../components/organismos/POSAdmin/ItemsTable";
import { ProductSearch } from "../components/organismos/POSAdmin/ProductSearch";
import { useEmpresa } from "../context/EmpresaContext";
import { useAuthStore } from "../store/AuthStore";
import { useThemeStore } from "../store/ThemeStore";
import { hoyISO } from "../utils/fecha";

const TIPO_DOC_ORDEN_CODIGO = 200;

function calcularTotales(items) {
  let bruto = 0, iva10 = 0, iva5 = 0, exentas = 0;
  for (const item of items) {
    const precio = Number(item.precio_unitario || item.precio_venta || 0);
    const cantidad = Number(item.cantidad || 1);
    const descMonto = Number(item.descuento_particular_precio_unitario_item || 0);
    const base = precio * cantidad - descMonto;
    const piva = Number(item.porcentaje_iva ?? item.iva ?? 10);
    bruto += base;
    if (piva === 10) iva10 += base * 10 / 110;
    else if (piva === 5) iva5 += base * 5 / 105;
    else exentas += base;
  }
  return {
    bruto: Math.round(bruto),
    iva10: Math.round(iva10),
    iva5: Math.round(iva5),
    totalIva: Math.round(iva10 + iva5),
    exentas: Math.round(exentas),
    total: Math.round(bruto),
  };
}

function fmtGs(n) {
  return `₲ ${Math.round(n || 0).toLocaleString("es-PY")}`;
}

export function OrdenVentaNueva() {
  const navigate = useNavigate();
  const { id: ordenId } = useParams();
  const isEditing = !!ordenId;
  const { themeStyle } = useThemeStore();
  const { user } = useAuthStore();
  const { empresa } = useEmpresa();

  // Form state
  const [sucursales, setSucursales] = useState([]);
  const [sucursalActiva, setSucursalActiva] = useState(null);
  const [puntoExpedicionActivo, setPuntoExpedicionActivo] = useState(null);
  const [numeracionActiva, setNumeracionActiva] = useState(null);
  const [monedas, setMonedas] = useState([]);
  const [monedaActiva, setMonedaActiva] = useState(null);
  const [condiciones, setCondiciones] = useState([]);
  const [condicion, setCondicion] = useState(null);
  const [depositos, setDepositos] = useState([]);
  const [deposito, setDeposito] = useState(null);
  const [vendedores, setVendedores] = useState([]);
  const [vendedor, setVendedor] = useState(null);
  const [fecha, setFecha] = useState(() => hoyISO());
  const [fechaVenc, setFechaVenc] = useState("");
  const [observaciones, setObservaciones] = useState("");

  // Cliente e items
  const [cliente, setCliente] = useState(null);
  const [items, setItems] = useState([]);
  const itemIdRef = useRef(0);

  // Loading
  const [saving, setSaving] = useState(false);
  const [confirming, setConfirming] = useState(false);

  // ── Fetch existing orden for edit mode ───────────────────

  const { data: ordenExistente } = useQuery({
    queryKey: ["orden-venta-edit", ordenId],
    queryFn: () => getOrdenVenta(ordenId),
    enabled: isEditing,
    staleTime: 0,
  });

  // Populate form once orden data arrives
  useEffect(() => {
    if (!ordenExistente) return;
    const o = ordenExistente.data || ordenExistente;
    if (o.estado_orden !== "borrador") {
      toast.error("Solo se pueden editar órdenes en borrador");
      navigate("/ventas?tab=ordenes-venta");
      return;
    }
    if (o.cliente) setCliente(o.cliente);
    if (o.fecha_pedido) setFecha(o.fecha_pedido.split("T")[0]);
    if (o.fecha_venc_orden) setFechaVenc(o.fecha_venc_orden.split("T")[0]);
    if (o.observaciones) setObservaciones(o.observaciones);
    const detalleItems = o.detalle || o.pedidos_detalle || [];
    if (detalleItems.length) {
      setItems(
        detalleItems.map((d, i) => ({
          _localId: i + 1,
          id: d.id,
          producto_id: d.producto_id,
          cod_producto: d.producto?.cod_producto || d.producto?.codigo_barra || "",
          descripcion: d.producto?.descripcion || d.descripcion || "",
          unidad_medida: d.unidad_medida || d.producto?.unidades_de_medida?.representacion || "UN",
          cantidad: Number(d.cantidad),
          precio_unitario: Number(d.precio_negociado ?? 0),
          porcentaje_iva: Number(d.porcentaje_iva ?? 10),
          descuento_particular_precio_unitario_item: Number(d.descuento_porcentaje ?? 0),
          total_operacion_item: Number(d.precio_negociado ?? 0) * Number(d.cantidad ?? 1),
        }))
      );
    }
    // Sucursal, deposito, vendedor, moneda, condicion populated via separate effects
    // once their lists load — we capture the IDs from the orden for matching
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [ordenExistente]);

  // After lists load, match ids from existing orden
  useEffect(() => {
    if (!ordenExistente || !sucursales.length) return;
    const o = ordenExistente.data || ordenExistente;
    if (o.sucursal_id) {
      const s = sucursales.find((x) => x.id === o.sucursal_id);
      if (s) setSucursalActiva(s);
    }
  }, [ordenExistente, sucursales]);

  useEffect(() => {
    if (!ordenExistente || !monedas.length) return;
    const o = ordenExistente.data || ordenExistente;
    if (o.moneda_id) {
      const m = monedas.find((x) => (x.moneda_id || x.id) === o.moneda_id);
      if (m) setMonedaActiva(m);
    }
  }, [ordenExistente, monedas]);

  useEffect(() => {
    if (!ordenExistente || !condiciones.length) return;
    const o = ordenExistente.data || ordenExistente;
    if (o.condicion_pago_id) {
      const c = condiciones.find((x) => x.id === o.condicion_pago_id);
      if (c) setCondicion(c);
    }
  }, [ordenExistente, condiciones]);

  useEffect(() => {
    if (!ordenExistente || !vendedores.length) return;
    const o = ordenExistente.data || ordenExistente;
    if (o.vendedor_id) {
      const v = vendedores.find((x) => x.id === o.vendedor_id);
      if (v) setVendedor(v);
    }
  }, [ordenExistente, vendedores]);

  useEffect(() => {
    if (!ordenExistente || !depositos.length) return;
    const o = ordenExistente.data || ordenExistente;
    if (o.deposito_id) {
      const d = depositos.find((x) => x.id === o.deposito_id);
      if (d) setDeposito(d);
    }
  }, [ordenExistente, depositos]);

  // ── Referenciales (unidades de medida, etc.) ──────────────

  const { data: referenciales } = useQuery({
    queryKey: ["referenciales"],
    queryFn: getReferenciales,
    staleTime: 60 * 60 * 1000,
  });

  // ── Numeraciones ───────────────────────────────────────────

  const { data: numeracionesData } = useQuery({
    queryKey: ["numeraciones-orden", sucursalActiva?.id],
    queryFn: () => getNumeracionesBySucursal(sucursalActiva?.id),
    enabled: !!sucursalActiva?.id,
  });

  const numeracionesOrden = useMemo(() => {
    if (!numeracionesData) return [];
    return (numeracionesData || []).filter(
      (n) => n.tipo_documento?.codigo === TIPO_DOC_ORDEN_CODIGO,
    );
  }, [numeracionesData]);

  const puntosExpedicion = useMemo(() => {
    const map = new Map();
    numeracionesOrden.forEach((n) => {
      if (n.punto_expedicion && !map.has(n.punto_expedicion.id)) {
        map.set(n.punto_expedicion.id, n.punto_expedicion);
      }
    });
    return Array.from(map.values());
  }, [numeracionesOrden]);

  const numeracionSiguiente = useMemo(() => {
    if (!numeracionActiva) return "";
    const pe = numeracionActiva.punto_expedicion;
    const est = pe?.empresas_sucursales?.punto_establecimiento || pe?.codigo || "001";
    const pexp = pe?.punto_expedicion || "001";
    const num = String(numeracionActiva.numero_actual).padStart(7, "0");
    return `${est}-${pexp}-${num}`;
  }, [numeracionActiva]);

  // ── Load data ────────────────────────────────────────────

  useEffect(() => {
    getSucursales()
      .then((d) => {
        const list = d?.data || d || [];
        setSucursales(list);
        const def = list.find((s) => s.id === user?.sucursal_id) || list[0];
        if (def) setSucursalActiva(def);
      })
      .catch(() => {});
  }, [user?.sucursal_id]);

  useEffect(() => {
    getEmpresaMonedas()
      .then((d) => {
        const list = d?.data || d || [];
        setMonedas(list);
        const principal = list.find((m) => m.es_principal && m.activo) || list[0];
        if (principal) setMonedaActiva(principal);
      })
      .catch(() => {});
  }, []);

  useEffect(() => {
    getCondicionesPago({ aplica_a: "VENTAS", activo: true })
      .then((list) => {
        setCondiciones(list);
        const contado = list.find((c) => c.cod_condicion_venta === 1) || list[0];
        if (contado) setCondicion(contado);
      })
      .catch(() => {});
  }, []);

  useEffect(() => {
    getVendedoresActivos()
      .then((d) => {
        const list = d?.data || d || [];
        setVendedores(list);
        // Auto-select vendedor vinculado al usuario actual
        const vinculado = list.find((v) => v.usuario_id === user?.id);
        if (vinculado) setVendedor(vinculado);
      })
      .catch(() => {});
  }, [user?.id]);

  useEffect(() => {
    if (!sucursalActiva?.id) return;
    getDepositos(sucursalActiva.id)
      .then((d) => {
        const list = d?.data || d || [];
        setDepositos(list);
        const principal = list.find((x) => x.es_principal && x.active);
        setDeposito(principal || list[0] || null);
      })
      .catch(() => {});
  }, [sucursalActiva?.id]);

  // Auto-select punto expedicion
  useEffect(() => {
    if (puntosExpedicion.length > 0) {
      setPuntoExpedicionActivo(puntosExpedicion[0]);
    } else {
      setPuntoExpedicionActivo(null);
    }
  }, [puntosExpedicion]);

  // Auto-select numeracion
  useEffect(() => {
    if (numeracionesOrden.length > 0 && puntoExpedicionActivo) {
      const num = numeracionesOrden.find(
        (n) => n.punto_expedicion_id === puntoExpedicionActivo.id,
      );
      setNumeracionActiva(num || null);
    } else {
      setNumeracionActiva(null);
    }
  }, [numeracionesOrden, puntoExpedicionActivo]);

  // ── Items ────────────────────────────────────────────────

  const handleAddProduct = (producto) => {
    const newItem = {
      _localId: ++itemIdRef.current,
      producto_id: producto.id || producto.producto_id,
      cod_producto: producto.cod_producto || producto.codigo,
      descripcion: producto.descripcion,
      unidad_medida: producto.unidades_de_medida?.representacion || producto.unidad_medida || "UN",
      cantidad: Number(producto.cantidad) || 1,
      precio_unitario: Number(producto.precio_venta) || 0,
      porcentaje_iva: Number(producto.porcentaje_iva ?? producto.iva ?? 10),
      descuento_particular_precio_unitario_item: 0,
      maneja_lote: producto.maneja_lote || false,
    };
    newItem.total_operacion_item = newItem.precio_unitario * newItem.cantidad;

    setItems((prev) => {
      const idx = prev.findIndex(
        (i) => i.producto_id === newItem.producto_id && i.precio_unitario === newItem.precio_unitario,
      );
      if (idx >= 0) {
        const updated = [...prev];
        updated[idx] = {
          ...updated[idx],
          cantidad: updated[idx].cantidad + newItem.cantidad,
          total_operacion_item: updated[idx].precio_unitario * (updated[idx].cantidad + newItem.cantidad),
        };
        return updated;
      }
      return [...prev, newItem];
    });
  };

  const handleUpdateItem = (index, field, value) => {
    setItems((prev) => {
      const updated = [...prev];
      const item = { ...updated[index], [field]: value };
      item.total_operacion_item =
        item.precio_unitario * item.cantidad - (item.descuento_particular_precio_unitario_item || 0);
      updated[index] = item;
      return updated;
    });
  };

  const handleRemoveItem = (index) => {
    setItems((prev) => prev.filter((_, i) => i !== index));
  };

  const totales = useMemo(() => calcularTotales(items), [items]);

  // ── Save / Confirm ────────────────────────────────────────

  const buildPayload = () => ({
    cliente_id: cliente?.id,
    sucursal_id: sucursalActiva?.id,
    deposito_id: deposito?.id,
    vendedor_id: vendedor?.id,
    moneda_id: monedaActiva?.moneda_id || monedaActiva?.id,
    condicion_pago_id: condicion?.id,
    fecha_venc_orden: fechaVenc || undefined,
    tipo_facturacion: empresa?.orden_tipo_facturacion || "total",
    observaciones: observaciones || undefined,
    items: items.map((i) => ({
      producto_id: i.producto_id,
      cantidad: i.cantidad,
      precio_negociado: i.precio_unitario,
      descuento_porcentaje: i.porcentaje_descuento_item || 0,
    })),
  });

  const handleGuardar = async () => {
    if (!cliente) { toast.error("Seleccione un cliente"); return; }
    if (items.length === 0) { toast.error("Agregue al menos un producto"); return; }
    setSaving(true);
    try {
      if (isEditing) {
        await updateOrdenVenta(ordenId, buildPayload());
        toast.success("Orden actualizada");
      } else {
        await createOrdenVenta(buildPayload());
        toast.success("Orden guardada como borrador");
      }
      setTimeout(() => navigate("/ventas?tab=ordenes-venta"), 1200);
    } catch (e) {
      toast.error(e?.response?.data?.message || "Error al guardar");
    } finally {
      setSaving(false);
    }
  };

  const handleConfirmar = async () => {
    if (!cliente) { toast.error("Seleccione un cliente"); return; }
    if (items.length === 0) { toast.error("Agregue al menos un producto"); return; }
    setConfirming(true);
    try {
      let id = ordenId;
      if (isEditing) {
        await updateOrdenVenta(ordenId, buildPayload());
      } else {
        const res = await createOrdenVenta(buildPayload());
        id = res.data?.id;
      }
      await confirmarOrdenVenta(id);
      toast.success("Orden confirmada");
      navigate("/ventas?tab=ordenes-venta");
    } catch (e) {
      toast.error(e?.response?.data?.message || "Error al confirmar");
    } finally {
      setConfirming(false);
    }
  };

  const handleLimpiar = () => {
    setCliente(null);
    setItems([]);
    setObservaciones("");
    setFechaVenc("");
  };

  return (
    <ThemeProvider theme={themeStyle}>
      <PageWrapper>
        {/* Header */}
        <PageHeader>
          <HeaderLeft>
            <BackBtn onClick={() => navigate("/ventas?tab=ordenes-venta")}>
              <Icon icon="mdi:arrow-left" width={20} />
            </BackBtn>
            <Icon icon="mdi:file-sign" width={24} style={{ color: themeStyle?.primary || "#7dd3a8" }} />
            <h1>{isEditing ? "Editar Orden de Venta" : "Nueva Orden de Venta"}</h1>
          </HeaderLeft>
          {numeracionSiguiente && (
            <NumeracionBadge>
              <Icon icon="mdi:pound" width={14} />
              {numeracionSiguiente}
            </NumeracionBadge>
          )}
          {!numeracionActiva && sucursalActiva && (
            <NoNumeracionBadge>
              <Icon icon="mdi:alert" width={14} />
              Sin numeración configurada
            </NoNumeracionBadge>
          )}
        </PageHeader>

        {/* Body */}
        <BodyGrid>
          <MainSection>
            {/* Datos de la Orden */}
            <Section>
              <SectionTitle>
                <Icon icon="mdi:clipboard-text-outline" />
                Datos de la Orden
              </SectionTitle>
              <FieldsGrid>
                <Field>
                  <label>Sucursal</label>
                  <select
                    value={sucursalActiva?.id || ""}
                    onChange={(e) => {
                      const s = sucursales.find((x) => x.id === e.target.value);
                      setSucursalActiva(s || null);
                    }}
                  >
                    {sucursales.map((s) => (
                      <option key={s.id} value={s.id}>{s.descripcion}</option>
                    ))}
                  </select>
                </Field>

                <Field>
                  <label>Punto Expedición</label>
                  <select
                    value={puntoExpedicionActivo?.id || ""}
                    onChange={(e) => {
                      const pe = puntosExpedicion.find((x) => x.id === e.target.value);
                      setPuntoExpedicionActivo(pe || null);
                    }}
                    disabled={puntosExpedicion.length === 0}
                  >
                    {puntosExpedicion.length === 0 && (
                      <option value="">Sin puntos configurados</option>
                    )}
                    {puntosExpedicion.map((pe) => (
                      <option key={pe.id} value={pe.id}>
                        {pe.punto_expedicion || pe.codigo}
                      </option>
                    ))}
                  </select>
                </Field>

                <Field>
                  <label>Numeración</label>
                  <NumeracionDisplay $hasNum={!!numeracionSiguiente}>
                    {numeracionSiguiente || "Sin numeración"}
                  </NumeracionDisplay>
                </Field>

                <Field>
                  <label>Fecha</label>
                  <input
                    type="date"
                    value={fecha}
                    onChange={(e) => setFecha(e.target.value)}
                  />
                </Field>

                <Field>
                  <label>Fecha Vencimiento</label>
                  <input
                    type="date"
                    value={fechaVenc}
                    onChange={(e) => setFechaVenc(e.target.value)}
                    min={fecha}
                  />
                </Field>

                <Field>
                  <label>Moneda</label>
                  <select
                    value={monedaActiva?.moneda_id || monedaActiva?.id || ""}
                    onChange={(e) => {
                      const m = monedas.find((x) => (x.moneda_id || x.id) === e.target.value);
                      setMonedaActiva(m || null);
                    }}
                  >
                    {monedas.map((m) => (
                      <option key={m.moneda_id || m.id} value={m.moneda_id || m.id}>
                        {m.moneda?.descripcion || m.descripcion} - {m.moneda?.codigo || m.codigo}
                      </option>
                    ))}
                  </select>
                </Field>

                <Field>
                  <label>Condición de Pago</label>
                  <select
                    value={condicion?.id || ""}
                    onChange={(e) => {
                      const c = condiciones.find((x) => x.id === e.target.value);
                      setCondicion(c || null);
                    }}
                  >
                    {condiciones.map((c) => (
                      <option key={c.id} value={c.id}>{c.descripcion}</option>
                    ))}
                  </select>
                </Field>

                <Field>
                  <label>Depósito Inventario</label>
                  <select
                    value={deposito?.id || ""}
                    onChange={(e) => {
                      const d = depositos.find((x) => x.id === e.target.value);
                      setDeposito(d || null);
                    }}
                  >
                    <option value="">— Sin depósito —</option>
                    {depositos.map((d) => (
                      <option key={d.id} value={d.id}>{d.descripcion}</option>
                    ))}
                  </select>
                </Field>

                <Field>
                  <label>Vendedor</label>
                  <select
                    value={vendedor?.id || ""}
                    onChange={(e) => {
                      const v = vendedores.find((x) => x.id === e.target.value);
                      setVendedor(v || null);
                    }}
                  >
                    <option value="">— Sin vendedor —</option>
                    {vendedores.map((v) => (
                      <option key={v.id} value={v.id}>
                        {v.nombre} {v.apellido || ""}
                      </option>
                    ))}
                  </select>
                </Field>
              </FieldsGrid>
            </Section>

            {/* Datos del Cliente */}
            <Section>
              <SectionTitle>
                <Icon icon="mdi:account-outline" />
                Datos del Cliente
              </SectionTitle>
              <ClienteSearch value={cliente} onChange={setCliente} />
              {!isEditing && cliente?.id && (
                <PresupuestoAceptadoBanner
                  clienteId={cliente.id}
                  zona={cliente.zona}
                  onConverted={(pedidoId) => pedidoId && navigate(`/ordenes-venta/${pedidoId}`)}
                />
              )}
            </Section>

            {/* Buscar Producto */}
            <Section>
              <SectionTitle>
                <Icon icon="mdi:magnify" />
                Buscar Producto
              </SectionTitle>
              <ProductSearch
                onProductSelect={handleAddProduct}
                cliente={cliente}
                condicionPago={condicion}
                depositoActivo={deposito}
                sucursalId={sucursalActiva?.id}
                moneda={monedaActiva}
                referenciales={referenciales}
              />
            </Section>

            {/* Items Table */}
            <ItemsTable
              items={items}
              onUpdateItem={handleUpdateItem}
              onRemoveItem={handleRemoveItem}
              moneda={monedaActiva}
              enableDiscounts={false}
            />
          </MainSection>

          {/* Side Panel */}
          <SidePanelWrapper>
            <Section>
              <SectionTitle>
                <Icon icon="mdi:calculator-variant-outline" />
                Resumen
              </SectionTitle>

              <TotalRow>
                <span>Total Bruto</span>
                <span>{fmtGs(totales.bruto)}</span>
              </TotalRow>
              <TotalRow>
                <span>Liq. IVA 10%</span>
                <span>{fmtGs(totales.iva10)}</span>
              </TotalRow>
              <TotalRow>
                <span>Liq. IVA 5%</span>
                <span>{fmtGs(totales.iva5)}</span>
              </TotalRow>
              <TotalRow>
                <span>Total IVA</span>
                <span>{fmtGs(totales.totalIva)}</span>
              </TotalRow>
              <TotalRow>
                <span>Total Exentas</span>
                <span>{fmtGs(totales.exentas)}</span>
              </TotalRow>
              <TotalRowBig>
                <span>TOTAL ORDEN</span>
                <span>{fmtGs(totales.total)}</span>
              </TotalRowBig>

              {empresa?.orden_tipo_facturacion && empresa.orden_tipo_facturacion !== "total" && (
                <TipoFacturacionInfo>
                  <Icon icon="mdi:information-outline" width={12} />
                  Facturación: {empresa.orden_tipo_facturacion === "parcial_item" ? "Parcial por ítem" : "Parcial por monto"}
                </TipoFacturacionInfo>
              )}
            </Section>

            <Section>
              <SectionTitle>
                <Icon icon="mdi:text-box-outline" />
                Observaciones
              </SectionTitle>
              <ObsTextarea
                placeholder="Observaciones opcionales..."
                value={observaciones}
                onChange={(e) => setObservaciones(e.target.value)}
                rows={4}
              />
            </Section>

            <ActionGroup>
              <BtnLimpiar type="button" onClick={handleLimpiar}>
                <Icon icon="mdi:trash-can-outline" width={16} />
                Limpiar
              </BtnLimpiar>
              <BtnGuardar
                type="button"
                onClick={handleGuardar}
                disabled={saving || confirming}
              >
                {saving ? <Icon icon="mdi:loading" width={16} className="spin" /> : <Icon icon="mdi:content-save-outline" width={16} />}
                {isEditing ? "Guardar Cambios" : "Guardar Borrador"}
              </BtnGuardar>
              <BtnConfirmar
                type="button"
                onClick={handleConfirmar}
                disabled={saving || confirming}
              >
                {confirming ? <Icon icon="mdi:loading" width={16} className="spin" /> : <Icon icon="mdi:check-circle-outline" width={16} />}
                Confirmar Orden
              </BtnConfirmar>
            </ActionGroup>
          </SidePanelWrapper>
        </BodyGrid>
      </PageWrapper>
    </ThemeProvider>
  );
}

// ── Styled Components ─────────────────────────────────────────────────────────

const PageWrapper = styled.div`
  min-height: 100vh;
  background: ${({ theme }) => theme?.bg || "#0f0f0f"};
  color: ${({ theme }) => theme?.text || "#f1f1f1"};
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 16px;
`;

const PageHeader = styled.header`
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 14px 20px;
  background: ${({ theme }) => theme?.bg2 || "#141414"};
  border-radius: 12px;
  border: 1px solid ${({ theme }) => theme?.color2 || "#2a2a2a"};
`;

const HeaderLeft = styled.div`
  display: flex;
  align-items: center;
  gap: 12px;

  h1 {
    margin: 0;
    font-size: 1.2rem;
    font-weight: 700;
  }
`;

const BackBtn = styled.button`
  display: flex;
  align-items: center;
  justify-content: center;
  width: 36px;
  height: 36px;
  border: none;
  border-radius: 8px;
  background: ${({ theme }) => theme?.bg3 || "#1a1a1a"};
  color: ${({ theme }) => theme?.text || "#f1f1f1"};
  cursor: pointer;
  transition: background 0.2s;

  &:hover {
    background: ${({ theme }) => theme?.bg4 || "#222"};
  }
`;

const NumeracionBadge = styled.div`
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 6px 12px;
  background: ${({ theme }) => (theme?.primary || "#7dd3a8") + "18"};
  border: 1px solid ${({ theme }) => (theme?.primary || "#7dd3a8") + "40"};
  border-radius: 8px;
  font-size: 0.8rem;
  font-weight: 600;
  font-family: monospace;
  color: ${({ theme }) => theme?.primary || "#7dd3a8"};
`;

const NoNumeracionBadge = styled.div`
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 6px 12px;
  background: #ef444415;
  border: 1px solid #ef444430;
  border-radius: 8px;
  font-size: 0.8rem;
  font-weight: 600;
  color: #ef4444;
`;

const BodyGrid = styled.div`
  display: grid;
  grid-template-columns: 1fr 320px;
  gap: 16px;
  align-items: start;

  @media (max-width: 960px) {
    grid-template-columns: 1fr;
  }
`;

const MainSection = styled.main`
  display: flex;
  flex-direction: column;
  gap: 16px;
`;

const SidePanelWrapper = styled.aside`
  display: flex;
  flex-direction: column;
  gap: 16px;
  position: sticky;
  top: 16px;
`;

const Section = styled.div`
  background: ${({ theme }) => theme?.bg2 || "#141414"};
  border-radius: 12px;
  border: 1px solid ${({ theme }) => theme?.color2 || "#2a2a2a"};
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 12px;
`;

const SectionTitle = styled.h3`
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0 0 4px 0;
  font-size: 0.9rem;
  font-weight: 600;
  color: ${({ theme }) => theme?.primary || "#7dd3a8"};
`;

const FieldsGrid = styled.div`
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 12px;

  @media (max-width: 1200px) {
    grid-template-columns: repeat(3, 1fr);
  }

  @media (max-width: 768px) {
    grid-template-columns: repeat(2, 1fr);
  }
`;

const Field = styled.div`
  display: flex;
  flex-direction: column;
  gap: 4px;
  min-width: 0;

  label {
    font-size: 0.75rem;
    font-weight: 500;
    color: ${({ theme }) => theme?.textSecondary || "#999"};
    text-transform: uppercase;
    letter-spacing: 0.5px;
  }

  input,
  select {
    padding: 10px 12px;
    border: 1px solid ${({ theme }) => theme?.color2 || "#2a2a2a"};
    border-radius: 8px;
    background: ${({ theme }) => theme?.bg3 || "#1a1a1a"};
    color: inherit;
    font-size: 0.9rem;
    width: 100%;
    box-sizing: border-box;
    transition: border-color 0.2s;

    &:focus {
      outline: none;
      border-color: ${({ theme }) => theme?.primary || "#7dd3a8"};
      box-shadow: 0 0 0 3px ${({ theme }) => (theme?.primary || "#7dd3a8") + "20"};
    }

    &:disabled {
      opacity: 0.5;
      cursor: default;
    }
  }

  select { cursor: pointer; }
`;

const NumeracionDisplay = styled.div`
  padding: 10px 12px;
  border: 1px solid ${({ theme, $hasNum }) => $hasNum ? (theme?.primary || "#7dd3a8") + "60" : "#ef444440"};
  border-radius: 8px;
  background: ${({ theme, $hasNum }) => $hasNum ? (theme?.primary || "#7dd3a8") + "12" : "#ef444410"};
  color: ${({ theme, $hasNum }) => $hasNum ? (theme?.primary || "#7dd3a8") : "#ef4444"};
  font-size: 0.9rem;
  font-weight: 600;
  font-family: monospace;
  letter-spacing: 0.5px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
`;

const TotalRow = styled.div`
  display: flex;
  justify-content: space-between;
  font-size: 0.85rem;
  color: ${({ theme }) => theme?.textSecondary || "#aaa"};
  padding: 2px 0;
`;

const TotalRowBig = styled(TotalRow)`
  font-size: 1rem;
  font-weight: 700;
  color: ${({ theme }) => theme?.primary || "#7dd3a8"};
  border-top: 1px solid ${({ theme }) => theme?.color2 || "#2a2a2a"};
  margin-top: 4px;
  padding-top: 8px;
`;

const TipoFacturacionInfo = styled.div`
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 0.72rem;
  color: ${({ theme }) => theme?.textSecondary || "#888"};
  padding-top: 4px;
`;

const ObsTextarea = styled.textarea`
  width: 100%;
  box-sizing: border-box;
  padding: 10px 12px;
  border: 1px solid ${({ theme }) => theme?.color2 || "#2a2a2a"};
  border-radius: 8px;
  background: ${({ theme }) => theme?.bg3 || "#1a1a1a"};
  color: inherit;
  font-size: 0.85rem;
  resize: vertical;
  font-family: inherit;
  transition: border-color 0.2s;

  &:focus {
    outline: none;
    border-color: ${({ theme }) => theme?.primary || "#7dd3a8"};
  }

  &::placeholder {
    color: ${({ theme }) => theme?.textSecondary || "#666"};
  }
`;

const ActionGroup = styled.div`
  display: flex;
  flex-direction: column;
  gap: 8px;
`;

const BtnBase = styled.button`
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 12px 16px;
  border: none;
  border-radius: 8px;
  font-size: 0.9rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s;
  width: 100%;

  &:disabled {
    opacity: 0.5;
    cursor: not-allowed;
  }

  .spin {
    animation: spin 1s linear infinite;
  }

  @keyframes spin {
    from { transform: rotate(0deg); }
    to { transform: rotate(360deg); }
  }
`;

const BtnLimpiar = styled(BtnBase)`
  background: transparent;
  border: 1px solid ${({ theme }) => theme?.color2 || "#2a2a2a"};
  color: ${({ theme }) => theme?.textSecondary || "#aaa"};

  &:hover:not(:disabled) {
    background: ${({ theme }) => theme?.bg3 || "#1a1a1a"};
    color: #ef4444;
    border-color: #ef444440;
  }
`;

const BtnGuardar = styled(BtnBase)`
  background: ${({ theme }) => theme?.bg3 || "#1a1a1a"};
  border: 1px solid ${({ theme }) => theme?.primary || "#7dd3a8"};
  color: ${({ theme }) => theme?.primary || "#7dd3a8"};

  &:hover:not(:disabled) {
    background: ${({ theme }) => (theme?.primary || "#7dd3a8") + "20"};
  }
`;

const BtnConfirmar = styled(BtnBase)`
  background: ${({ theme }) => theme?.primary || "#7dd3a8"};
  color: #000;

  &:hover:not(:disabled) {
    opacity: 0.9;
  }
`;
