"use client";

import React, { useState, useCallback, useEffect, useMemo, useRef } from "react";
import { useRouter } from "next/navigation";
import { usePopCompanyPath } from "@/hooks/usePopCompanyPath";
import { SupplierModal, type Supplier, matchChosung } from "../inbound/SupplierModal";
import { SimpleKeypadModal } from "../common/SimpleKeypadModal";
import { BarcodeScanModal } from "../common/BarcodeScanModal";
import type { CartItemWithId } from "../common/useCartSync";
import { COLOR_MAP } from "../common/theme";

/* ------------------------------------------------------------------ */
/* Types                                                               */
/* ------------------------------------------------------------------ */

interface OutboundOrder {
  id: string;
  reference_no: string;
  order_date: string;
  customer_code: string;
  customer_name: string;
  item_code: string;
  item_name: string;
  spec: string;
  material: string;
  order_qty: number;
  shipped_qty: number;
  remain_qty: number;
  unit_price: number;
  status: string;
  due_date: string;
  source_table: string;
  inspection_type: "self" | "request" | null;
  image: string | null;
}

/* ------------------------------------------------------------------ */
/* Component                                                           */
/* ------------------------------------------------------------------ */

interface SubcontractorOutboundProps {
  cart: import("../common/useCartSync").UseCartSyncReturn;
  onCartClick: () => void;
  saving: boolean;
  outboundType: string;
  sourceTable: string;
}

const STORAGE_KEY = "pop_customer_subcontractor";

export function SubcontractorOutbound({ cart, onCartClick, saving, outboundType, sourceTable }: SubcontractorOutboundProps) {
  const router = useRouter();
  const companyPath = usePopCompanyPath();

  const [selectedCustomer, setSelectedCustomer] = useState<Supplier | null>(null);
  const [customerModalOpen, setCustomerModalOpen] = useState(false);
  const [orders, setOrders] = useState<OutboundOrder[]>([]);
  const [loading, setLoading] = useState(false);
  const [fetchError, setFetchError] = useState<string | null>(null);
  const [keyword, setKeyword] = useState("");

  const [numpadOpen, setNumpadOpen] = useState(false);
  const [numpadTarget, setNumpadTarget] = useState<OutboundOrder | null>(null);

  const [customerScanOpen, setCustomerScanOpen] = useState(false);
  const [itemScanOpen, setItemScanOpen] = useState(false);

  const [customerSearchText, setCustomerSearchText] = useState("");
  const [customerDropdownOpen, setCustomerDropdownOpen] = useState(false);
  const [allCustomers, setAllCustomers] = useState<Supplier[]>([]);
  const customerInputRef = useRef<HTMLInputElement>(null);
  const customerDropdownRef = useRef<HTMLDivElement>(null);

  /* Fetch all customers
   * TODO: API 연결 — 외주출고용 거래처 조회 엔드포인트 확정 후 연동
   */
  const fetchAllCustomers = useCallback(async () => {
    setAllCustomers([]);
  }, []);

  useEffect(() => { fetchAllCustomers(); }, [fetchAllCustomers]);
  /* sessionStorage 복원 — 장바구니 갔다 돌아올 때 거래처 선택 유지 */
  useEffect(() => {
    const saved = sessionStorage.getItem(STORAGE_KEY);
    if (saved) {
      try {
        const parsed = JSON.parse(saved);
        setSelectedCustomer(parsed);
      } catch {}
    }
  }, []);

  /* 거래처 선택 래퍼 — sessionStorage에도 저장/제거 */
  const selectCustomer = (s: Supplier | null) => {
    setSelectedCustomer(s);
    if (s) {
      sessionStorage.setItem(STORAGE_KEY, JSON.stringify(s));
    } else {
      sessionStorage.removeItem(STORAGE_KEY);
    }
  };

  const filteredCustomers = useMemo(() => {
    if (!customerSearchText.trim()) return [];
    return allCustomers.filter((s) => matchChosung(s.customer_name, customerSearchText.trim()));
  }, [allCustomers, customerSearchText]);

  useEffect(() => {
    const handleClickOutside = (e: MouseEvent) => {
      if (
        customerDropdownRef.current &&
        !customerDropdownRef.current.contains(e.target as Node) &&
        customerInputRef.current &&
        !customerInputRef.current.contains(e.target as Node)
      ) {
        setCustomerDropdownOpen(false);
      }
    };
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  /* Fetch outbound orders
   * TODO: API 연결 — 외주출고 대상 품목 조회 엔드포인트 확정 후 연동
   */
  const fetchOrders = useCallback(async (_searchKeyword?: string) => {
    setLoading(true);
    setFetchError(null);
    try {
      setOrders([]);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchOrders();
  }, [fetchOrders]);

  const filteredOrders = selectedCustomer
    ? orders.filter((o) =>
        o.customer_code === selectedCustomer.customer_code ||
        o.customer_name === selectedCustomer.customer_name
      )
    : orders;

  const displayOrders = keyword
    ? filteredOrders.filter((o) =>
        o.item_name.toLowerCase().includes(keyword.toLowerCase()) ||
        o.item_code.toLowerCase().includes(keyword.toLowerCase()) ||
        o.reference_no.toLowerCase().includes(keyword.toLowerCase())
      )
    : filteredOrders;

  const openNumpad = (order: OutboundOrder) => {
    setNumpadTarget(order);
    setNumpadOpen(true);
  };

  const handleNumpadConfirm = (qty: number) => {
    if (!numpadTarget) return;
    const order = numpadTarget;
    if (cart.isItemInCart(order.id)) return;

    if (cart.cartItems.length > 0) {
      const existingCustomer = String(cart.cartItems[0].row.customer_code || "");
      if (existingCustomer && existingCustomer !== order.customer_code) {
        alert("다른 거래처의 품목이 이미 장바구니에 있습니다.\n같은 거래처의 품목만 담을 수 있습니다.");
        setNumpadTarget(null);
        return;
      }
    }

    const finalQty = Math.min(qty, order.remain_qty);

    cart.addItem(
      {
        row: {
          id: order.id,
          item_code: order.item_code,
          item_name: order.item_name,
          customer_code: order.customer_code,
          customer_name: order.customer_name,
          reference_no: order.reference_no,
          unit_price: order.unit_price || 0,
          spec: order.spec || "",
          material: order.material || "",
          order_qty: order.order_qty,
          remain_qty: order.remain_qty,
          order_date: order.order_date || "",
          inspection_type: order.inspection_type,
          source_table: order.source_table,
          image: order.image || null,
          outbound_type: outboundType,
        },
        quantity: finalQty,
      },
      order.id,
      sourceTable,
    );
    setNumpadTarget(null);
    setTimeout(() => cart.saveToDb().catch(() => {}), 300);
  };

  const handleRemoveFromCart = (id: string) => {
    cart.removeItem(id);
    setTimeout(() => cart.saveToDb().catch(() => {}), 300);
  };

  const handleSearch = () => {
    fetchOrders(keyword || undefined);
  };

  const isInCart = (id: string) => cart.isItemInCart(id);
  const getCartItem = (id: string): CartItemWithId | undefined => cart.getCartItem(id);

  return (
    <div className="flex flex-col gap-4">
      {/* ===== Header ===== */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <button
            onClick={() => router.push(companyPath("/pop/outbound"))}
            className="w-10 h-10 rounded-xl bg-white border border-gray-200 flex items-center justify-center text-gray-500 hover:bg-gray-50 active:scale-95 transition-all"
          >
            <svg className="w-5 h-5" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" d="M15.75 19.5L8.25 12l7.5-7.5" />
            </svg>
          </button>
          <div>
            <h1 className="text-xl sm:text-2xl font-bold text-gray-900 tracking-tight">외주출고</h1>
            <p className="text-xs text-gray-400 mt-0.5">외주 품목을 선택하여 출고하세요</p>
          </div>
        </div>

        <button
          onClick={onCartClick}
          disabled={saving}
          className={`relative min-w-[144px] min-h-[48px] px-4 rounded-xl flex items-center justify-center gap-2 text-white font-semibold text-sm active:scale-95 transition-all shrink-0 disabled:opacity-60 ${COLOR_MAP.purple.buttonBg} ${COLOR_MAP.purple.buttonBgHover} shadow-[0_4px_12px_rgba(109,40,217,0.3)]`}
        >
          {saving ? (
            <svg className="animate-spin w-6 h-6" fill="none" viewBox="0 0 24 24">
              <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
              <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
            </svg>
          ) : (
            <svg className="w-6 h-6" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" d="M2.25 3h1.386c.51 0 .955.343 1.087.835l.383 1.437M7.5 14.25a3 3 0 00-3 3h15.75m-12.75-3h11.218c1.121 0 2.002-.881 2.002-2.003V6.75m-14.22 0h14.22" />
            </svg>
          )}
          <span>장바구니</span>
          {cart.cartCount > 0 && (
            <span
              className={`absolute -top-1 -right-1 min-w-[20px] h-5 px-1 rounded-full text-[10px] font-bold text-white flex items-center justify-center ${
                cart.isDirty ? "bg-orange-500 animate-pulse" : "bg-red-500"
              }`}
            >
              {cart.cartCount}
            </span>
          )}
        </button>
      </div>

      {/* ===== Search area ===== */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-3">
        <div className="bg-white rounded-xl border border-gray-100 shadow-sm p-3">
          <div className="flex items-center justify-between mb-1.5">
            <span className="text-xs font-semibold text-gray-500">거래처</span>
            {selectedCustomer && (
              <span className="text-[11px] font-medium text-purple-600 bg-purple-50 px-2 py-0.5 rounded-full">
                {selectedCustomer.customer_name}
              </span>
            )}
          </div>
          <div className="relative flex items-center gap-2">
            <button
              onClick={() => setCustomerModalOpen(true)}
              className={`flex-1 px-3 py-2.5 border rounded-lg text-sm text-left outline-none transition-all ${
                selectedCustomer
                  ? "bg-purple-50/50 border-purple-200 text-purple-800 font-medium"
                  : "border-gray-200 text-gray-500 hover:border-gray-300 hover:bg-gray-50"
              }`}
            >
              {selectedCustomer ? selectedCustomer.customer_name : "거래처를 선택하세요"}
            </button>
            <button
              onClick={() => setCustomerScanOpen(true)}
              className={`min-w-[48px] min-h-[48px] rounded-xl flex items-center justify-center text-white active:scale-95 transition-all shrink-0 ${COLOR_MAP.purple.buttonBg} ${COLOR_MAP.purple.buttonBgHover} shadow-[0_4px_12px_rgba(109,40,217,0.3)]`}
            >
              <svg className="w-6 h-6" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2}>
                <path strokeLinecap="round" strokeLinejoin="round" d="M3.75 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 013.75 9.375v-4.5zM3.75 14.625c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5a1.125 1.125 0 01-1.125-1.125v-4.5zM13.5 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 0113.5 9.375v-4.5z" />
                <path strokeLinecap="round" strokeLinejoin="round" d="M13.5 14.625v2.25h2.25m-2.25 2.25h4.5v-4.5" />
              </svg>
            </button>
            {selectedCustomer && (
              <button
                onClick={() => { selectCustomer(null); setCustomerSearchText(""); }}
                className="w-10 h-10 rounded-lg bg-gray-100 flex items-center justify-center text-gray-400 hover:bg-gray-200 transition-colors shrink-0"
              >
                <svg className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>
            )}
          </div>
        </div>

        <div className="bg-white rounded-xl border border-gray-100 shadow-sm p-3">
          <div className="flex items-center justify-between mb-1.5">
            <span className="text-xs font-semibold text-gray-500">출하 품목</span>
            <span className="text-[11px] font-semibold text-white bg-purple-500 px-2 py-0.5 rounded-full min-w-[24px] text-center">
              {selectedCustomer ? displayOrders.length : 0}
            </span>
          </div>
          <div className="flex items-center gap-2">
            <input
              type="text"
              value={keyword}
              onChange={(e) => setKeyword(e.target.value)}
              onKeyDown={(e) => { if (e.key === "Enter") handleSearch(); }}
              placeholder="품목명, 품목코드, 주문번호 검색..."
              disabled={!selectedCustomer}
              className={`flex-1 px-3 py-2.5 border border-gray-200 rounded-lg text-sm outline-none transition-all ${
                selectedCustomer
                  ? "focus:border-purple-400 focus:ring-2 focus:ring-purple-100"
                  : "bg-gray-50 text-gray-400 cursor-not-allowed"
              }`}
            />
            <button
              onClick={() => setItemScanOpen(true)}
              disabled={!selectedCustomer}
              className={`min-w-[48px] min-h-[48px] rounded-xl flex items-center justify-center text-white active:scale-95 transition-all shrink-0 ${COLOR_MAP.purple.buttonBg} ${COLOR_MAP.purple.buttonBgHover} ${
                !selectedCustomer ? "opacity-40 cursor-not-allowed" : "shadow-[0_4px_12px_rgba(109,40,217,0.3)]"
              }`}
            >
              <svg className="w-6 h-6" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2}>
                <path strokeLinecap="round" strokeLinejoin="round" d="M3.75 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 013.75 9.375v-4.5zM3.75 14.625c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5a1.125 1.125 0 01-1.125-1.125v-4.5zM13.5 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 0113.5 9.375v-4.5z" />
                <path strokeLinecap="round" strokeLinejoin="round" d="M13.5 14.625v2.25h2.25m-2.25 2.25h4.5v-4.5" />
              </svg>
            </button>
          </div>
        </div>
      </div>

      {/* ===== Order items ===== */}
      <div className="bg-white rounded-xl border border-gray-100 shadow-sm p-3">
        <div className="flex items-center justify-between mb-2 pb-2 border-b border-gray-50">
          <span className="text-xs font-semibold text-gray-500">출하 품목 목록</span>
          <span className="text-[11px] text-gray-400">
            {selectedCustomer ? `${displayOrders.length}건` : "-"}
          </span>
        </div>

        {!selectedCustomer ? (
          <div className="flex flex-col items-center justify-center py-16 text-gray-400">
            <svg className="w-16 h-16 mb-4 opacity-20" fill="none" stroke="currentColor" strokeWidth={1} viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" d="M18 18.72a9.094 9.094 0 003.741-.479 3 3 0 00-4.682-2.72m.94 3.198l.001.031c0 .225-.012.447-.037.666A11.944 11.944 0 0112 21c-2.17 0-4.207-.576-5.963-1.584A6.062 6.062 0 016 18.719m12 0a5.971 5.971 0 00-.941-3.197m0 0A5.995 5.995 0 0012 12.75a5.995 5.995 0 00-5.058 2.772m0 0a3 3 0 00-4.681 2.72 8.986 8.986 0 003.74.477m.94-3.197a5.971 5.971 0 00-.94 3.197M15 6.75a3 3 0 11-6 0 3 3 0 016 0zm6 3a2.25 2.25 0 11-4.5 0 2.25 2.25 0 014.5 0zm-13.5 0a2.25 2.25 0 11-4.5 0 2.25 2.25 0 014.5 0z" />
            </svg>
            <p className="text-sm font-medium text-gray-500 mb-1">거래처를 먼저 선택하세요</p>
            <p className="text-xs text-gray-400">거래처를 선택하면 해당 거래처의 출하 품목이 표시됩니다</p>
          </div>
        ) : loading ? (
          <div className="flex items-center justify-center py-12 text-sm text-gray-400">
            <svg className="animate-spin w-5 h-5 mr-2 text-purple-500" fill="none" viewBox="0 0 24 24">
              <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
              <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
            </svg>
            불러오는 중...
          </div>
        ) : displayOrders.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-12 text-gray-400">
            <svg className="w-12 h-12 mb-3 opacity-30" fill="none" stroke="currentColor" strokeWidth={1} viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4" />
            </svg>
            <p className="text-sm">
              {fetchError ? fetchError : selectedCustomer ? "해당 거래처의 출하 품목이 없습니다" : "거래처를 선택하거나 품목을 검색하세요"}
            </p>
            {fetchError && (
              <button
                onClick={() => fetchOrders()}
                className="mt-3 px-4 py-2 text-xs font-medium text-white bg-purple-500 rounded-lg hover:bg-purple-600 active:scale-95 transition-all"
              >
                다시 시도
              </button>
            )}
          </div>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-3">
            {displayOrders.map((order) => {
              const inCart = isInCart(order.id);
              const cartItem = getCartItem(order.id);

              return (
                <div
                  key={order.id}
                  className={`relative rounded-xl border p-3 transition-all ${
                    inCart
                      ? "border-green-300 bg-gradient-to-br from-green-50/80 to-emerald-50/50"
                      : "border-gray-200 bg-white hover:border-purple-300"
                  }`}
                >
                  {inCart && (
                    <div className="absolute top-0 left-0 w-[3px] h-full bg-green-500 rounded-l-xl" />
                  )}

                  <div className="flex items-center gap-1.5 mb-2.5 pb-2 border-b border-gray-100">
                    <span className="text-[11px] text-gray-400 font-medium shrink-0">{order.item_code}</span>
                    <span className="text-[13px] font-semibold text-gray-900 flex-1 truncate">{order.item_name}</span>
                    {order.inspection_type === "self" && (
                      <span className="text-[9px] font-bold px-1.5 py-0.5 rounded bg-blue-100 text-blue-700 border border-blue-200 shrink-0 whitespace-nowrap">
                        검사 필수
                      </span>
                    )}
                    {order.inspection_type === "request" && (
                      <span className="text-[9px] font-bold px-1.5 py-0.5 rounded bg-amber-100 text-amber-700 border border-amber-200 shrink-0 whitespace-nowrap">
                        검사의뢰 선택
                      </span>
                    )}
                  </div>

                  <div className="flex gap-2.5">
                    <div className="w-[56px] h-[56px] min-w-[56px] bg-gray-50 border border-gray-200 rounded-lg flex items-center justify-center shrink-0 overflow-hidden">
                      {order.image ? (
                        <img src={order.image} alt={order.item_name} className="w-full h-full object-cover rounded-lg" />
                      ) : (
                        <span className="text-2xl text-gray-300">{"\uD83D\uDCE6"}</span>
                      )}
                    </div>

                    <div className="flex-1 min-w-0 flex flex-col gap-[3px]">
                      <div className="flex items-center gap-1.5 text-[11px]">
                        <span className="text-gray-400 min-w-[45px] shrink-0">주문일</span>
                        <span className="font-medium text-gray-700">{order.order_date}</span>
                      </div>
                      <div className="flex items-center gap-1.5 text-[11px]">
                        <span className="text-gray-400 min-w-[45px] shrink-0">주문번호</span>
                        <span className="font-medium text-gray-700 truncate">{order.reference_no}</span>
                      </div>
                      <div className="flex items-center gap-1.5 text-[11px]">
                        <span className="text-gray-400 min-w-[45px] shrink-0">출고수량</span>
                        <span className="font-medium text-gray-700">{order.order_qty.toLocaleString()}</span>
                      </div>
                      <div className="flex items-center gap-1.5 text-[11px]">
                        <span className="text-gray-400 min-w-[45px] shrink-0">미출고</span>
                        <span className="font-bold text-red-500">
                          {inCart
                            ? (order.remain_qty - (cartItem?.quantity ?? 0)).toLocaleString()
                            : order.remain_qty.toLocaleString()
                          }
                        </span>
                      </div>
                    </div>

                    <div className="flex flex-col gap-1.5 items-stretch min-w-[80px] shrink-0">
                      <button
                        onClick={() => { if (!inCart) openNumpad(order); }}
                        disabled={inCart}
                        className={`flex items-center justify-center gap-1 px-2.5 py-2 rounded-md border transition-all ${
                          inCart
                            ? "bg-gray-50 border-gray-200 cursor-default"
                            : "bg-purple-50 border-purple-200 hover:bg-purple-100 cursor-pointer active:scale-95"
                        }`}
                      >
                        <span className={`text-sm font-bold ${inCart ? "text-gray-400" : "text-purple-700"}`}
                          style={{ fontVariantNumeric: "tabular-nums" }}
                        >
                          {inCart
                            ? (cartItem?.quantity ?? order.remain_qty).toLocaleString()
                            : order.remain_qty.toLocaleString()
                          }
                        </span>
                        <span className="text-[10px] text-gray-400">EA</span>
                      </button>

                      {inCart ? (
                        <button
                          onClick={() => handleRemoveFromCart(order.id)}
                          className="flex items-center justify-center gap-1 px-2.5 py-2 rounded-md bg-red-500 text-white text-xs font-semibold hover:bg-red-600 active:scale-95 transition-all"
                        >
                          취소
                        </button>
                      ) : (
                        <button
                          onClick={() => openNumpad(order)}
                          className={`flex items-center justify-center gap-1 px-2.5 py-2 rounded-md text-white text-xs font-semibold active:scale-95 transition-all ${COLOR_MAP.purple.buttonBg} ${COLOR_MAP.purple.buttonBgHover}`}
                        >
                          <svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" d="M2.25 3h1.386c.51 0 .955.343 1.087.835l.383 1.437M7.5 14.25a3 3 0 00-3 3h15.75m-12.75-3h11.218c1.121 0 2.002-.881 2.002-2.003V6.75m-14.22 0h14.22" />
                          </svg>
                          담기
                        </button>
                      )}
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </div>

      {/* ===== Modals ===== */}
      <SupplierModal
        open={customerModalOpen}
        onClose={() => setCustomerModalOpen(false)}
        onSelect={(s) => selectCustomer(s)}
      />

      <SimpleKeypadModal
        open={numpadOpen}
        onClose={() => { setNumpadOpen(false); setNumpadTarget(null); }}
        onConfirm={handleNumpadConfirm}
        maxQty={numpadTarget?.remain_qty ?? 0}
        itemName={numpadTarget?.item_name ?? ""}
      />

      <BarcodeScanModal
        open={customerScanOpen}
        onOpenChange={setCustomerScanOpen}
        targetField="거래처"
        autoSubmit
        onScanSuccess={(barcode) => {
          setCustomerScanOpen(false);
          const match = allCustomers.find(
            (s) => s.customer_code === barcode || s.customer_name.includes(barcode)
          );
          if (match) {
            selectCustomer(match);
            setCustomerSearchText("");
          } else {
            setCustomerSearchText(barcode);
            setCustomerDropdownOpen(true);
          }
        }}
      />

      <BarcodeScanModal
        open={itemScanOpen}
        onOpenChange={setItemScanOpen}
        targetField="출하 품목"
        autoSubmit
        onScanSuccess={(barcode) => {
          setItemScanOpen(false);
          setKeyword(barcode);
          fetchOrders(barcode);
        }}
      />
    </div>
  );
}
