"use client";

import React, { useState, useMemo, useEffect, useCallback } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import { Checkbox } from "@/components/ui/checkbox";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogDescription } from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";
import { Plus, Trash2, Save, X, ChevronLeft, ChevronRight, Search, Loader2, Wrench, Pencil, CheckCircle2, ArrowRight, Check, ChevronsUpDown, ClipboardCheck, Inbox, Settings2 } from "lucide-react";
import { cn } from "@/lib/utils";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from "@/components/ui/command";
// API: /work-instruction/*
import {
  getWorkInstructionList, previewWorkInstructionNo, saveWorkInstruction, deleteWorkInstructions,
  getWIItemSource, getWISalesOrderSource, getWIProductionPlanSource, getEquipmentList, getEmployeeList,
  getRoutingVersions, RoutingVersionData,
} from "@/lib/api/workInstruction";
import { WorkStandardEditModal } from "./WorkStandardEditModal";
import { useTableSettings } from "@/hooks/useTableSettings";
import { TableSettingsModal } from "@/components/common/TableSettingsModal";
import { DynamicSearchFilter, FilterValue } from "@/components/common/DynamicSearchFilter";

const GRID_COLUMNS = [
  { key: "work_instruction_no", label: "작업지시번호" },
  { key: "status", label: "상태" },
  { key: "progress", label: "진행현황" },
  { key: "item_name", label: "품목명" },
  { key: "spec", label: "규격" },
  { key: "qty", label: "수량" },
  { key: "equipment", label: "설비" },
  { key: "routing", label: "라우팅" },
  { key: "work_team", label: "작업조" },
  { key: "worker", label: "작업자" },
  { key: "start_date", label: "시작일" },
  { key: "end_date", label: "완료일" },
  { key: "actions", label: "작업" },
];

type SourceType = "production" | "order" | "item";

const STATUS_BADGE: Record<string, { label: string; cls: string }> = {
  "일반": { label: "일반", cls: "bg-primary/10 text-primary border-primary/20" },
  "긴급": { label: "긴급", cls: "bg-destructive/10 text-destructive border-destructive/20" },
};
const PROGRESS_BADGE: Record<string, { label: string; cls: string }> = {
  "대기": { label: "대기", cls: "bg-warning/10 text-warning" },
  "진행중": { label: "진행중", cls: "bg-primary/10 text-primary" },
  "완료": { label: "완료", cls: "bg-success/10 text-success" },
};

interface EquipmentOption { id: string; equipment_code: string; equipment_name: string; }
interface EmployeeOption { user_id: string; user_name: string; dept_name: string | null; }
interface SelectedItem {
  itemCode: string; itemName: string; spec: string; qty: number; remark: string;
  sourceType: SourceType; sourceTable: string; sourceId: string | number;
  routing?: string; routingOptions?: RoutingVersionData[];
}

export default function WorkInstructionPage() {
  const ts = useTableSettings("c16-work-instruction", "work_instruction", GRID_COLUMNS);
  const [orders, setOrders] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [equipmentOptions, setEquipmentOptions] = useState<EquipmentOption[]>([]);
  const [employeeOptions, setEmployeeOptions] = useState<EmployeeOption[]>([]);

  // 검색
  const [searchFilters, setSearchFilters] = useState<FilterValue[]>([]);

  // 1단계: 등록 모달
  const [isRegModalOpen, setIsRegModalOpen] = useState(false);
  const [regSourceType, setRegSourceType] = useState<SourceType | "">("");
  const [regSourceData, setRegSourceData] = useState<any[]>([]);
  const [regSourceLoading, setRegSourceLoading] = useState(false);
  const [regKeyword, setRegKeyword] = useState("");
  const [regCheckedIds, setRegCheckedIds] = useState<Set<string>>(new Set());
  const [regMergeSameItem, setRegMergeSameItem] = useState(true);
  const [regPage, setRegPage] = useState(1);
  const [regPageSize] = useState(20);
  const [regTotalCount, setRegTotalCount] = useState(0);

  // 2단계: 확인 모달
  const [isConfirmModalOpen, setIsConfirmModalOpen] = useState(false);
  const [confirmItems, setConfirmItems] = useState<SelectedItem[]>([]);
  const [confirmWiNo, setConfirmWiNo] = useState("");
  const [confirmStatus, setConfirmStatus] = useState("일반");
  const [confirmStartDate, setConfirmStartDate] = useState("");
  const [confirmEndDate, setConfirmEndDate] = useState("");
  const nv = (v: string) => v || "none";
  const fromNv = (v: string) => v === "none" ? "" : v;
  const [confirmEquipmentId, setConfirmEquipmentId] = useState("");
  const [confirmWorkTeam, setConfirmWorkTeam] = useState("");
  const [confirmWorker, setConfirmWorker] = useState("");
  const [saving, setSaving] = useState(false);

  // 등록 확인 모달 — 인라인 추가 폼
  const [confirmAddQty, setConfirmAddQty] = useState("");
  const [confirmAddWorkerOpen, setConfirmAddWorkerOpen] = useState(false);

  // 수정 모달
  const [isEditModalOpen, setIsEditModalOpen] = useState(false);
  const [editOrder, setEditOrder] = useState<any>(null);
  const [editItems, setEditItems] = useState<SelectedItem[]>([]);
  const [editStatus, setEditStatus] = useState("일반");
  const [editStartDate, setEditStartDate] = useState("");
  const [editEndDate, setEditEndDate] = useState("");
  const [editEquipmentId, setEditEquipmentId] = useState("");
  const [editWorkTeam, setEditWorkTeam] = useState("");
  const [editWorker, setEditWorker] = useState("");
  const [editRemark, setEditRemark] = useState("");
  const [editSaving, setEditSaving] = useState(false);
  const [addQty, setAddQty] = useState("");
  const [addEquipment, setAddEquipment] = useState("");
  const [addWorkTeam, setAddWorkTeam] = useState("");
  const [addWorker, setAddWorker] = useState("");
  const [confirmWorkerOpen, setConfirmWorkerOpen] = useState(false);
  const [editWorkerOpen, setEditWorkerOpen] = useState(false);
  const [addWorkerOpen, setAddWorkerOpen] = useState(false);

  // 라우팅 관련 상태
  const [confirmRouting, setConfirmRouting] = useState("");
  const [confirmRoutingOptions, setConfirmRoutingOptions] = useState<RoutingVersionData[]>([]);
  const [editRouting, setEditRouting] = useState("");
  const [editRoutingOptions, setEditRoutingOptions] = useState<RoutingVersionData[]>([]);

  // 공정작업기준 모달 상태
  const [wsModalOpen, setWsModalOpen] = useState(false);
  const [wsModalWiNo, setWsModalWiNo] = useState("");
  const [wsModalRoutingId, setWsModalRoutingId] = useState("");
  const [wsModalRoutingName, setWsModalRoutingName] = useState("");
  const [wsModalItemName, setWsModalItemName] = useState("");
  const [wsModalItemCode, setWsModalItemCode] = useState("");

  useEffect(() => {
    getEquipmentList().then(r => { if (r.success) setEquipmentOptions(r.data || []); });
    getEmployeeList().then(r => { if (r.success) setEmployeeOptions(r.data || []); });
  }, []);

  const fetchOrders = useCallback(async () => {
    setLoading(true);
    try {
      const params: any = {};
      for (const f of searchFilters) {
        if (f.columnName === "start_date" && f.operator === "between" && f.value) {
          const [from, to] = f.value.split("|");
          if (from) params.dateFrom = from;
          if (to) params.dateTo = to;
        } else if (f.columnName === "status" && f.value) {
          params.status = f.value;
        } else if (f.columnName === "progress" && f.value) {
          params.progressStatus = f.value;
        } else if (f.columnName === "work_instruction_no" && f.value) {
          params.keyword = f.value;
        } else if (f.columnName === "item_name" && f.value) {
          params.keyword = f.value;
        }
      }
      const r = await getWorkInstructionList(params);
      if (r.success) setOrders(r.data || []);
    } catch {} finally { setLoading(false); }
  }, [searchFilters]);

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

  // ─── 1단계 등록 ───
  const openRegModal = () => {
    setRegSourceType("production"); setRegSourceData([]); setRegKeyword(""); setRegCheckedIds(new Set());
    setRegPage(1); setRegTotalCount(0); setRegMergeSameItem(true); setIsRegModalOpen(true);
  };

  const fetchRegSource = useCallback(async (pageOverride?: number) => {
    if (!regSourceType) return;
    setRegSourceLoading(true);
    try {
      const p = pageOverride ?? regPage;
      const params: any = { page: p, pageSize: regPageSize };
      if (regKeyword.trim()) params.keyword = regKeyword.trim();
      let r;
      switch (regSourceType) {
        case "production": r = await getWIProductionPlanSource(params); break;
        case "order": r = await getWISalesOrderSource(params); break;
        case "item": r = await getWIItemSource(params); break;
      }
      if (r?.success) { setRegSourceData(r.data || []); setRegTotalCount(r.totalCount || 0); }
    } catch {} finally { setRegSourceLoading(false); }
  }, [regSourceType, regKeyword, regPage, regPageSize]);

  useEffect(() => { if (isRegModalOpen && regSourceType) { setRegPage(1); setRegCheckedIds(new Set()); fetchRegSource(1); } }, [regSourceType]);

  const getRegId = (item: any) => regSourceType === "item" ? (item.item_code || item.id) : String(item.id);
  const toggleRegItem = (id: string) => { setRegCheckedIds(prev => { const n = new Set(prev); if (n.has(id)) n.delete(id); else n.add(id); return n; }); };
  const toggleRegAll = () => { if (regCheckedIds.size === regSourceData.length) setRegCheckedIds(new Set()); else setRegCheckedIds(new Set(regSourceData.map(getRegId))); };

  const applyRegistration = () => {
    if (regCheckedIds.size === 0) { alert("품목을 선택해주세요."); return; }
    const items: SelectedItem[] = [];
    for (const item of regSourceData) {
      if (!regCheckedIds.has(getRegId(item))) continue;
      if (regSourceType === "item") items.push({ itemCode: item.item_code, itemName: item.item_name || "", spec: item.spec || "", qty: 1, remark: "", sourceType: "item", sourceTable: "item_info", sourceId: item.item_code });
      else if (regSourceType === "order") items.push({ itemCode: item.item_code || "", itemName: item.item_name || "", spec: item.spec || "", qty: Number(item.qty || 1), remark: "", sourceType: "order", sourceTable: "sales_order_detail", sourceId: item.id });
      else items.push({ itemCode: item.item_code || "", itemName: item.item_name || "", spec: "", qty: Number(item.plan_qty || 1), remark: "", sourceType: "production", sourceTable: "production_plan_mng", sourceId: item.id });
    }

    // 동일품목 합산
    if (regMergeSameItem) {
      const merged = new Map<string, SelectedItem>();
      for (const it of items) {
        const key = it.itemCode;
        if (merged.has(key)) { merged.get(key)!.qty += it.qty; }
        else { merged.set(key, { ...it }); }
      }
      setConfirmItems(Array.from(merged.values()));
    } else {
      setConfirmItems(items);
    }

    setConfirmWiNo("불러오는 중...");
    setConfirmStatus("일반"); setConfirmStartDate(new Date().toISOString().split("T")[0]);
    setConfirmEndDate(""); setConfirmEquipmentId(""); setConfirmWorkTeam(""); setConfirmWorker("");
    setConfirmRouting(""); setConfirmRoutingOptions([]);
    previewWorkInstructionNo().then(r => { if (r.success) setConfirmWiNo(r.instructionNo); else setConfirmWiNo("(자동생성)"); }).catch(() => setConfirmWiNo("(자동생성)"));

    // 품목별 라우팅 옵션 로드
    const finalItems = regMergeSameItem ? Array.from(new Map(items.map(i => [i.itemCode, i])).values()) : items;
    const uniqueItemCodes = [...new Set(finalItems.map(i => i.itemCode).filter(Boolean))];
    for (const ic of uniqueItemCodes) {
      getRoutingVersions("__new__", ic).then(r => {
        if (r.success && r.data) {
          setConfirmItems(prev => prev.map(it => {
            if (it.itemCode !== ic) return it;
            const defaultRv = r.data.find(rv => rv.is_default);
            return { ...it, routingOptions: r.data, routing: defaultRv?.id || "" };
          }));
        }
      }).catch(() => {});
    }

    setIsRegModalOpen(false); setIsConfirmModalOpen(true);
  };

  // 등록 확인 모달 — 인라인 품목 추가
  const addConfirmItem = () => {
    if (!confirmAddQty || Number(confirmAddQty) <= 0) { alert("수량을 입력해주세요."); return; }
    const firstItem = confirmItems[0];
    setConfirmItems(prev => [...prev, {
      itemCode: firstItem?.itemCode || "", itemName: firstItem?.itemName || "", spec: firstItem?.spec || "",
      qty: Number(confirmAddQty), remark: "",
      sourceType: "item" as SourceType, sourceTable: "item_info", sourceId: firstItem?.itemCode || "",
    }]);
    setConfirmAddQty("");
  };

  // ─── 2단계 최종 적용 ───
  const finalizeRegistration = async () => {
    if (confirmItems.length === 0) { alert("품목이 없습니다."); return; }
    setSaving(true);
    try {
      const payload = {
        status: confirmStatus, startDate: confirmStartDate, endDate: confirmEndDate,
        equipmentId: confirmEquipmentId, workTeam: confirmWorkTeam, worker: confirmWorker,
        routing: confirmRouting || null,
        items: confirmItems.map(i => ({ itemNumber: i.itemCode, itemCode: i.itemCode, qty: String(i.qty), remark: i.remark, sourceTable: i.sourceTable, sourceId: String(i.sourceId), partCode: i.itemCode, routing: i.routing || null })),
      };
      const r = await saveWorkInstruction(payload);
      if (r.success) { setIsConfirmModalOpen(false); fetchOrders(); alert("작업지시가 등록되었습니다."); }
      else alert(r.message || "저장 실패");
    } catch (e: any) { alert(e.message || "저장 실패"); } finally { setSaving(false); }
  };

  // ─── 수정 모달 ───
  const openEditModal = (order: any) => {
    const wiNo = order.work_instruction_no;
    const relatedDetails = orders.filter(o => o.work_instruction_no === wiNo);
    setEditOrder(order); setEditStatus(order.status || "일반");
    setEditStartDate(order.start_date || ""); setEditEndDate(order.end_date || "");
    setEditEquipmentId(order.equipment_id || ""); setEditWorkTeam(order.work_team || "");
    setEditWorker(order.worker || ""); setEditRemark(order.wi_remark || "");
    const items: SelectedItem[] = relatedDetails.map((d: any) => ({
      itemCode: d.item_number || d.part_code || "", itemName: d.item_name || "", spec: d.item_spec || "",
      qty: Number(d.detail_qty || 0), remark: d.detail_remark || "",
      sourceType: (d.source_table === "sales_order_detail" ? "order" : d.source_table === "production_plan_mng" ? "production" : "item") as SourceType,
      sourceTable: d.source_table || "item_info", sourceId: d.source_id || "",
      routing: d.detail_routing_version_id || order.routing_version_id || "",
      routingOptions: [],
    }));
    setEditItems(items);
    setAddQty(""); setAddEquipment(""); setAddWorkTeam(""); setAddWorker("");
    setEditRouting(order.routing_version_id || "");
    setEditRoutingOptions([]);

    // 품목별 라우팅 옵션 로드
    const uniqueItemCodes = [...new Set(items.map(i => i.itemCode).filter(Boolean))];
    for (const ic of uniqueItemCodes) {
      getRoutingVersions(wiNo, ic).then(r => {
        if (r.success && r.data) {
          setEditItems(prev => prev.map(it => {
            if (it.itemCode !== ic) return it;
            const opts = r.data;
            const hasRouting = it.routing && opts.some(rv => rv.id === it.routing);
            return {
              ...it,
              routingOptions: opts,
              routing: hasRouting ? it.routing : (opts.find(rv => rv.is_default)?.id || it.routing || ""),
            };
          }));
        }
      }).catch(() => {});
    }

    setIsEditModalOpen(true);
  };

  const addEditItem = () => {
    if (!addQty || Number(addQty) <= 0) { alert("수량을 입력해주세요."); return; }
    setEditItems(prev => [...prev, {
      itemCode: editOrder?.item_number || "", itemName: editOrder?.item_name || "", spec: editOrder?.item_spec || "",
      qty: Number(addQty), remark: "", sourceType: "item", sourceTable: "item_info", sourceId: editOrder?.item_number || "",
    }]);
    setAddQty("");
  };

  const saveEdit = async () => {
    if (!editOrder || editItems.length === 0) { alert("품목이 없습니다."); return; }
    setEditSaving(true);
    try {
      const payload = {
        id: editOrder.wi_id, status: editStatus, startDate: editStartDate, endDate: editEndDate,
        equipmentId: editEquipmentId, workTeam: editWorkTeam, worker: editWorker, remark: editRemark,
        routing: editRouting || null,
        items: editItems.map(i => ({ itemNumber: i.itemCode, itemCode: i.itemCode, qty: String(i.qty), remark: i.remark, sourceTable: i.sourceTable, sourceId: String(i.sourceId), partCode: i.itemCode, routing: i.routing || null })),
      };
      const r = await saveWorkInstruction(payload);
      if (r.success) { setIsEditModalOpen(false); fetchOrders(); alert("수정되었습니다."); }
      else alert(r.message || "저장 실패");
    } catch (e: any) { alert(e.message || "저장 실패"); } finally { setEditSaving(false); }
  };

  const handleDelete = async (wiId: string) => {
    if (!confirm("이 작업지시를 삭제하시겠습니까?")) return;
    const r = await deleteWorkInstructions([wiId]);
    if (r.success) { fetchOrders(); } else alert(r.message || "삭제 실패");
  };

  const getProgress = (o: any) => {
    const t = Number(o.total_qty || 0), c = Number(o.completed_qty || 0);
    return t === 0 ? 0 : Math.min(100, Math.round((c / t) * 100));
  };
  const getProgressLabel = (o: any) => { const p = getProgress(o); if (o.progress_status) return o.progress_status; if (p >= 100) return "완료"; if (p > 0) return "진행중"; return "대기"; };
  const totalRegPages = Math.max(1, Math.ceil(regTotalCount / regPageSize));

  const getDisplayNo = (o: any) => {
    const cnt = Number(o.detail_count || 1);
    const seq = Number(o.detail_seq || 1);
    if (cnt <= 1) return o.work_instruction_no || "-";
    return `${o.work_instruction_no}-${String(seq).padStart(2, "0")}`;
  };

  const openWorkStandardModal = (wiNo: string, routingVersionId: string, routingName: string, itemName: string, itemCode: string) => {
    if (!routingVersionId) { alert("라우팅이 선택되지 않았습니다."); return; }
    setWsModalWiNo(wiNo);
    setWsModalRoutingId(routingVersionId);
    setWsModalRoutingName(routingName);
    setWsModalItemName(itemName);
    setWsModalItemCode(itemCode);
    setWsModalOpen(true);
  };

  const getWorkerName = (userId: string) => {
    if (!userId) return "-";
    const emp = employeeOptions.find(e => e.user_id === userId);
    return emp ? emp.user_name : userId;
  };

  const WorkerCombobox = ({ value, onChange, open, onOpenChange, className, triggerClassName }: {
    value: string; onChange: (v: string) => void; open: boolean; onOpenChange: (v: boolean) => void;
    className?: string; triggerClassName?: string;
  }) => (
    <Popover open={open} onOpenChange={onOpenChange}>
      <PopoverTrigger asChild>
        <Button variant="outline" role="combobox" aria-expanded={open}
          className={cn("w-full justify-between font-normal", triggerClassName || "h-9 text-sm")}>
          {value ? (employeeOptions.find(e => e.user_id === value)?.user_name || value) : "작업자 선택"}
          <ChevronsUpDown className="ml-2 h-3.5 w-3.5 shrink-0 opacity-50" />
        </Button>
      </PopoverTrigger>
      <PopoverContent className="p-0" style={{ width: "var(--radix-popover-trigger-width)" }} align="start">
        <Command>
          <CommandInput placeholder="이름 검색..." className="text-xs" />
          <CommandList>
            <CommandEmpty className="text-xs py-4 text-center">사원을 찾을 수 없습니다</CommandEmpty>
            <CommandGroup>
              <CommandItem value="__none__" onSelect={() => { onChange(""); onOpenChange(false); }} className="text-xs">
                <Check className={cn("mr-2 h-3.5 w-3.5", !value ? "opacity-100" : "opacity-0")} />
                선택 안 함
              </CommandItem>
              {employeeOptions.map(emp => (
                <CommandItem key={emp.user_id} value={`${emp.user_name} ${emp.user_id}`}
                  onSelect={() => { onChange(emp.user_id); onOpenChange(false); }} className="text-xs">
                  <Check className={cn("mr-2 h-3.5 w-3.5", value === emp.user_id ? "opacity-100" : "opacity-0")} />
                  {emp.user_name}{emp.dept_name ? ` (${emp.dept_name})` : ""}
                </CommandItem>
              ))}
            </CommandGroup>
          </CommandList>
        </Command>
      </PopoverContent>
    </Popover>
  );

  return (
    <div className="flex flex-col h-[calc(100vh-4rem)] p-3 gap-3">
      {/* 검색 필터 바 */}
      <DynamicSearchFilter
        tableName="work_instruction"
        filterId="c16-work-instruction"
        onFilterChange={setSearchFilters}
        externalFilterConfig={ts.filterConfig}
        dataCount={new Set(orders.map(o => o.work_instruction_no)).size}
      />

      {/* 메인 테이블 */}
      <div className="flex-1 overflow-hidden border bg-card rounded-lg flex flex-col">
        <div className="flex flex-col h-full">
          {/* 패널 헤더 */}
          <div className="flex items-center justify-between px-4 py-2 border-b bg-muted/30 shrink-0">
            <div className="flex items-center gap-2">
              <Wrench className="w-4 h-4 text-muted-foreground" />
              <span className="text-[13px] font-bold text-foreground">작업지시 목록</span>
              <span className="text-[11px] font-semibold text-primary bg-primary/8 border border-primary/15 px-2 py-0.5 rounded-full font-mono">
                {new Set(orders.map(o => o.work_instruction_no)).size}건 ({orders.length}행)
              </span>
              {loading && <Loader2 className="w-3.5 h-3.5 animate-spin text-muted-foreground" />}
            </div>
            <div className="flex items-center gap-2">
              <Button size="sm" onClick={openRegModal}>
                <Plus className="w-3.5 h-3.5" /> 작업지시 등록
              </Button>
              <Button variant="ghost" size="sm" onClick={() => ts.setOpen(true)} title="테이블 설정">
                <Settings2 className="h-4 w-4" />
              </Button>
            </div>
          </div>

          {/* 테이블 */}
          <div className="flex-1 overflow-auto">
            <Table>
              <TableHeader className="sticky top-0 z-10">
                <TableRow className="bg-muted hover:bg-muted">
                  {ts.isVisible("work_instruction_no") && <TableHead className="w-[150px] text-[11px] font-bold uppercase tracking-wide text-muted-foreground">작업지시번호</TableHead>}
                  {ts.isVisible("status") && <TableHead className="w-[70px] text-center text-[11px] font-bold uppercase tracking-wide text-muted-foreground">상태</TableHead>}
                  {ts.isVisible("progress") && <TableHead className="w-[100px] text-center text-[11px] font-bold uppercase tracking-wide text-muted-foreground">진행현황</TableHead>}
                  {ts.isVisible("item_name") && <TableHead className="text-[11px] font-bold uppercase tracking-wide text-muted-foreground">품목명</TableHead>}
                  {ts.isVisible("spec") && <TableHead className="w-[100px] text-[11px] font-bold uppercase tracking-wide text-muted-foreground">규격</TableHead>}
                  {ts.isVisible("qty") && <TableHead className="w-[80px] text-right text-[11px] font-bold uppercase tracking-wide text-muted-foreground">수량</TableHead>}
                  {ts.isVisible("equipment") && <TableHead className="w-[120px] text-[11px] font-bold uppercase tracking-wide text-muted-foreground">설비</TableHead>}
                  {ts.isVisible("routing") && <TableHead className="w-[120px] text-[11px] font-bold uppercase tracking-wide text-muted-foreground">라우팅</TableHead>}
                  {ts.isVisible("work_team") && <TableHead className="w-[80px] text-center text-[11px] font-bold uppercase tracking-wide text-muted-foreground">작업조</TableHead>}
                  {ts.isVisible("worker") && <TableHead className="w-[100px] text-[11px] font-bold uppercase tracking-wide text-muted-foreground">작업자</TableHead>}
                  {ts.isVisible("start_date") && <TableHead className="w-[100px] text-center text-[11px] font-bold uppercase tracking-wide text-muted-foreground">시작일</TableHead>}
                  {ts.isVisible("end_date") && <TableHead className="w-[100px] text-center text-[11px] font-bold uppercase tracking-wide text-muted-foreground">완료일</TableHead>}
                  {ts.isVisible("actions") && <TableHead className="w-[150px] text-center text-[11px] font-bold uppercase tracking-wide text-muted-foreground">작업</TableHead>}
                </TableRow>
              </TableHeader>
              <TableBody>
                {loading ? (
                  <TableRow><TableCell colSpan={13} className="text-center py-16"><Loader2 className="w-6 h-6 animate-spin mx-auto text-muted-foreground" /></TableCell></TableRow>
                ) : orders.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={13} className="py-16">
                      <div className="flex flex-col items-center justify-center text-center">
                        <div className="rounded-full border-2 border-dashed border-muted-foreground/20 w-12 h-12 flex items-center justify-center mb-4">
                          <Inbox className="w-6 h-6 text-muted-foreground/40" />
                        </div>
                        <p className="text-sm font-medium text-muted-foreground mb-1">등록된 작업지시가 없어요</p>
                        <p className="text-xs text-muted-foreground/60">새로운 작업지시를 등록해주세요</p>
                      </div>
                    </TableCell>
                  </TableRow>
                ) : orders.map((o, rowIdx) => {
                  const pct = getProgress(o);
                  const pLabel = getProgressLabel(o);
                  const pBadge = PROGRESS_BADGE[pLabel] || PROGRESS_BADGE["대기"];
                  const sBadge = STATUS_BADGE[o.status] || STATUS_BADGE["일반"];
                  const isFirstOfGroup = Number(o.detail_seq) === 1;
                  return (
                    <TableRow key={`${o.wi_id}-${o.detail_id}`} className="hover:bg-muted/30">
                      {ts.isVisible("work_instruction_no") && <TableCell className="font-mono text-[13px] font-medium">{getDisplayNo(o)}</TableCell>}
                      {ts.isVisible("status") && <TableCell className="text-center"><Badge variant="outline" className={cn("text-[10px]", sBadge.cls)}>{sBadge.label}</Badge></TableCell>}
                      {ts.isVisible("progress") && <TableCell className="text-center">
                        {isFirstOfGroup ? (
                          <div className="flex flex-col items-center gap-1">
                            <Badge variant="secondary" className={cn("text-[10px]", pBadge.cls)}>{pBadge.label}</Badge>
                            <div className="w-full h-1.5 bg-muted rounded-full overflow-hidden">
                              <div className={cn("h-full rounded-full transition-all", pct >= 100 ? "bg-success" : pct > 0 ? "bg-primary" : "bg-muted-foreground/30")} style={{ width: `${pct}%` }} />
                            </div>
                            <span className="text-[10px] text-muted-foreground">{pct}%</span>
                          </div>
                        ) : <span className="text-[10px] text-muted-foreground">↑</span>}
                      </TableCell>}
                      {ts.isVisible("item_name") && <TableCell className="text-sm">{o.item_name || o.item_number || "-"}</TableCell>}
                      {ts.isVisible("spec") && <TableCell className="text-[13px] text-muted-foreground">{o.item_spec || "-"}</TableCell>}
                      {ts.isVisible("qty") && <TableCell className="text-right text-[13px] font-mono font-medium">{Number(o.detail_qty || 0).toLocaleString()}</TableCell>}
                      {ts.isVisible("equipment") && <TableCell className="text-[13px]">{isFirstOfGroup ? (o.equipment_name || "-") : ""}</TableCell>}
                      {ts.isVisible("routing") && <TableCell className="text-[13px]">
                        {isFirstOfGroup ? (
                          o.routing_version_id ? (
                            <button
                              className="text-primary underline underline-offset-2 hover:text-primary/80 cursor-pointer text-xs text-left"
                              onClick={e => {
                                e.stopPropagation();
                                openWorkStandardModal(
                                  o.work_instruction_no,
                                  o.routing_version_id,
                                  o.routing_name || "",
                                  o.item_name || o.item_number || "",
                                  o.item_number || ""
                                );
                              }}
                            >
                              {o.routing_name || "라우팅"} <ClipboardCheck className="w-3 h-3 inline ml-0.5" />
                            </button>
                          ) : <span className="text-muted-foreground">-</span>
                        ) : ""}
                      </TableCell>}
                      {ts.isVisible("work_team") && <TableCell className="text-center text-[13px]">{isFirstOfGroup ? (o.work_team || "-") : ""}</TableCell>}
                      {ts.isVisible("worker") && <TableCell className="text-[13px]">{isFirstOfGroup ? getWorkerName(o.worker) : ""}</TableCell>}
                      {ts.isVisible("start_date") && <TableCell className="text-center text-[13px] font-mono">{isFirstOfGroup ? (o.start_date || "-") : ""}</TableCell>}
                      {ts.isVisible("end_date") && <TableCell className="text-center text-[13px] font-mono">{isFirstOfGroup ? (o.end_date || "-") : ""}</TableCell>}
                      {ts.isVisible("actions") && <TableCell className="text-center">
                        {isFirstOfGroup && (
                          <div className="flex items-center justify-center gap-1">
                            <Button variant="ghost" size="sm" className="h-7 text-xs px-2" onClick={() => openEditModal(o)}><Pencil className="w-3 h-3" /> 수정</Button>
                            <Button variant="ghost" size="sm" className="h-7 text-xs px-2 text-destructive hover:text-destructive" onClick={() => handleDelete(o.wi_id)}><Trash2 className="w-3 h-3" /></Button>
                          </div>
                        )}
                      </TableCell>}
                    </TableRow>
                  );
                })}
              </TableBody>
            </Table>
          </div>
        </div>
      </div>

      {/* ── 1단계: 등록 모달 ── */}
      <Dialog open={isRegModalOpen} onOpenChange={setIsRegModalOpen}>
        <DialogContent className="max-w-[95vw] sm:max-w-[1200px] h-[80vh] flex flex-col p-0 gap-0">
          <DialogHeader className="px-6 py-4 border-b shrink-0">
            <DialogTitle className="text-base flex items-center gap-2"><Plus className="w-4 h-4" /> 작업지시 등록</DialogTitle>
            <DialogDescription className="text-xs text-muted-foreground">근거를 선택하고 품목을 체크한 후 "작업지시 적용" 버튼을 눌러주세요.</DialogDescription>
          </DialogHeader>

          <div className="px-6 py-3 border-b bg-muted/30 flex items-center gap-3 flex-wrap shrink-0">
            <span className="text-[11px] font-semibold uppercase tracking-wide text-muted-foreground whitespace-nowrap">근거</span>
            <Select value={regSourceType} onValueChange={v => setRegSourceType(v as SourceType)}>
              <SelectTrigger className="h-9 w-[160px]"><SelectValue placeholder="선택" /></SelectTrigger>
              <SelectContent><SelectItem value="production">생산계획</SelectItem><SelectItem value="order">수주</SelectItem><SelectItem value="item">품목정보</SelectItem></SelectContent>
            </Select>
            {regSourceType && (<>
              <Input placeholder="검색..." value={regKeyword} onChange={e => setRegKeyword(e.target.value)} className="h-9 w-[220px]"
                onKeyDown={e => { if (e.key === "Enter") { setRegPage(1); fetchRegSource(1); } }} />
              <Button size="sm" className="h-9" onClick={() => { setRegPage(1); fetchRegSource(1); }} disabled={regSourceLoading}>
                {regSourceLoading ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <Search className="w-3.5 h-3.5" />}<span className="ml-1.5">조회</span>
              </Button>
            </>)}
            <div className="flex-1" />
            <label className="flex items-center gap-1.5 cursor-pointer select-none">
              <Checkbox checked={regMergeSameItem} onCheckedChange={v => setRegMergeSameItem(!!v)} />
              <span className="text-xs font-semibold text-foreground">동일품목 합산</span>
            </label>
          </div>

          <div className="flex-1 overflow-auto px-6 py-4">
            {!regSourceType ? (
              <div className="flex flex-col items-center justify-center h-full text-center">
                <div className="rounded-full border-2 border-dashed border-muted-foreground/20 w-12 h-12 flex items-center justify-center mb-4">
                  <Search className="w-6 h-6 text-muted-foreground/40" />
                </div>
                <p className="text-sm font-medium text-muted-foreground mb-1">근거를 선택해주세요</p>
                <p className="text-xs text-muted-foreground/60">근거를 선택하고 검색하면 품목이 표시돼요</p>
              </div>
            ) : regSourceLoading ? (
              <div className="flex items-center justify-center h-full"><Loader2 className="w-6 h-6 animate-spin text-muted-foreground" /></div>
            ) : regSourceData.length === 0 ? (
              <div className="flex flex-col items-center justify-center h-full text-center">
                <div className="rounded-full border-2 border-dashed border-muted-foreground/20 w-12 h-12 flex items-center justify-center mb-4">
                  <Inbox className="w-6 h-6 text-muted-foreground/40" />
                </div>
                <p className="text-sm font-medium text-muted-foreground mb-1">검색 결과가 없어요</p>
                <p className="text-xs text-muted-foreground/60">다른 키워드로 검색해주세요</p>
              </div>
            ) : (
              <Table>
                <TableHeader className="sticky top-0 z-10">
                  <TableRow className="bg-muted hover:bg-muted">
                    <TableHead className="w-[50px] text-center text-[11px] font-bold uppercase tracking-wide text-muted-foreground"><Checkbox checked={regSourceData.length > 0 && regCheckedIds.size === regSourceData.length} onCheckedChange={toggleRegAll} /></TableHead>
                    {regSourceType === "item" && <><TableHead className="w-[120px] text-[11px] font-bold uppercase tracking-wide text-muted-foreground">품목코드</TableHead><TableHead>품목명</TableHead><TableHead className="w-[120px] text-[11px] font-bold uppercase tracking-wide text-muted-foreground">규격</TableHead></>}
                    {regSourceType === "order" && <><TableHead className="w-[110px] text-[11px] font-bold uppercase tracking-wide text-muted-foreground">수주번호</TableHead><TableHead className="w-[100px]">품번</TableHead><TableHead>품목명</TableHead><TableHead className="w-[100px]">규격</TableHead><TableHead className="w-[80px] text-right">수량</TableHead><TableHead className="w-[100px]">납기일</TableHead></>}
                    {regSourceType === "production" && <><TableHead className="w-[110px] text-[11px] font-bold uppercase tracking-wide text-muted-foreground">계획번호</TableHead><TableHead className="w-[100px]">품번</TableHead><TableHead>품목명</TableHead><TableHead className="w-[80px] text-right">계획수량</TableHead><TableHead className="w-[90px]">시작일</TableHead><TableHead className="w-[90px]">완료일</TableHead><TableHead className="w-[100px]">설비</TableHead></>}
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {regSourceData.map((item, idx) => {
                    const id = getRegId(item);
                    const checked = regCheckedIds.has(id);
                    return (
                      <TableRow key={`${regSourceType}-${id}-${idx}`} className={cn("cursor-pointer hover:bg-muted/30", checked && "bg-primary/5")} onClick={() => toggleRegItem(id)}>
                        <TableCell className="text-center" onClick={e => e.stopPropagation()}><Checkbox checked={checked} onCheckedChange={() => toggleRegItem(id)} /></TableCell>
                        {regSourceType === "item" && <><TableCell className="text-[13px] font-medium">{item.item_code}</TableCell><TableCell className="text-sm">{item.item_name}</TableCell><TableCell className="text-[13px]">{item.spec || "-"}</TableCell></>}
                        {regSourceType === "order" && <><TableCell className="text-[13px]">{item.order_no}</TableCell><TableCell className="text-[13px]">{item.item_code}</TableCell><TableCell className="text-sm">{item.item_name}</TableCell><TableCell className="text-[13px]">{item.spec || "-"}</TableCell><TableCell className="text-right text-[13px]">{Number(item.qty || 0).toLocaleString()}</TableCell><TableCell className="text-[13px]">{item.due_date || "-"}</TableCell></>}
                        {regSourceType === "production" && <><TableCell className="text-[13px]">{item.plan_no}</TableCell><TableCell className="text-[13px]">{item.item_code}</TableCell><TableCell className="text-sm">{item.item_name}</TableCell><TableCell className="text-right text-[13px]">{Number(item.plan_qty || 0).toLocaleString()}</TableCell><TableCell className="text-[13px]">{item.start_date ? String(item.start_date).split("T")[0] : "-"}</TableCell><TableCell className="text-[13px]">{item.end_date ? String(item.end_date).split("T")[0] : "-"}</TableCell><TableCell className="text-[13px]">{item.equipment_name || "-"}</TableCell></>}
                      </TableRow>
                    );
                  })}
                </TableBody>
              </Table>
            )}
          </div>

          {regTotalCount > 0 && (
            <div className="px-6 py-2 border-t bg-muted/10 flex items-center justify-between shrink-0">
              <span className="text-xs text-muted-foreground">총 {regTotalCount}건 (선택: {regCheckedIds.size}건)</span>
              <div className="flex items-center gap-1">
                <Button variant="ghost" size="icon" className="h-7 w-7" disabled={regPage <= 1} onClick={() => { const p = regPage - 1; setRegPage(p); fetchRegSource(p); }}><ChevronLeft className="w-3.5 h-3.5" /></Button>
                <span className="text-xs font-medium px-2">{regPage} / {totalRegPages}</span>
                <Button variant="ghost" size="icon" className="h-7 w-7" disabled={regPage >= totalRegPages} onClick={() => { const p = regPage + 1; setRegPage(p); fetchRegSource(p); }}><ChevronRight className="w-3.5 h-3.5" /></Button>
              </div>
            </div>
          )}

          <DialogFooter className="px-6 py-3 border-t shrink-0">
            <Button variant="outline" onClick={() => setIsRegModalOpen(false)}>취소</Button>
            <Button onClick={applyRegistration} disabled={regCheckedIds.size === 0}><ArrowRight className="w-4 h-4 mr-1.5" /> 작업지시 적용</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* ── 2단계: 확인 모달 ── */}
      <Dialog open={isConfirmModalOpen} onOpenChange={setIsConfirmModalOpen}>
        <DialogContent className="max-w-[1100px] w-[95vw] max-h-[90vh] flex flex-col overflow-hidden">
          <DialogHeader>
            <DialogTitle>작업지시 적용 확인</DialogTitle>
            <DialogDescription>기본 정보를 입력하고 '최종 적용' 버튼을 눌러주세요.</DialogDescription>
          </DialogHeader>
          <div className="flex-1 overflow-y-auto">
          <div className="space-y-5">
            <div className="bg-muted/30 border rounded-lg p-5">
              <h4 className="text-[13px] font-bold pb-2 border-b text-foreground">작업지시 기본 정보</h4>
              <div className="grid grid-cols-2 sm:grid-cols-4 gap-4 mt-3">
                <div className="space-y-1"><Label className="text-[11px] font-semibold text-muted-foreground">작업지시번호</Label><Input value={confirmWiNo} readOnly className="h-9 bg-muted cursor-not-allowed font-mono" /></div>
                <div className="space-y-1"><Label className="text-[11px] font-semibold text-muted-foreground">상태</Label>
                  <Select value={confirmStatus} onValueChange={setConfirmStatus}><SelectTrigger className="h-9"><SelectValue /></SelectTrigger><SelectContent><SelectItem value="일반">일반</SelectItem><SelectItem value="긴급">긴급</SelectItem></SelectContent></Select>
                </div>
                <div className="space-y-1"><Label className="text-[11px] font-semibold text-muted-foreground">시작일</Label><Input type="date" value={confirmStartDate} onChange={(e) => setConfirmStartDate(e.target.value)} className="h-9" /></div>
                <div className="space-y-1"><Label className="text-[11px] font-semibold text-muted-foreground">완료예정일</Label><Input type="date" value={confirmEndDate} onChange={(e) => setConfirmEndDate(e.target.value)} className="h-9" /></div>
                <div className="space-y-1"><Label className="text-[11px] font-semibold text-muted-foreground">설비</Label>
                  <Select value={nv(confirmEquipmentId)} onValueChange={v => setConfirmEquipmentId(fromNv(v))}><SelectTrigger className="h-9"><SelectValue placeholder="설비 선택" /></SelectTrigger><SelectContent><SelectItem value="none">선택 안 함</SelectItem>{equipmentOptions.map(eq => <SelectItem key={eq.id} value={eq.id}>{eq.equipment_name}</SelectItem>)}</SelectContent></Select>
                </div>
                <div className="space-y-1"><Label className="text-[11px] font-semibold text-muted-foreground">작업조</Label>
                  <Select value={nv(confirmWorkTeam)} onValueChange={v => setConfirmWorkTeam(fromNv(v))}><SelectTrigger className="h-9"><SelectValue placeholder="작업조" /></SelectTrigger><SelectContent><SelectItem value="none">선택 안 함</SelectItem><SelectItem value="주간">주간</SelectItem><SelectItem value="야간">야간</SelectItem></SelectContent></Select>
                </div>
                <div className="space-y-1"><Label className="text-[11px] font-semibold text-muted-foreground">작업자</Label>
                  <WorkerCombobox value={confirmWorker} onChange={setConfirmWorker} open={confirmWorkerOpen} onOpenChange={setConfirmWorkerOpen} />
                </div>
                <div className="space-y-1"><Label className="text-[11px] font-semibold text-muted-foreground">비고</Label><Input className="h-9" placeholder="비고를 입력해주세요" /></div>
              </div>
            </div>
            <div className="border rounded-lg p-5">
              <h4 className="text-[13px] font-bold pb-2 border-b text-foreground mb-3">품목 목록</h4>
              <div className="overflow-auto">
                <Table>
                  <TableHeader className="sticky top-0 z-10">
                    <TableRow className="bg-muted hover:bg-muted">
                      <TableHead className="w-[50px] text-[11px] font-bold uppercase tracking-wide text-muted-foreground">순번</TableHead>
                      <TableHead className="w-[110px] text-[11px] font-bold uppercase tracking-wide text-muted-foreground">품목코드</TableHead>
                      <TableHead className="text-[11px] font-bold uppercase tracking-wide text-muted-foreground">품목명</TableHead>
                      <TableHead className="w-[80px] text-[11px] font-bold uppercase tracking-wide text-muted-foreground">규격</TableHead>
                      <TableHead className="w-[90px] text-[11px] font-bold uppercase tracking-wide text-muted-foreground">수량</TableHead>
                      <TableHead className="w-[180px] text-[11px] font-bold uppercase tracking-wide text-muted-foreground">라우팅</TableHead>
                      <TableHead className="text-[11px] font-bold uppercase tracking-wide text-muted-foreground">비고</TableHead>
                      <TableHead className="w-[40px]" />
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {confirmItems.map((item, idx) => (
                      <TableRow key={idx}>
                        <TableCell className="text-[13px] text-center">{idx + 1}</TableCell>
                        <TableCell className="text-[13px] font-medium">{item.itemCode}</TableCell>
                        <TableCell className="text-sm">{item.itemName || item.itemCode}</TableCell>
                        <TableCell className="text-[13px]">{item.spec || "-"}</TableCell>
                        <TableCell><Input type="number" className="h-7 text-[13px] w-20" value={item.qty} onChange={e => setConfirmItems(prev => prev.map((it, i) => i === idx ? { ...it, qty: Number(e.target.value) } : it))} /></TableCell>
                        <TableCell>
                          <Select
                            value={nv(item.routing || "")}
                            onValueChange={v => {
                              const val = fromNv(v);
                              setConfirmItems(prev => prev.map((it, i) => i === idx ? { ...it, routing: val } : it));
                            }}
                          >
                            <SelectTrigger className="h-7 text-xs"><SelectValue placeholder="라우팅" /></SelectTrigger>
                            <SelectContent>
                              <SelectItem value="none">선택 안 함</SelectItem>
                              {(item.routingOptions || []).map((rv: RoutingVersionData) => (
                                <SelectItem key={rv.id} value={rv.id}>
                                  {rv.version_name || "라우팅"} {rv.is_default ? "(기본)" : ""} - {rv.processes.length}공정
                                </SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                        </TableCell>
                        <TableCell><Input className="h-7 text-[13px]" value={item.remark} placeholder="비고" onChange={e => setConfirmItems(prev => prev.map((it, i) => i === idx ? { ...it, remark: e.target.value } : it))} /></TableCell>
                        <TableCell><Button variant="ghost" size="icon" className="h-6 w-6" onClick={() => setConfirmItems(prev => prev.filter((_, i) => i !== idx))}><X className="w-3 h-3 text-destructive" /></Button></TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            </div>
          </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => { setIsConfirmModalOpen(false); setIsRegModalOpen(true); }}><ChevronLeft className="w-4 h-4 mr-1" /> 이전</Button>
            <Button variant="outline" onClick={() => setIsConfirmModalOpen(false)}>취소</Button>
            <Button onClick={finalizeRegistration} disabled={saving}>{saving ? <Loader2 className="w-4 h-4 mr-1.5 animate-spin" /> : <CheckCircle2 className="w-4 h-4 mr-1.5" />} 최종 적용</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* ── 수정 모달 ── */}
      <Dialog open={isEditModalOpen} onOpenChange={(v) => { if (!v && wsModalOpen) return; setIsEditModalOpen(v); }}>
        <DialogContent className="max-w-[1100px] w-[95vw] max-h-[90vh] flex flex-col overflow-hidden">
          <DialogHeader>
            <DialogTitle>{`작업지시 관리 - ${editOrder?.work_instruction_no || ""}`}</DialogTitle>
            <DialogDescription>품목을 추가/삭제하고 정보를 수정해주세요.</DialogDescription>
          </DialogHeader>
          <div className="flex-1 overflow-y-auto">
          <div className="space-y-5">
            <div className="bg-muted/30 border rounded-lg p-5">
              <h4 className="text-[13px] font-bold pb-2 border-b text-foreground">기본 정보</h4>
              <div className="grid grid-cols-2 sm:grid-cols-4 gap-4 mt-3">
                <div className="space-y-1"><Label className="text-[11px] font-semibold text-muted-foreground">상태</Label><Select value={editStatus} onValueChange={setEditStatus}><SelectTrigger className="h-9"><SelectValue /></SelectTrigger><SelectContent><SelectItem value="일반">일반</SelectItem><SelectItem value="긴급">긴급</SelectItem></SelectContent></Select></div>
                <div className="space-y-1"><Label className="text-[11px] font-semibold text-muted-foreground">시작일</Label><Input type="date" value={editStartDate} onChange={(e) => setEditStartDate(e.target.value)} className="h-9" /></div>
                <div className="space-y-1"><Label className="text-[11px] font-semibold text-muted-foreground">완료예정일</Label><Input type="date" value={editEndDate} onChange={(e) => setEditEndDate(e.target.value)} className="h-9" /></div>
                <div className="space-y-1"><Label className="text-[11px] font-semibold text-muted-foreground">설비</Label><Select value={nv(editEquipmentId)} onValueChange={v => setEditEquipmentId(fromNv(v))}><SelectTrigger className="h-9"><SelectValue placeholder="설비 선택" /></SelectTrigger><SelectContent><SelectItem value="none">선택 안 함</SelectItem>{equipmentOptions.map(eq => <SelectItem key={eq.id} value={eq.id}>{eq.equipment_name}</SelectItem>)}</SelectContent></Select></div>
                <div className="space-y-1"><Label className="text-[11px] font-semibold text-muted-foreground">작업조</Label><Select value={nv(editWorkTeam)} onValueChange={v => setEditWorkTeam(fromNv(v))}><SelectTrigger className="h-9"><SelectValue placeholder="작업조" /></SelectTrigger><SelectContent><SelectItem value="none">선택 안 함</SelectItem><SelectItem value="주간">주간</SelectItem><SelectItem value="야간">야간</SelectItem></SelectContent></Select></div>
                <div className="space-y-1"><Label className="text-[11px] font-semibold text-muted-foreground">작업자</Label>
                  <WorkerCombobox value={editWorker} onChange={setEditWorker} open={editWorkerOpen} onOpenChange={setEditWorkerOpen} />
                </div>
                <div className="space-y-1 col-span-2"><Label className="text-[11px] font-semibold text-muted-foreground">비고</Label><Input value={editRemark} onChange={e => setEditRemark(e.target.value)} className="h-9" placeholder="비고를 입력해주세요" /></div>
              </div>
            </div>

            {/* 품목 테이블 — 라우팅/공정작업기준을 품목별로 표시 */}
            <div className="border rounded-lg overflow-hidden">
              <div className="flex items-center justify-between px-4 py-2.5 bg-muted/30 border-b">
                <span className="text-[13px] font-bold text-foreground">작업지시 항목</span>
                <span className="text-[11px] font-semibold text-primary bg-primary/8 border border-primary/15 px-2 py-0.5 rounded-full font-mono">{editItems.length}건</span>
              </div>
              <div className="overflow-auto">
                <Table>
                  <TableHeader className="sticky top-0 z-10">
                    <TableRow className="bg-muted hover:bg-muted">
                      <TableHead className="w-[50px] text-[11px] font-bold uppercase tracking-wide text-muted-foreground">순번</TableHead>
                      <TableHead className="w-[110px] text-[11px] font-bold uppercase tracking-wide text-muted-foreground">품목코드</TableHead>
                      <TableHead className="text-[11px] font-bold uppercase tracking-wide text-muted-foreground">품목명</TableHead>
                      <TableHead className="w-[80px] text-[11px] font-bold uppercase tracking-wide text-muted-foreground">규격</TableHead>
                      <TableHead className="w-[90px] text-right text-[11px] font-bold uppercase tracking-wide text-muted-foreground">수량</TableHead>
                      <TableHead className="w-[180px] text-[11px] font-bold uppercase tracking-wide text-muted-foreground">라우팅</TableHead>
                      <TableHead className="w-[100px] text-[11px] font-bold uppercase tracking-wide text-muted-foreground">공정작업기준</TableHead>
                      <TableHead className="text-[11px] font-bold uppercase tracking-wide text-muted-foreground">비고</TableHead>
                      <TableHead className="w-[40px]" />
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {editItems.length === 0 ? (
                      <TableRow><TableCell colSpan={9} className="text-center py-8 text-sm text-muted-foreground">등록된 품목이 없어요</TableCell></TableRow>
                    ) : editItems.map((item, idx) => (
                      <TableRow key={idx}>
                        <TableCell className="text-[13px] text-center">{idx + 1}</TableCell>
                        <TableCell className="text-[13px] font-medium">{item.itemCode}</TableCell>
                        <TableCell className="text-[13px] max-w-[150px] truncate" title={item.itemName}>{item.itemName || "-"}</TableCell>
                        <TableCell className="text-[13px] truncate" title={item.spec}>{item.spec || "-"}</TableCell>
                        <TableCell className="text-right"><Input type="number" className="h-7 text-[13px] w-20 ml-auto" value={item.qty} onChange={e => setEditItems(prev => prev.map((it, i) => i === idx ? { ...it, qty: Number(e.target.value) } : it))} /></TableCell>
                        <TableCell>
                          <Select
                            value={nv(item.routing || "")}
                            onValueChange={v => {
                              const val = fromNv(v);
                              setEditItems(prev => prev.map((it, i) => i === idx ? { ...it, routing: val } : it));
                            }}
                          >
                            <SelectTrigger className="h-7 text-xs"><SelectValue placeholder="라우팅" /></SelectTrigger>
                            <SelectContent>
                              <SelectItem value="none">선택 안 함</SelectItem>
                              {(item.routingOptions || []).map((rv: RoutingVersionData) => (
                                <SelectItem key={rv.id} value={rv.id}>
                                  {rv.version_name || "라우팅"} {rv.is_default ? "(기본)" : ""} - {rv.processes.length}공정
                                </SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                        </TableCell>
                        <TableCell>
                          <Button
                            variant="ghost"
                            size="sm"
                            className="h-7 text-xs"
                            disabled={!item.routing}
                            onClick={() => {
                              if (!editOrder || !item.routing) return;
                              const rv = (item.routingOptions || []).find((r: RoutingVersionData) => r.id === item.routing);
                              openWorkStandardModal(
                                editOrder.work_instruction_no,
                                item.routing,
                                rv?.version_name || "",
                                item.itemName || item.itemCode || "",
                                item.itemCode || ""
                              );
                            }}
                          >
                            <ClipboardCheck className="w-3 h-3 mr-1" /> 수정
                          </Button>
                        </TableCell>
                        <TableCell><Input className="h-7 text-[13px]" value={item.remark} placeholder="비고" onChange={e => setEditItems(prev => prev.map((it, i) => i === idx ? { ...it, remark: e.target.value } : it))} /></TableCell>
                        <TableCell><Button variant="ghost" size="icon" className="h-6 w-6" onClick={() => setEditItems(prev => prev.filter((_, i) => i !== idx))}><X className="w-3 h-3 text-destructive" /></Button></TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
              {editItems.length > 0 && (
                <div className="px-4 py-2.5 border-t bg-muted/30 flex items-center justify-between">
                  <span className="text-[13px] font-bold text-foreground">총 수량</span>
                  <span className="text-lg font-bold font-mono text-primary">{editItems.reduce((s, i) => s + i.qty, 0).toLocaleString()} EA</span>
                </div>
              )}
            </div>
          </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setIsEditModalOpen(false)}>취소</Button>
            <Button onClick={saveEdit} disabled={editSaving}>{editSaving ? <Loader2 className="w-4 h-4 mr-1.5 animate-spin" /> : <Save className="w-4 h-4 mr-1.5" />} 저장</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 공정작업기준 수정 모달 */}
      <WorkStandardEditModal
        open={wsModalOpen}
        onClose={() => setWsModalOpen(false)}
        workInstructionNo={wsModalWiNo}
        routingVersionId={wsModalRoutingId}
        routingName={wsModalRoutingName}
        itemName={wsModalItemName}
        itemCode={wsModalItemCode}
      />

      <TableSettingsModal
        open={ts.open}
        onOpenChange={ts.setOpen}
        tableName={ts.tableName}
        settingsId={ts.settingsId}
        defaultVisibleKeys={ts.defaultVisibleKeys}
        onSave={ts.applySettings}
      />
    </div>
  );
}
