"use client";

import React, { useState, useEffect, useCallback } from "react";
import { useRouter } from "next/navigation";
import { usePopCompanyPath } from "@/hooks/usePopCompanyPath";
import { SupplierModal, type Supplier } from "../inbound/SupplierModal";
import {
  getOutboundList,
  updateOutbound,
  deleteOutbound,
  getOutboundWarehouses,
  type OutboundItem,
  type WarehouseOption,
} from "@/lib/api/outbound";

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

interface OutboundRecord extends OutboundItem {
  detail_id?: string;
  seq_no?: number;
  detail_outbound_type?: string;
  header_memo?: string;
  item_number?: string;
}

const STATUS_OPTIONS = ["출고완료", "부분출고", "대기"];
const OUTBOUND_TYPE_OPTIONS = [
  { value: "all", label: "전체" },
  { value: "판매출고", label: "판매출고" },
  { value: "생산출고", label: "생산출고" },
  { value: "외주출고", label: "외주출고" },
  { value: "사급출고", label: "사급출고" },
  { value: "반품출고", label: "반품출고" },
  { value: "기타출고", label: "기타출고" },
  { value: "재고이동", label: "재고이동" },
];

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

export function OutboundManage() {
  const router = useRouter();
  const companyPath = usePopCompanyPath();
  const today = new Date().toISOString().slice(0, 10);

  /* ── Filters ── */
  const [outboundDate, setOutboundDate] = useState(today);
  const [outboundType, setOutboundType] = useState("all");
  const [keyword, setKeyword] = useState("");
  const [selectedCustomer, setSelectedCustomer] = useState<Supplier | null>(
    null,
  );
  const [customerModalOpen, setCustomerModalOpen] = useState(false);

  /* ── Data ── */
  const [records, setRecords] = useState<OutboundRecord[]>([]);
  const [loading, setLoading] = useState(false);
  const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
  const [warehouses, setWarehouses] = useState<WarehouseOption[]>([]);

  /* ── Edit modal ── */
  const [editRecord, setEditRecord] = useState<OutboundRecord | null>(null);
  const [editForm, setEditForm] = useState<Record<string, any>>({});
  const [saving, setSaving] = useState(false);
  const [deleting, setDeleting] = useState(false);

  /* ── Helpers ── */
  const getRowKey = (r: OutboundRecord) => r.detail_id || r.id;

  /* ---------------------------------------------------------------- */
  /* Fetch                                                             */
  /* ---------------------------------------------------------------- */

  const fetchRecords = useCallback(async () => {
    setLoading(true);
    try {
      const params: Record<string, string> = {};
      if (outboundDate) {
        params.date_from = outboundDate;
        params.date_to = outboundDate;
      }
      if (outboundType !== "all") params.outbound_type = outboundType;
      if (keyword.trim()) params.search_keyword = keyword.trim();

      const res = await getOutboundList(params);
      if (res.success) {
        let data = res.data as unknown as OutboundRecord[];
        if (selectedCustomer?.customer_code) {
          data = data.filter(
            (r) => r.customer_code === selectedCustomer.customer_code,
          );
        }
        setRecords(data);
        setSelectedIds(new Set());
      }
    } catch (e) {
      console.error("출고 목록 조회 실패", e);
    } finally {
      setLoading(false);
    }
  }, [outboundDate, outboundType, keyword, selectedCustomer]);

  useEffect(() => {
    getOutboundWarehouses()
      .then((res) => {
        if (res.success) setWarehouses(res.data);
      })
      .catch(() => {});
  }, []);

  useEffect(() => {
    fetchRecords();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  /* ---------------------------------------------------------------- */
  /* Selection                                                         */
  /* ---------------------------------------------------------------- */

  const toggleSelect = (key: string) => {
    setSelectedIds((prev) => {
      const next = new Set(prev);
      if (next.has(key)) next.delete(key);
      else next.add(key);
      return next;
    });
  };

  const toggleSelectAll = () => {
    if (selectedIds.size === records.length) setSelectedIds(new Set());
    else setSelectedIds(new Set(records.map(getRowKey)));
  };

  /* ---------------------------------------------------------------- */
  /* Delete                                                            */
  /* ---------------------------------------------------------------- */

  const handleDelete = async () => {
    if (selectedIds.size === 0) return;

    const headerIds = new Set<string>();
    records.forEach((r) => {
      if (selectedIds.has(getRowKey(r))) headerIds.add(r.id);
    });

    if (
      !confirm(
        `선택한 ${headerIds.size}건의 출고를 삭제하시겠습니까?\n(재고가 롤백됩니다)`,
      )
    )
      return;

    setDeleting(true);
    try {
      for (const hid of headerIds) {
        await deleteOutbound(hid);
      }
      await fetchRecords();
    } catch (e: any) {
      alert(`삭제 실패: ${e?.message || "알 수 없는 오류"}`);
    } finally {
      setDeleting(false);
    }
  };

  /* ---------------------------------------------------------------- */
  /* Edit                                                              */
  /* ---------------------------------------------------------------- */

  const openEdit = (record: OutboundRecord) => {
    setEditRecord(record);
    setEditForm({
      outbound_date: record.outbound_date?.slice(0, 10) || today,
      outbound_qty: record.outbound_qty ?? 0,
      unit_price: record.unit_price ?? 0,
      total_amount: record.total_amount ?? 0,
      lot_number: record.lot_number || "",
      warehouse_code: record.warehouse_code || "",
      location_code: record.location_code || "",
      outbound_status: record.outbound_status || "출고완료",
      manager_id: record.manager_id || "",
      memo: record.memo || "",
    });
  };

  const handleEditFromSelection = () => {
    if (selectedIds.size !== 1) {
      alert("수정할 항목을 1건만 선택해주세요.");
      return;
    }
    const key = Array.from(selectedIds)[0];
    const rec = records.find((r) => getRowKey(r) === key);
    if (rec) openEdit(rec);
  };

  const updateField = (key: string, value: any) => {
    setEditForm((prev) => {
      const next = { ...prev, [key]: value };
      if (key === "outbound_qty" || key === "unit_price") {
        next.total_amount =
          Math.round(
            (Number(next.outbound_qty) || 0) *
              (Number(next.unit_price) || 0) *
              100,
          ) / 100;
      }
      return next;
    });
  };

  const handleSave = async () => {
    if (!editRecord) return;
    setSaving(true);
    try {
      const payload: Record<string, any> = { ...editForm };
      if (editRecord.detail_id) payload.detail_id = editRecord.detail_id;

      await updateOutbound(editRecord.id, payload as Partial<OutboundItem>);
      setEditRecord(null);
      await fetchRecords();
    } catch (e: any) {
      alert(`수정 실패: ${e?.message || "알 수 없는 오류"}`);
    } finally {
      setSaving(false);
    }
  };

  /* ---------------------------------------------------------------- */
  /* Render                                                            */
  /* ---------------------------------------------------------------- */

  return (
    <div className="flex flex-col gap-4">
      {/* ===== Header ===== */}
      <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>

      {/* ===== Search / Filter ===== */}
      <div className="bg-white rounded-xl border border-gray-100 shadow-sm p-3">
        <div className="grid grid-cols-2 lg:grid-cols-5 gap-3">
          {/* 출고일 */}
          <div>
            <label className="text-xs font-semibold text-gray-500 mb-1 block">
              출고일
            </label>
            <input
              type="date"
              value={outboundDate}
              onChange={(e) => setOutboundDate(e.target.value)}
              className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm outline-none focus:border-emerald-400 focus:ring-2 focus:ring-emerald-100"
            />
          </div>
          {/* 출고유형 */}
          <div>
            <label className="text-xs font-semibold text-gray-500 mb-1 block">
              출고유형
            </label>
            <select
              value={outboundType}
              onChange={(e) => setOutboundType(e.target.value)}
              className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm outline-none focus:border-emerald-400 focus:ring-2 focus:ring-emerald-100 bg-white"
            >
              {OUTBOUND_TYPE_OPTIONS.map((opt) => (
                <option key={opt.value} value={opt.value}>
                  {opt.label}
                </option>
              ))}
            </select>
          </div>
          {/* 거래처 */}
          <div>
            <label className="text-xs font-semibold text-gray-500 mb-1 block">
              거래처
            </label>
            <button
              onClick={() => setCustomerModalOpen(true)}
              className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm text-left outline-none focus:border-emerald-400 focus:ring-2 focus:ring-emerald-100 bg-white flex items-center justify-between"
            >
              <span
                className={
                  selectedCustomer
                    ? "text-gray-900 truncate"
                    : "text-gray-400"
                }
              >
                {selectedCustomer ? selectedCustomer.customer_name : "전체"}
              </span>
              {selectedCustomer ? (
                <span
                  onClick={(e) => {
                    e.stopPropagation();
                    setSelectedCustomer(null);
                  }}
                  className="text-gray-400 hover:text-gray-600 ml-1 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>
                </span>
              ) : (
                <svg
                  className="w-4 h-4 text-gray-400 shrink-0"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth={2}
                  viewBox="0 0 24 24"
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    d="M8.25 15L12 18.75 15.75 15m-7.5-6L12 5.25 15.75 9"
                  />
                </svg>
              )}
            </button>
          </div>
          {/* 검색어 + 검색버튼 */}
          <div className="col-span-2">
            <label className="text-xs font-semibold text-gray-500 mb-1 block">
              검색
            </label>
            <div className="flex items-center gap-2">
              <input
                type="text"
                value={keyword}
                onChange={(e) => setKeyword(e.target.value)}
                onKeyDown={(e) => {
                  if (e.key === "Enter") fetchRecords();
                }}
                placeholder="출고번호, 품목명, 거래처명..."
                className="flex-1 px-3 py-2 border border-gray-200 rounded-lg text-sm outline-none focus:border-emerald-400 focus:ring-2 focus:ring-emerald-100"
              />
              <button
                onClick={fetchRecords}
                disabled={loading}
                className="min-w-[48px] min-h-[40px] rounded-lg flex items-center justify-center text-white active:scale-95 transition-all disabled:opacity-50"
                style={{
                  background: "linear-gradient(to bottom, #34d399, #059669)",
                }}
              >
                {loading ? (
                  <svg
                    className="w-5 h-5 animate-spin"
                    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-5 h-5"
                    fill="none"
                    stroke="currentColor"
                    strokeWidth={2}
                    viewBox="0 0 24 24"
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      d="M21 21l-5.197-5.197m0 0A7.5 7.5 0 105.196 5.196a7.5 7.5 0 0010.607 10.607z"
                    />
                  </svg>
                )}
              </button>
            </div>
          </div>
        </div>
      </div>

      {/* ===== Action buttons ===== */}
      <div className="flex items-center justify-between">
        <span className="text-sm text-gray-500">
          {selectedIds.size > 0
            ? `${selectedIds.size}건 선택`
            : `총 ${records.length}건`}
        </span>
        <div className="flex items-center gap-2">
          <button
            disabled={selectedIds.size !== 1}
            onClick={handleEditFromSelection}
            className="px-4 py-2 rounded-lg text-sm font-semibold text-white active:scale-95 transition-all disabled:opacity-40 disabled:cursor-not-allowed"
            style={{
              background: "linear-gradient(to bottom, #34d399, #059669)",
            }}
          >
            수정
          </button>
          <button
            disabled={selectedIds.size === 0 || deleting}
            onClick={handleDelete}
            className="px-4 py-2 rounded-lg text-sm font-semibold text-white active:scale-95 transition-all disabled:opacity-40 disabled:cursor-not-allowed"
            style={{
              background: "linear-gradient(to bottom, #f87171, #dc2626)",
            }}
          >
            {deleting ? "삭제 중..." : "삭제"}
          </button>
        </div>
      </div>

      {/* ===== Record list ===== */}
      <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">
          <div className="flex items-center gap-2">
            <input
              type="checkbox"
              checked={
                records.length > 0 && selectedIds.size === records.length
              }
              onChange={toggleSelectAll}
              className="w-4 h-4 rounded border-gray-300 text-emerald-600 focus:ring-emerald-500"
            />
            <span className="text-xs font-semibold text-gray-500">
              출고 내역
            </span>
          </div>
          <span className="text-[11px] text-gray-400">{records.length}건</span>
        </div>

        {loading && records.length === 0 ? (
          <div className="flex items-center justify-center py-16">
            <svg
              className="w-8 h-8 animate-spin text-emerald-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>
        ) : records.length === 0 ? (
          <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="M19.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m5.231 13.481L15 17.25m-4.5-15H5.625c-.621 0-1.125.504-1.125 1.125v16.5c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9zm3.75 11.625a2.625 2.625 0 11-5.25 0 2.625 2.625 0 015.25 0z"
              />
            </svg>
            <p className="text-sm font-medium text-gray-500 mb-1">
              출고 내역이 없습니다
            </p>
            <p className="text-xs text-gray-400">
              조회 조건을 변경하거나 출고를 진행해 주세요
            </p>
          </div>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-3">
            {records.map((record) => {
              const key = getRowKey(record);
              return (
                <div
                  key={key}
                  className={`relative rounded-xl border p-3 transition-all cursor-pointer ${
                    selectedIds.has(key)
                      ? "ring-2 ring-emerald-500 border-emerald-300 bg-emerald-50/30"
                      : "border-gray-200 bg-white hover:border-emerald-300"
                  }`}
                  onClick={() => toggleSelect(key)}
                >
                  {/* Card header */}
                  <div className="flex items-center gap-1.5 mb-2.5 pb-2 border-b border-gray-100">
                    <input
                      type="checkbox"
                      checked={selectedIds.has(key)}
                      onChange={() => toggleSelect(key)}
                      onClick={(e) => e.stopPropagation()}
                      className="w-4 h-4 rounded border-gray-300 text-emerald-600 focus:ring-emerald-500"
                    />
                    <span className="text-[11px] text-gray-400 font-medium">
                      {record.outbound_number}
                    </span>
                    <span className="text-[11px] font-semibold px-1.5 py-0.5 rounded-full bg-emerald-50 text-emerald-600">
                      {record.detail_outbound_type || record.outbound_type}
                    </span>
                    <span
                      className={`ml-auto text-[11px] font-semibold px-1.5 py-0.5 rounded-full ${
                        record.outbound_status === "출고완료"
                          ? "bg-green-50 text-green-600"
                          : record.outbound_status === "부분출고"
                            ? "bg-amber-50 text-amber-600"
                            : "bg-gray-50 text-gray-500"
                      }`}
                    >
                      {record.outbound_status || "출고"}
                    </span>
                    <button
                      onClick={(e) => {
                        e.stopPropagation();
                        openEdit(record);
                      }}
                      className="ml-1 w-7 h-7 rounded-lg bg-gray-50 hover:bg-emerald-50 flex items-center justify-center text-gray-400 hover:text-emerald-600 transition-colors"
                    >
                      <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="M16.862 4.487l1.687-1.688a1.875 1.875 0 112.652 2.652L10.582 16.07a4.5 4.5 0 01-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 011.13-1.897l8.932-8.931zm0 0L19.5 7.125M18 14v4.75A2.25 2.25 0 0115.75 21H5.25A2.25 2.25 0 013 18.75V8.25A2.25 2.25 0 015.25 6H10"
                        />
                      </svg>
                    </button>
                  </div>
                  {/* Card body */}
                  <div className="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 truncate">
                        {record.item_name || "-"}
                      </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-500 truncate">
                        {record.item_code || record.item_number || "-"}
                      </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">
                        {record.customer_name || "-"}
                      </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-emerald-700">
                        {Number(record.outbound_qty).toLocaleString()}{" "}
                        {record.unit || "EA"}
                      </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">
                        {record.outbound_date?.slice(0, 10) || "-"}
                      </span>
                    </div>
                    {(record as any).warehouse_name && (
                      <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">
                          {(record as any).warehouse_name}
                        </span>
                      </div>
                    )}
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </div>

      {/* ===== Edit Modal ===== */}
      {editRecord && (
        <div
          className="fixed inset-0 z-50 bg-black/40"
          onClick={() => setEditRecord(null)}
        >
          <div
            className="absolute inset-x-0 bottom-0 sm:inset-auto sm:left-1/2 sm:top-1/2 sm:-translate-x-1/2 sm:-translate-y-1/2 bg-white w-full sm:max-w-lg max-h-[90vh] rounded-t-2xl sm:rounded-2xl overflow-hidden flex flex-col"
            onClick={(e) => e.stopPropagation()}
          >
            {/* Modal header */}
            <div className="flex items-center justify-between px-4 py-3 border-b border-gray-100 bg-gradient-to-b from-emerald-50 to-white shrink-0">
              <div className="min-w-0">
                <h2 className="text-lg font-bold text-gray-900">출고 수정</h2>
                <p className="text-[11px] text-gray-400 truncate">
                  {editRecord.outbound_number} | {editRecord.item_name}
                </p>
              </div>
              <button
                onClick={() => setEditRecord(null)}
                className="w-9 h-9 rounded-xl bg-white border border-gray-200 flex items-center justify-center text-gray-400 hover:text-gray-600 shrink-0 ml-2"
              >
                <svg
                  className="w-5 h-5"
                  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>

            {/* Modal body */}
            <div className="flex-1 overflow-y-auto px-4 py-4 space-y-5">
              {/* 기본 정보 */}
              <FieldGroup title="기본 정보">
                <FormField
                  label="출고일"
                  type="date"
                  value={editForm.outbound_date}
                  onChange={(v) => updateField("outbound_date", v)}
                />
                <FormField
                  label="출고상태"
                  type="select"
                  value={editForm.outbound_status}
                  onChange={(v) => updateField("outbound_status", v)}
                  options={STATUS_OPTIONS}
                />
              </FieldGroup>

              {/* 수량/금액 */}
              <FieldGroup title="수량/금액">
                <FormField
                  label="수량"
                  type="number"
                  value={editForm.outbound_qty}
                  onChange={(v) => updateField("outbound_qty", v)}
                />
                <FormField
                  label="단가"
                  type="number"
                  value={editForm.unit_price}
                  onChange={(v) => updateField("unit_price", v)}
                />
                <FormField
                  label="금액"
                  type="number"
                  value={editForm.total_amount}
                  onChange={(v) => updateField("total_amount", v)}
                  readOnly
                />
              </FieldGroup>

              {/* 출고 상세 */}
              <FieldGroup title="출고 상세">
                <FormField
                  label="LOT번호"
                  value={editForm.lot_number}
                  onChange={(v) => updateField("lot_number", v)}
                />
                <FormField
                  label="창고"
                  type="select"
                  value={editForm.warehouse_code}
                  onChange={(v) => updateField("warehouse_code", v)}
                  options={warehouses.map((w) => ({
                    value: w.warehouse_code,
                    label: w.warehouse_name,
                  }))}
                  emptyLabel="선택..."
                />
                <FormField
                  label="위치"
                  value={editForm.location_code}
                  onChange={(v) => updateField("location_code", v)}
                />
                <FormField
                  label="담당자"
                  value={editForm.manager_id}
                  onChange={(v) => updateField("manager_id", v)}
                />
              </FieldGroup>

              {/* 메모 */}
              <div>
                <h3 className="text-xs font-bold text-gray-500 mb-2 uppercase tracking-wider">
                  메모
                </h3>
                <textarea
                  value={editForm.memo}
                  onChange={(e) => updateField("memo", e.target.value)}
                  rows={3}
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm outline-none focus:border-emerald-400 focus:ring-2 focus:ring-emerald-100 resize-none"
                  placeholder="메모 입력..."
                />
              </div>
            </div>

            {/* Modal footer */}
            <div className="flex items-center gap-3 px-4 py-3 border-t border-gray-100 bg-gray-50/50 shrink-0">
              <button
                onClick={() => setEditRecord(null)}
                className="flex-1 py-3 rounded-xl border border-gray-200 text-sm font-semibold text-gray-600 active:scale-95 transition-all"
              >
                취소
              </button>
              <button
                onClick={handleSave}
                disabled={saving}
                className="flex-1 py-3 rounded-xl text-sm font-semibold text-white active:scale-95 transition-all disabled:opacity-50"
                style={{
                  background: "linear-gradient(to bottom, #34d399, #059669)",
                }}
              >
                {saving ? "저장 중..." : "저장"}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* ===== Customer Modal ===== */}
      <SupplierModal
        open={customerModalOpen}
        onClose={() => setCustomerModalOpen(false)}
        onSelect={(customer) => setSelectedCustomer(customer)}
      />
    </div>
  );
}

/* ------------------------------------------------------------------ */
/* Sub-components                                                      */
/* ------------------------------------------------------------------ */

function FieldGroup({
  title,
  children,
}: {
  title: string;
  children: React.ReactNode;
}) {
  return (
    <div>
      <h3 className="text-xs font-bold text-gray-500 mb-2 uppercase tracking-wider">
        {title}
      </h3>
      <div className="grid grid-cols-2 gap-3">{children}</div>
    </div>
  );
}

interface FormFieldProps {
  label: string;
  value: any;
  onChange: (v: any) => void;
  type?: "text" | "number" | "date" | "select";
  options?: string[] | { value: string; label: string }[];
  emptyLabel?: string;
  readOnly?: boolean;
}

function FormField({
  label,
  value,
  onChange,
  type = "text",
  options,
  emptyLabel,
  readOnly,
}: FormFieldProps) {
  const baseClass =
    "w-full px-3 py-2 border border-gray-200 rounded-lg text-sm outline-none focus:border-emerald-400 focus:ring-2 focus:ring-emerald-100";

  return (
    <div>
      <label className="text-[11px] font-semibold text-gray-400 mb-1 block">
        {label}
      </label>
      {type === "select" && options ? (
        <select
          value={value}
          onChange={(e) => onChange(e.target.value)}
          className={`${baseClass} bg-white`}
        >
          {emptyLabel && <option value="">{emptyLabel}</option>}
          {options.map((opt) => {
            const v = typeof opt === "string" ? opt : opt.value;
            const l = typeof opt === "string" ? opt : opt.label;
            return (
              <option key={v} value={v}>
                {l}
              </option>
            );
          })}
        </select>
      ) : (
        <input
          type={type}
          value={value}
          onChange={(e) =>
            onChange(
              type === "number" ? Number(e.target.value) : e.target.value,
            )
          }
          readOnly={readOnly}
          className={`${baseClass} ${readOnly ? "bg-gray-50 text-gray-500" : ""}`}
        />
      )}
    </div>
  );
}
