import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { ArrowLeft, Check, ChevronsUpDown, Plus, Trash2 } from "lucide-react";

import { OcBookAPI } from "@/apis/OcBookAPI";
import { ProductAPI } from "@/apis/ProductAPI";
import { OcSupplierAPI } from "@/apis/OcSupplierAPI";
import { PaymentMethodAPI } from "@/apis/PaymentMethodAPI";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
} from "@/components/ui/command";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";
import { cn } from "@/lib/utils";
import { useAuth } from "@/hooks/useAuth";
import { useCompanyStore } from "@/hooks/store/useCompanyStore";
import { createPanelPageUrl } from "@/utils";

const MAX_LINES = 60;

const PAYMENT_METHOD_NONE = "__payment_method_none__";

/** @param {import("@/types/modules/ocSupplier").OcSupplier} s @param {import("@/types/modules/payment").PaymentMethodRecord[]} methods */
const resolvePaymentMethodIdFromSupplier = (s, methods) => {
  if (s.id_payment_method != null && String(s.id_payment_method) !== "") {
    if (methods.length === 0 || methods.some((m) => String(m.id) === String(s.id_payment_method))) {
      return String(s.id_payment_method);
    }
  }
  if (s.payment_terms && String(s.payment_terms).trim() !== "" && methods.length) {
    const t = String(s.payment_terms).trim();
    const match = methods.find((m) => String(m.name ?? "").trim() === t);
    if (match?.id != null) return String(match.id);
  }
  return PAYMENT_METHOD_NONE;
};

const round2 = (n) => Math.round(Number(n) * 100) / 100;

const lineNetSubtotal = (qty, unitPrice, discountType, discountValue) => {
  const q = Number(qty) || 0;
  const p = Number(unitPrice) || 0;
  const base = round2(q * p);
  const dv = Number(discountValue) || 0;
  if (discountType === "percent") {
    const d = round2((base * Math.min(100, Math.max(0, dv))) / 100);
    return Math.max(0, round2(base - d));
  }
  if (discountType === "amount") {
    const d = Math.min(base, Math.max(0, round2(dv)));
    return Math.max(0, round2(base - d));
  }
  return base;
};

const globalAfterDiscount = (subtotal, type, value) => {
  const s = round2(subtotal);
  const v = Number(value) || 0;
  if (type === "percent") {
    const amt = round2((s * Math.min(100, Math.max(0, v))) / 100);
    return Math.max(0, round2(s - amt));
  }
  if (type === "amount") {
    const amt = Math.min(s, Math.max(0, round2(v)));
    return Math.max(0, round2(s - amt));
  }
  return s;
};

const newLine = () => ({
  key: `${Date.now()}-${Math.random().toString(16).slice(2)}`,
  product_id: "",
  product_code: "",
  description: "",
  quantity: "1",
  unit_measure: "UN",
  unit_price: "",
  discount_type: "none",
  discount_value: "0",
});

export default function OCPurchaseOrderCreate() {
  const router = useRouter();
  const queryClient = useQueryClient();
  const { selectedCompany } = useCompanyStore();
  const { user } = useAuth();
  const companyId = String(selectedCompany?.id ?? "");

  const executedPreview = [user?.rut, user?.n_document, user?.email].filter(Boolean).join(" ") || "—";

  const [selectedSupplierId, setSelectedSupplierId] = useState("");
  const [supplierOpen, setSupplierOpen] = useState(false);

  const [emissionDate, setEmissionDate] = useState(() => {
    const d = new Date();
    const y = d.getFullYear();
    const m = String(d.getMonth() + 1).padStart(2, "0");
    const day = String(d.getDate()).padStart(2, "0");
    return `${y}-${m}-${day}`;
  });
  const [paymentMethodId, setPaymentMethodId] = useState(PAYMENT_METHOD_NONE);
  const userChosePaymentNoneRef = useRef(false);
  const [purchaseClassification, setPurchaseClassification] = useState("");
  const [costCenter, setCostCenter] = useState("");
  const [requestedBy, setRequestedBy] = useState("");
  const [quotationAuth, setQuotationAuth] = useState("");
  const [deliveryPlace, setDeliveryPlace] = useState("");
  const [validityDays, setValidityDays] = useState("");
  const [deliveryNotes, setDeliveryNotes] = useState("");
  const [contactName, setContactName] = useState("");
  const [observations, setObservations] = useState("");

  const [globalDiscountType, setGlobalDiscountType] = useState("none");
  const [globalDiscountValue, setGlobalDiscountValue] = useState("0");
  const taxRate = "19";
  const exemptAmount = "0";
  const specificTax = "0";

  const [lines, setLines] = useState(() => [newLine()]);
  const [lineProductOpen, setLineProductOpen] = useState({});

  const suppliersQuery = useQuery({
    queryKey: ["suppliers-active", companyId],
    queryFn: () => OcSupplierAPI.list(companyId),
    enabled: Boolean(companyId),
  });

  const paymentMethodsQuery = useQuery({
    queryKey: ["payment-methods", companyId],
    queryFn: () => PaymentMethodAPI.getByCompanyId(companyId),
    enabled: Boolean(companyId),
  });

  const productsQuery = useQuery({
    queryKey: ["oc-products-master", companyId],
    queryFn: () => ProductAPI.getForPurchaseOrderByCompanyId(companyId),
    enabled: Boolean(companyId),
  });

  const selectedSupplier = useMemo(() => {
    const list = suppliersQuery.data ?? [];
    return list.find((x) => String(x.id) === String(selectedSupplierId)) ?? null;
  }, [suppliersQuery.data, selectedSupplierId]);

  const pickSupplier = useCallback(
    (s) => {
      userChosePaymentNoneRef.current = false;
      setSelectedSupplierId(String(s.id));
      setSupplierOpen(false);
      const methods = paymentMethodsQuery.data ?? [];
      setPaymentMethodId(resolvePaymentMethodIdFromSupplier(s, methods));
    },
    [paymentMethodsQuery.data],
  );

  useEffect(() => {
    if (!selectedSupplierId || !selectedSupplier || userChosePaymentNoneRef.current) return;
    const methods = paymentMethodsQuery.data ?? [];
    if (methods.length === 0) return;
    setPaymentMethodId((prev) => {
      if (prev !== PAYMENT_METHOD_NONE) return prev;
      return resolvePaymentMethodIdFromSupplier(selectedSupplier, methods);
    });
  }, [paymentMethodsQuery.data, selectedSupplierId, selectedSupplier]);

  const updateLine = useCallback((key, field, value) => {
    setLines((prev) => prev.map((row) => (row.key === key ? { ...row, [field]: value } : row)));
  }, []);

  const pickLineProduct = useCallback(
    (lineKey, productId) => {
      const product = (productsQuery.data ?? []).find((p) => String(p.id ?? "") === String(productId));
      if (!product) return;
      setLines((prev) =>
        prev.map((row) =>
          row.key === lineKey
            ? {
                ...row,
                product_id: String(product.id ?? ""),
                product_code: String(product.sku ?? product.barcode ?? ""),
                description: String(product.name ?? product.description ?? ""),
                unit_measure: String(product.unit ?? row.unit_measure ?? "UN"),
                unit_price: String(
                  Number(product.cost ?? 0) > 0 ? product.cost : Number(product.price ?? 0) > 0 ? product.price : row.unit_price,
                ),
              }
            : row,
        ),
      );
      setLineProductOpen((prev) => ({ ...prev, [lineKey]: false }));
    },
    [productsQuery.data],
  );

  const addLine = useCallback(() => {
    setLines((prev) => {
      if (prev.length >= MAX_LINES) return prev;
      return [...prev, newLine()];
    });
  }, []);

  const removeLine = useCallback((key) => {
    setLines((prev) => {
      const next = prev.filter((r) => r.key !== key);
      return next.length ? next : [newLine()];
    });
  }, []);

  const totalsPreview = useMemo(() => {
    let subtotal = 0;
    let linesDisc = 0;
    for (const row of lines) {
      const q = Number(row.quantity) || 0;
      const p = Number(row.unit_price) || 0;
      const base = round2(q * p);
      const net = lineNetSubtotal(q, p, row.discount_type, row.discount_value);
      linesDisc += round2(base - net);
      subtotal += net;
    }
    subtotal = round2(subtotal);
    linesDisc = round2(linesDisc);
    const taxable = globalAfterDiscount(subtotal, globalDiscountType, globalDiscountValue);
    const globalDiscAmt = round2(subtotal - taxable);
    const tr = Number(taxRate) || 0;
    const tax = round2((taxable * tr) / 100);
    const ex = round2(Number(exemptAmount) || 0);
    const sp = round2(Number(specificTax) || 0);
    const total = round2(taxable + tax + ex + sp);
    return {
      subtotal,
      linesDisc,
      globalDiscAmt,
      taxable,
      tax,
      total,
    };
  }, [lines, globalDiscountType, globalDiscountValue, taxRate, exemptAmount, specificTax]);

  const createMutation = useMutation({
    mutationFn: async () => {
      const methods = paymentMethodsQuery.data ?? [];
      const pm = methods.find((m) => String(m.id) === String(paymentMethodId));
      const paymentTermsFromMaster = pm && String(pm.name ?? "").trim() !== "" ? String(pm.name).trim().slice(0, 80) : undefined;

      const body = {
        id_supplier: Number(selectedSupplierId),
        emission_date: emissionDate || undefined,
        payment_terms: paymentTermsFromMaster,
        purchase_classification: purchaseClassification.trim() || undefined,
        cost_center: costCenter.trim() || undefined,
        requested_by: requestedBy.trim() || undefined,
        quotation_auth_number: quotationAuth.trim() || undefined,
        delivery_place: deliveryPlace.trim() || undefined,
        validity_days: validityDays === "" ? undefined : Number(validityDays),
        delivery_notes: deliveryNotes.trim() || undefined,
        contact_name: contactName.trim() || undefined,
        global_discount_type: globalDiscountType,
        global_discount_value: Number(globalDiscountValue) || 0,
        tax_rate: Number(taxRate) || 19,
        exempt_amount: Number(exemptAmount) || 0,
        specific_tax: Number(specificTax) || 0,
        observations: observations.trim() || undefined,
        lines: lines.map((row) => ({
          product_code: row.product_code.trim() || undefined,
          description: row.description.trim(),
          quantity: Number(row.quantity),
          unit_measure: row.unit_measure.trim() || undefined,
          unit_price: Number(row.unit_price),
          discount_type: row.discount_type,
          discount_value: Number(row.discount_value) || 0,
        })),
      };
      return OcBookAPI.createPurchaseOrder(companyId, body);
    },
    onSuccess: async (order) => {
      await queryClient.invalidateQueries({ queryKey: ["oc-book-tracking", companyId] });
      await queryClient.invalidateQueries({ queryKey: ["oc-book-validation", companyId] });
      await queryClient.invalidateQueries({ queryKey: ["oc-book-match-orders", companyId] });
      await queryClient.invalidateQueries({ queryKey: ["oc-book-bitacora", companyId] });
      toast.success(`Orden creada • Folio ${order?.folio ?? ""}`);
      router.push(createPanelPageUrl("oc/book/pending-orders"));
    },
    onError: () => toast.error("No se pudo crear la orden de compra."),
  });

  const handleSubmit = (e) => {
    e.preventDefault();
    if (!companyId) {
      toast.error("Seleccione una empresa.");
      return;
    }
    if (!selectedSupplierId) {
      toast.error("Seleccione un proveedor del maestro.");
      return;
    }
    const invalidLine = lines.some(
      (row) => !row.product_id || !row.description.trim() || Number(row.quantity) <= 0 || Number(row.unit_price) < 0,
    );
    if (invalidLine) {
      toast.error("Revise las líneas: seleccione producto del maestro, detalle, cantidad y valor neto válidos.");
      return;
    }
    createMutation.mutate();
  };

  const fmt = (n) =>
    new Intl.NumberFormat("es-CL", {
      minimumFractionDigits: 0,
      maximumFractionDigits: 2,
    }).format(n);

  return (
    <div className="p-4 lg:p-8 space-y-8">
      <div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
        <div>
          <h1 className="text-3xl font-bold text-gradient">Emitir orden de compra</h1>
          <p className="text-gray-600 mt-1">
            {selectedCompany?.name ?? "Empresa"} • Libro OC — cabecera, detalle y totales.
          </p>
        </div>
        <Button
          type="button"
          variant="outline"
          className="shrink-0 border-blue-200 text-blue-700 hover:bg-blue-50"
          onClick={() => router.push(createPanelPageUrl("oc/book/pending-orders"))}
        >
          <ArrowLeft className="h-4 w-4 mr-2" />
          Volver
        </Button>
      </div>

      {!companyId ? (
        <p className="text-sm text-amber-800 bg-amber-50 border border-amber-200 rounded-lg p-3 max-w-3xl">
          Seleccione una empresa para registrar la orden en el libro OC.
        </p>
      ) : null}

      <form onSubmit={handleSubmit} className="space-y-6">
        <Card className="glass-card border-white/20">
          <CardHeader>
            <CardTitle>Nueva orden de compra</CardTitle>
          </CardHeader>
          <CardContent className="space-y-8">
            <div className="space-y-4">
              <p className="text-sm font-semibold text-slate-900 border-b border-slate-200 pb-2">Proveedor</p>
              <div className="grid grid-cols-2 gap-4">
                <div className="col-span-2">
                  <Label>
                    Proveedor <span className="text-red-600">*</span>
                  </Label>
                  <Popover open={supplierOpen} onOpenChange={setSupplierOpen}>
                    <PopoverTrigger asChild>
                      <Button
                        type="button"
                        variant="outline"
                        role="combobox"
                        aria-expanded={supplierOpen}
                        className="w-full justify-between font-normal"
                        disabled={!companyId || suppliersQuery.isLoading}
                      >
                        <span className="truncate text-left">
                          {selectedSupplier
                            ? `${selectedSupplier.rut} — ${selectedSupplier.business_name}`
                            : "Seleccionar proveedor..."}
                        </span>
                        <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
                      </Button>
                    </PopoverTrigger>
                    <PopoverContent className="w-[var(--radix-popover-trigger-width)] p-0" align="start">
                      <Command>
                        <CommandInput placeholder="Escriba para filtrar..." className="h-9" />
                        <CommandList>
                          <CommandEmpty>
                            {suppliersQuery.isLoading ? "Cargando..." : "Sin coincidencias."}
                          </CommandEmpty>
                          <CommandGroup>
                            {(suppliersQuery.data ?? []).map((s) => (
                              <CommandItem
                                key={String(s.id)}
                                value={`${String(s.rut)} ${String(s.business_name)} ${String(s.trade_name ?? "")}`}
                                onSelect={() => pickSupplier(s)}
                              >
                                <Check
                                  className={cn(
                                    "mr-2 h-4 w-4",
                                    String(selectedSupplierId) === String(s.id) ? "opacity-100" : "opacity-0",
                                  )}
                                />
                                <span className="truncate">
                                  {s.rut} — {s.business_name}
                                  {s.trade_name ? ` (${s.trade_name})` : ""}
                                </span>
                              </CommandItem>
                            ))}
                          </CommandGroup>
                        </CommandList>
                      </Command>
                    </PopoverContent>
                  </Popover>
                </div>
                {selectedSupplierId ? (
                  <div className="col-span-2">
                    <Button
                      type="button"
                      variant="ghost"
                      size="sm"
                      className="h-8 px-0 text-slate-600"
                      onClick={() => {
                        userChosePaymentNoneRef.current = false;
                        setSelectedSupplierId("");
                        setPaymentMethodId(PAYMENT_METHOD_NONE);
                      }}
                    >
                      Quitar selección
                    </Button>
                  </div>
                ) : null}
                {companyId && !suppliersQuery.isLoading && (suppliersQuery.data ?? []).length === 0 ? (
                  <p className="col-span-2 text-xs text-amber-700">
                    No hay proveedores registrados.{" "}
                    <Link href={createPanelPageUrl("suppliers")} className="underline font-medium text-amber-900">
                      Ir al maestro de proveedores
                    </Link>
                  </p>
                ) : null}
                {selectedSupplier ? (
                  <div className="col-span-2 rounded-lg border border-slate-200 p-3 text-sm space-y-2">
                    <p className="text-xs font-medium text-slate-500">Datos del maestro (solo lectura)</p>
                    <div className="grid sm:grid-cols-2 gap-x-4 gap-y-1 text-slate-700">
                      <div>
                        <span className="text-gray-500">RUT:</span> {selectedSupplier.rut}
                      </div>
                      <div>
                        <span className="text-gray-500">Razón social:</span> {selectedSupplier.business_name}
                      </div>
                      {selectedSupplier.trade_name ? (
                        <div>
                          <span className="text-gray-500">Fantasía:</span> {selectedSupplier.trade_name}
                        </div>
                      ) : null}
                      {selectedSupplier.giro ? (
                        <div>
                          <span className="text-gray-500">Giro:</span> {selectedSupplier.giro}
                        </div>
                      ) : null}
                      {selectedSupplier.phone ? (
                        <div>
                          <span className="text-gray-500">Tel.:</span> {selectedSupplier.phone}
                        </div>
                      ) : null}
                      {selectedSupplier.email ? (
                        <div>
                          <span className="text-gray-500">Email:</span> {selectedSupplier.email}
                        </div>
                      ) : null}
                      {selectedSupplier.address ? (
                        <div className="sm:col-span-2">
                          <span className="text-gray-500">Dirección:</span> {selectedSupplier.address}
                        </div>
                      ) : null}
                      <div className="sm:col-span-2">
                        <span className="text-gray-500">Forma de pago frecuente :</span>{" "}
                        {selectedSupplier.payment_terms && String(selectedSupplier.payment_terms).trim() !== ""
                          ? selectedSupplier.payment_terms
                          : "—"}
                      </div>
                    </div>
                  </div>
                ) : null}
              </div>
            </div>

            <div className="space-y-4">
              <p className="text-sm font-semibold text-slate-900 border-b border-slate-200 pb-2">Cabecera del documento</p>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label>Fecha emisión</Label>
                  <Input type="date" value={emissionDate} onChange={(e) => setEmissionDate(e.target.value)} />
                </div>
                <div>
                  <Label>Forma de pago</Label>
                  <Select
                    value={paymentMethodId}
                    onValueChange={(v) => {
                      userChosePaymentNoneRef.current = v === PAYMENT_METHOD_NONE;
                      setPaymentMethodId(v);
                    }}
                    disabled={!companyId || paymentMethodsQuery.isLoading}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="Seleccione del maestro de formas de pago" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value={PAYMENT_METHOD_NONE}>Sin seleccionar</SelectItem>
                      {(paymentMethodsQuery.data ?? [])
                        .filter((m) => m.id !== undefined && m.id !== null && String(m.id) !== "")
                        .map((m) => (
                          <SelectItem key={String(m.id)} value={String(m.id)}>
                            {String(m.name ?? "—")}
                            {m.code ? ` · ${m.code}` : ""}
                          </SelectItem>
                        ))}
                    </SelectContent>
                  </Select>
                </div>
                <div>
                  <Label>Clasificación de compra</Label>
                  <Input value={purchaseClassification} onChange={(e) => setPurchaseClassification(e.target.value)} />
                </div>
                <div>
                  <Label>Centro de costo</Label>
                  <Input value={costCenter} onChange={(e) => setCostCenter(e.target.value)} />
                </div>
                <div>
                  <Label>Solicitado por</Label>
                  <Input value={requestedBy} onChange={(e) => setRequestedBy(e.target.value)} />
                </div>
                <div>
                  <Label>Ejecutado por</Label>
                  <Input className="text-slate-600" value={executedPreview} readOnly />
                </div>
                <div>
                  <Label>N° cotización autoriz.</Label>
                  <Input value={quotationAuth} onChange={(e) => setQuotationAuth(e.target.value)} />
                </div>
                <div>
                  <Label>Lugar de entrega</Label>
                  <Input value={deliveryPlace} onChange={(e) => setDeliveryPlace(e.target.value)} />
                </div>
                <div>
                  <Label>Validez (días)</Label>
                  <Input type="number" min={0} value={validityDays} onChange={(e) => setValidityDays(e.target.value)} />
                </div>
                <div>
                  <Label>Entrega / notas</Label>
                  <Input value={deliveryNotes} onChange={(e) => setDeliveryNotes(e.target.value)} />
                </div>
                <div className="col-span-2">
                  <Label>Contacto</Label>
                  <Input value={contactName} onChange={(e) => setContactName(e.target.value)} />
                </div>
              </div>
            </div>

            <div className="space-y-4">
              <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between border-b border-slate-200 pb-3">
                <div>
                  <h3 className="text-sm font-semibold text-slate-900">Líneas de detalle</h3>
                  <p className="text-xs text-slate-500 mt-1">
                    Seleccione productos del maestro (insumos y productos finales) para autocompletar código, detalle y UM.
                  </p>
                  {companyId && !productsQuery.isLoading && (productsQuery.data ?? []).length === 0 ? (
                    <p className="text-xs text-amber-700 mt-1">No hay productos activos (insumo/producto final) en el maestro.</p>
                  ) : null}
                </div>
                <Button
                  type="button"
                  className="bg-gradient-to-r from-blue-500 to-blue-600 hover:from-blue-600 hover:to-blue-700 shrink-0"
                  onClick={addLine}
                  disabled={lines.length >= MAX_LINES}
                >
                  <Plus className="h-4 w-4 mr-2" />
                  Agregar línea
                </Button>
              </div>
              <div className="overflow-auto rounded-lg border border-slate-200 bg-white/60 shadow-sm">
                <table className="w-full min-w-[920px]">
                  <thead className="bg-slate-50/90">
                    <tr>
                      <th className="p-3 text-left text-xs font-semibold text-slate-600 w-[280px]">Producto</th>
                      <th className="p-3 text-right text-xs font-semibold text-slate-600 w-24">Cant.</th>
                      <th className="p-3 text-left text-xs font-semibold text-slate-600 w-20">UM</th>
                      <th className="p-3 text-right text-xs font-semibold text-slate-600 w-28">Valor neto</th>
                      <th className="p-3 text-left text-xs font-semibold text-slate-600 w-32">Tipo dcto.</th>
                      <th className="p-3 text-right text-xs font-semibold text-slate-600 w-28">Valor dcto.</th>
                      <th className="p-3 text-right text-xs font-semibold text-slate-600 w-28">Subtotal</th>
                      <th className="p-3 w-12" aria-hidden />
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-slate-100">
                    {lines.map((row) => (
                      <tr key={row.key} className="hover:bg-slate-50/70 transition-colors">
                        <td className="p-3 align-top">
                          <Popover
                            open={Boolean(lineProductOpen[row.key])}
                            onOpenChange={(open) => setLineProductOpen((prev) => ({ ...prev, [row.key]: open }))}
                          >
                            <PopoverTrigger asChild>
                              <Button
                                type="button"
                                variant="outline"
                                role="combobox"
                                aria-expanded={Boolean(lineProductOpen[row.key])}
                                className="h-9 w-full justify-between font-normal"
                                disabled={!companyId || productsQuery.isLoading}
                              >
                                <span className="truncate text-left">
                                  {row.product_id
                                    ? (() => {
                                        const selected = (productsQuery.data ?? []).find(
                                          (p) => String(p.id ?? "") === String(row.product_id),
                                        );
                                        return selected
                                          ? `${String(selected.sku ?? "SIN-SKU")} — ${String(selected.name ?? "Producto")}`
                                          : "Producto seleccionado";
                                      })()
                                    : "Seleccionar producto..."}
                                </span>
                                <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
                              </Button>
                            </PopoverTrigger>
                            <PopoverContent className="w-[var(--radix-popover-trigger-width)] p-0" align="start">
                              <Command>
                                <CommandInput placeholder="Buscar por SKU o nombre..." className="h-9" />
                                <CommandList>
                                  <CommandEmpty>
                                    {productsQuery.isLoading ? "Cargando productos..." : "Sin coincidencias."}
                                  </CommandEmpty>
                                  <CommandGroup>
                                    {(productsQuery.data ?? []).map((p) => (
                                      <CommandItem
                                        key={String(p.id)}
                                        value={`${String(p.sku ?? "")} ${String(p.name ?? "")} ${String(p.type ?? "")}`}
                                        onSelect={() => pickLineProduct(row.key, String(p.id))}
                                      >
                                        <Check
                                          className={cn(
                                            "mr-2 h-4 w-4",
                                            String(row.product_id) === String(p.id) ? "opacity-100" : "opacity-0",
                                          )}
                                        />
                                        <span className="truncate">
                                          {String(p.sku ?? "SIN-SKU")} — {String(p.name ?? "Producto")}
                                        </span>
                                      </CommandItem>
                                    ))}
                                  </CommandGroup>
                                </CommandList>
                              </Command>
                            </PopoverContent>
                          </Popover>
                        </td>
                        <td className="p-3 align-top">
                          <Input
                            className="h-9 text-sm text-right bg-white"
                            type="number"
                            min="0"
                            step="0.0001"
                            value={row.quantity}
                            onChange={(e) => updateLine(row.key, "quantity", e.target.value)}
                          />
                        </td>
                        <td className="p-3 align-top">
                          <Input
                            className="h-9 text-sm bg-white"
                            value={row.unit_measure}
                            onChange={(e) => updateLine(row.key, "unit_measure", e.target.value)}
                          />
                        </td>
                        <td className="p-3 align-top">
                          <Input
                            className="h-9 text-sm text-right bg-white"
                            type="number"
                            min="0"
                            step="1"
                            value={row.unit_price}
                            onChange={(e) => updateLine(row.key, "unit_price", e.target.value)}
                          />
                        </td>
                        <td className="p-3 align-top">
                          <Select value={row.discount_type} onValueChange={(v) => updateLine(row.key, "discount_type", v)}>
                            <SelectTrigger className="h-9 text-sm bg-white">
                              <SelectValue />
                            </SelectTrigger>
                            <SelectContent>
                              <SelectItem value="none">Sin dcto.</SelectItem>
                              <SelectItem value="percent">%</SelectItem>
                              <SelectItem value="amount">Monto</SelectItem>
                            </SelectContent>
                          </Select>
                        </td>
                        <td className="p-3 align-top">
                          <Input
                            className="h-9 text-sm text-right bg-white"
                            type="number"
                            min="0"
                            step="0.01"
                            value={row.discount_value}
                            onChange={(e) => updateLine(row.key, "discount_value", e.target.value)}
                          />
                        </td>
                        <td className="p-3 align-top text-right text-sm font-semibold text-slate-900 tabular-nums">
                          ${fmt(lineNetSubtotal(row.quantity, row.unit_price, row.discount_type, row.discount_value))}
                        </td>
                        <td className="p-3 align-top">
                          <Button
                            type="button"
                            variant="ghost"
                            size="icon"
                            className="text-slate-500 hover:text-red-600 hover:bg-red-50"
                            onClick={() => removeLine(row.key)}
                            aria-label="Eliminar línea"
                          >
                            <Trash2 className="h-4 w-4" />
                          </Button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>

            <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
              <div className="lg:col-span-2 space-y-4">
                <p className="text-sm font-semibold text-slate-900 border-b border-slate-200 pb-2">Totales y observaciones</p>
                <div>
                  <Label>Observación</Label>
                  <Textarea className="resize-none" value={observations} onChange={(e) => setObservations(e.target.value)} rows={4} />
                </div>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label>Descuento global (tipo)</Label>
                    <Select value={globalDiscountType} onValueChange={setGlobalDiscountType}>
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="none">Sin descuento</SelectItem>
                        <SelectItem value="percent">Porcentaje</SelectItem>
                        <SelectItem value="amount">Monto</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                  <div>
                    <Label>Descuento global</Label>
                    <Input type="number" min="0" step="0.01" value={globalDiscountValue} onChange={(e) => setGlobalDiscountValue(e.target.value)} />
                  </div>
                </div>
              </div>

              <div className="rounded-lg border border-slate-200 bg-slate-50/40 p-4 space-y-3 h-fit">
                <p className="text-sm font-semibold text-slate-900 border-b border-slate-200 pb-2">Resumen del documento</p>
                <div className="grid gap-3 text-sm">
                  <div className="flex justify-between gap-4">
                    <span className="text-gray-600">Subtotal ítems</span>
                    <span className="font-semibold text-slate-800 tabular-nums">${fmt(totalsPreview.subtotal)}</span>
                  </div>
                  <div className="flex justify-between gap-4">
                    <span className="text-gray-600">Descuento líneas</span>
                    <span className="font-semibold text-slate-800 tabular-nums">${fmt(totalsPreview.linesDisc)}</span>
                  </div>
                  <div className="flex justify-between gap-4">
                    <span className="text-gray-600">Descuento global</span>
                    <span className="font-semibold text-slate-800 tabular-nums">${fmt(totalsPreview.globalDiscAmt)}</span>
                  </div>
                  <div className="flex justify-between gap-4">
                    <span className="text-gray-600">Total afecto (neto)</span>
                    <span className="font-semibold text-slate-800 tabular-nums">${fmt(totalsPreview.taxable)}</span>
                  </div>
                  <div className="flex justify-between gap-4">
                    <span className="text-gray-600">IVA ({taxRate}%)</span>
                    <span className="font-semibold text-slate-800 tabular-nums">${fmt(totalsPreview.tax)}</span>
                  </div>
                  <div className="flex justify-between gap-4 pt-2 border-t border-slate-200 text-base">
                    <span className="font-semibold text-slate-800">Total</span>
                    <span className="font-bold text-slate-900 tabular-nums">${fmt(totalsPreview.total)}</span>
                  </div>
                </div>
              </div>
            </div>

            <div className="flex justify-end gap-3 pt-2">
              <Button type="button" variant="outline" onClick={() => router.push(createPanelPageUrl("oc/book/pending-orders"))}>
                Cancelar
              </Button>
              <Button
                type="submit"
                className="bg-gradient-to-r from-blue-500 to-blue-600 hover:from-blue-600 hover:to-blue-700 min-w-[180px]"
                disabled={createMutation.isPending || !companyId}
              >
                {createMutation.isPending ? "Guardando…" : "Ingresar orden"}
              </Button>
            </div>
          </CardContent>
        </Card>
      </form>
    </div>
  );
}
