"use client";

import React, { useState, useEffect, useCallback } from "react";
import { useRouter } from "next/navigation";
import { usePopCompanyPath } from "@/hooks/usePopCompanyPath";
import { SupplierModal, type Supplier } from "./SupplierModal";
import {
  getReceivingList,
  updateReceiving,
  deleteReceiving,
  getReceivingWarehouses,
  type InboundItem,
  type WarehouseOption,
} from "@/lib/api/receiving";

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

interface InboundRecord extends InboundItem {
  detail_id?: string;
  seq_no?: number;
  detail_inbound_type?: string;
  header_memo?: string;
}

const STATUS_OPTIONS = ["입고완료", "부분입고", "대기"];
const INSPECTION_OPTIONS = ["대기", "검사완료", "합격", "불합격"];
const INBOUND_TYPE_OPTIONS = [
  { value: "all", label: "전체" },
  { value: "구매입고", label: "구매입고" },
  { value: "생산입고", label: "생산입고" },
  { value: "외주입고", label: "외주입고" },
  { value: "사급자재입고", label: "사급자재입고" },
  { value: "반품입고", label: "반품입고" },
  { value: "반납입고", label: "반납입고" },
  { value: "불량입고", label: "불량입고" },
  { value: "교환입고", label: "교환입고" },
  { value: "외주자재회수", label: "외주자재회수" },
  { value: "기타입고", label: "기타입고" },
];

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

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

  /* ── Filters ── */
  const [inboundDate, setInboundDate] = useState(today);
  const [inboundType, setInboundType] = useState("all");
  const [keyword, setKeyword] = useState("");
  const [selectedSupplier, setSelectedSupplier] = useState<Supplier | null>(
    null,
  );
  const [supplierModalOpen, setSupplierModalOpen] = useState(false);

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

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

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

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

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

      const res = await getReceivingList(params);
      if (res.success) {
        let data = res.data as unknown as InboundRecord[];
        if (selectedSupplier?.customer_code) {
          data = data.filter(
            (r) => r.supplier_code === selectedSupplier.customer_code,
          );
        }
        setRecords(data);
        setSelectedIds(new Set());
      }
    } catch (e) {
      console.error("입고 목록 조회 실패", e);
    } finally {
      setLoading(false);
    }
  }, [inboundDate, inboundType, keyword, selectedSupplier]);

  useEffect(() => {
    getReceivingWarehouses()
      .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 deleteReceiving(hid);
      }
      await fetchRecords();
    } catch (e: any) {
      alert(`삭제 실패: ${e?.message || "알 수 없는 오류"}`);
    } finally {
      setDeleting(false);
    }
  };

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

  const openEdit = (record: InboundRecord) => {
    setEditRecord(record);
    setEditForm({
      inbound_date: record.inbound_date?.slice(0, 10) || today,
      inbound_qty: record.inbound_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 || "",
      inbound_status: record.inbound_status || "입고완료",
      inspection_status: record.inspection_status || "대기",
      inspector: record.inspector || "",
      manager: record.manager || "",
      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 === "inbound_qty" || key === "unit_price") {
        next.total_amount =
          Math.round(
            (Number(next.inbound_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 updateReceiving(editRecord.id, payload as Partial<InboundItem>);
      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 justify-between gap-3">
        <div className="flex items-center gap-3">
          <button
            onClick={() => router.push(companyPath("/pop/inbound"))}
            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>
        <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, #60a5fa, #2563eb)",
            }}
          >
            수정
          </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>

      {/* ===== 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={inboundDate}
              onChange={(e) => setInboundDate(e.target.value)}
              className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100"
            />
          </div>
          {/* 입고유형 */}
          <div>
            <label className="text-xs font-semibold text-gray-500 mb-1 block">
              입고유형
            </label>
            <select
              value={inboundType}
              onChange={(e) => setInboundType(e.target.value)}
              className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100 bg-white"
            >
              {INBOUND_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={() => setSupplierModalOpen(true)}
              className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm text-left outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100 bg-white flex items-center justify-between"
            >
              <span
                className={
                  selectedSupplier
                    ? "text-gray-900 truncate"
                    : "text-gray-400"
                }
              >
                {selectedSupplier ? selectedSupplier.customer_name : "전체"}
              </span>
              {selectedSupplier ? (
                <span
                  onClick={(e) => {
                    e.stopPropagation();
                    setSelectedSupplier(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-blue-400 focus:ring-2 focus:ring-blue-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, #60a5fa, #2563eb)",
                }}
              >
                {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>

      {/* ===== 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-blue-600 focus:ring-blue-500"
            />
            <span className="text-xs font-semibold text-gray-500">
              입고 내역
            </span>
          </div>
          <span className="text-sm text-gray-500">
            {selectedIds.size > 0
              ? `${selectedIds.size}건 선택`
              : `총 ${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-blue-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-blue-500 border-blue-300 bg-blue-50/30"
                      : "border-gray-200 bg-white hover:border-blue-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-blue-600 focus:ring-blue-500"
                    />
                    <span className="text-[11px] text-gray-400 font-medium">
                      {record.inbound_number}
                    </span>
                    <span className="text-[11px] font-semibold px-1.5 py-0.5 rounded-full bg-blue-50 text-blue-600">
                      {record.detail_inbound_type || record.inbound_type}
                    </span>
                    <span
                      className={`ml-auto text-[11px] font-semibold px-1.5 py-0.5 rounded-full ${
                        record.inbound_status === "입고완료"
                          ? "bg-green-50 text-green-600"
                          : record.inbound_status === "부분입고"
                            ? "bg-amber-50 text-amber-600"
                            : "bg-gray-50 text-gray-500"
                      }`}
                    >
                      {record.inbound_status || "입고"}
                    </span>
                    <button
                      onClick={(e) => {
                        e.stopPropagation();
                        openEdit(record);
                      }}
                      className="ml-1 w-7 h-7 rounded-lg bg-gray-50 hover:bg-blue-50 flex items-center justify-center text-gray-400 hover:text-blue-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_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.supplier_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-blue-700">
                        {Number(record.inbound_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.inbound_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-blue-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.inbound_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.inbound_date}
                  onChange={(v) => updateField("inbound_date", v)}
                />
                <FormField
                  label="입고상태"
                  type="select"
                  value={editForm.inbound_status}
                  onChange={(v) => updateField("inbound_status", v)}
                  options={STATUS_OPTIONS}
                />
              </FieldGroup>

              {/* 수량/금액 */}
              <FieldGroup title="수량/금액">
                <FormField
                  label="수량"
                  type="number"
                  value={editForm.inbound_qty}
                  onChange={(v) => updateField("inbound_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="검사상태"
                  type="select"
                  value={editForm.inspection_status}
                  onChange={(v) => updateField("inspection_status", v)}
                  options={INSPECTION_OPTIONS}
                />
                <FormField
                  label="검사자"
                  value={editForm.inspector}
                  onChange={(v) => updateField("inspector", v)}
                />
                <FormField
                  label="담당자"
                  value={editForm.manager}
                  onChange={(v) => updateField("manager", 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-blue-400 focus:ring-2 focus:ring-blue-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, #60a5fa, #2563eb)",
                }}
              >
                {saving ? "저장 중..." : "저장"}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* ===== Supplier Modal ===== */}
      <SupplierModal
        open={supplierModalOpen}
        onClose={() => setSupplierModalOpen(false)}
        onSelect={(supplier) => setSelectedSupplier(supplier)}
      />
    </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-blue-400 focus:ring-2 focus:ring-blue-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>
  );
}
