"use client";

import React, { useState, useEffect, useCallback, useMemo } from "react";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogDescription } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Checkbox } from "@/components/ui/checkbox";
import { cn } from "@/lib/utils";
import {
  Loader2, Save, RotateCcw, Plus, Trash2, Pencil, ClipboardCheck,
  GripVertical, AlertCircle, ClipboardList,
} from "lucide-react";
import { toast } from "sonner";
import {
  getWIWorkStandard, copyWorkStandard, saveWIWorkStandard, resetWIWorkStandard,
  WIWorkItem, WIWorkItemDetail, WIWorkStandardProcess,
} from "@/lib/api/workInstruction";

interface WorkStandardEditModalProps {
  open: boolean;
  onClose: () => void;
  workInstructionNo: string;
  routingVersionId: string;
  routingName: string;
  itemName: string;
  itemCode: string;
}

const PHASES = [
  { key: "PRE", label: "작업 전 (Pre-Work)" },
  { key: "IN", label: "작업 중 (In-Work)" },
  { key: "POST", label: "작업 후 (Post-Work)" },
];

const DETAIL_TYPES = [
  { value: "checklist", label: "체크리스트" },
  { value: "inspection", label: "검사항목" },
  { value: "procedure", label: "작업절차" },
  { value: "input", label: "직접입력" },
  { value: "lookup", label: "문서참조" },
  { value: "equip_inspection", label: "설비점검" },
  { value: "equip_condition", label: "설비조건" },
  { value: "production_result", label: "실적등록" },
  { value: "material_input", label: "자재투입" },
];

const INPUT_TYPES = [
  { value: "text", label: "텍스트" },
  { value: "number", label: "숫자" },
  { value: "date", label: "날짜" },
  { value: "textarea", label: "장문 텍스트" },
];

const UNIT_OPTIONS = [
  "mm", "cm", "m", "μm", "℃", "℉", "bar", "Pa", "MPa", "psi",
  "RPM", "kg", "N", "N·m", "m/s", "m/min", "A", "V", "kW", "%",
  "L/min", "Hz", "dB", "ea", "g", "mg", "ml", "L",
];

const getDetailTypeLabel = (type: string) =>
  DETAIL_TYPES.find(d => d.value === type)?.label || type;

const getContentSummary = (detail: WIWorkItemDetail): string => {
  const type = detail.detail_type;
  if (type === "inspection") {
    const parts = [detail.content];
    if (detail.inspection_method) parts.push(`[${detail.inspection_method}]`);
    if (detail.base_value) {
      parts.push(`(기준: ${detail.base_value}${detail.tolerance ? ` ±${detail.tolerance}` : ""} ${detail.unit || ""})`);
    }
    return parts.join(" ");
  }
  if (type === "procedure" && detail.duration_minutes) {
    return `${detail.content} (${detail.duration_minutes}분)`;
  }
  if (type === "input" && detail.input_type) {
    const typeMap: Record<string, string> = { text: "텍스트", number: "숫자", date: "날짜", textarea: "장문" };
    return `${detail.content} [${typeMap[detail.input_type] || detail.input_type}]`;
  }
  if (type === "lookup") return "품목 등록 문서 (자동 연동)";
  if (type === "equip_inspection") return detail.content || "설비점검";
  if (type === "equip_condition") {
    const parts = [detail.content];
    if (detail.condition_base_value) {
      parts.push(`(기준: ${detail.condition_base_value}${detail.condition_tolerance ? ` ±${detail.condition_tolerance}` : ""} ${detail.condition_unit || ""})`);
    }
    return parts.join(" ");
  }
  if (type === "production_result") return "작업수량 / 불량수량 / 양품수량";
  if (type === "material_input") return "BOM 구성 자재 (자동 연동)";
  return detail.content || "-";
};

export function WorkStandardEditModal({
  open,
  onClose,
  workInstructionNo,
  routingVersionId,
  routingName,
  itemName,
  itemCode,
}: WorkStandardEditModalProps) {
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [processes, setProcesses] = useState<WIWorkStandardProcess[]>([]);
  const [isCustom, setIsCustom] = useState(false);
  const [selectedProcessIdx, setSelectedProcessIdx] = useState(0);
  const [selectedWorkItemIdByPhase, setSelectedWorkItemIdByPhase] = useState<Record<string, string | null>>({});
  const [dirty, setDirty] = useState(false);

  // 작업항목 추가/수정 모달
  const [addItemOpen, setAddItemOpen] = useState(false);
  const [addItemPhase, setAddItemPhase] = useState("PRE");
  const [addItemTitle, setAddItemTitle] = useState("");
  const [addItemRequired, setAddItemRequired] = useState("Y");
  const [editingWorkItem, setEditingWorkItem] = useState<WIWorkItem | null>(null);

  // 상세 추가/수정 모달
  const [detailModalOpen, setDetailModalOpen] = useState(false);
  const [detailModalMode, setDetailModalMode] = useState<"add" | "edit">("add");
  const [detailModalPhase, setDetailModalPhase] = useState("PRE");
  const [detailFormData, setDetailFormData] = useState<Partial<WIWorkItemDetail>>({});
  const [editingDetail, setEditingDetail] = useState<WIWorkItemDetail | null>(null);

  // 데이터 로드
  const loadData = useCallback(async () => {
    if (!workInstructionNo || !routingVersionId) return;
    setLoading(true);
    try {
      const res = await getWIWorkStandard(workInstructionNo, routingVersionId);
      if (res.success && res.data) {
        setProcesses(res.data.processes);
        setIsCustom(res.data.isCustom);
        setSelectedProcessIdx(0);
        setSelectedWorkItemIdByPhase({});
        setDirty(false);
      }
    } catch (err) {
      console.error("공정작업기준 로드 실패", err);
    } finally {
      setLoading(false);
    }
  }, [workInstructionNo, routingVersionId]);

  useEffect(() => {
    if (open) loadData();
  }, [open, loadData]);

  const currentProcess = processes[selectedProcessIdx] || null;

  // Phase별 작업항목 그룹핑 (MAIN을 IN으로 매핑)
  const workItemsByPhase = useMemo(() => {
    if (!currentProcess) return {};
    const map: Record<string, WIWorkItem[]> = {};
    for (const phase of PHASES) {
      map[phase.key] = currentProcess.workItems.filter(
        wi => wi.work_phase === phase.key || (phase.key === "IN" && wi.work_phase === "MAIN")
      );
    }
    return map;
  }, [currentProcess]);

  // 커스텀 복사 확인 후 수정
  const ensureCustom = useCallback(async () => {
    if (isCustom) return true;
    try {
      const res = await copyWorkStandard(workInstructionNo, routingVersionId);
      if (res.success) {
        await loadData();
        setIsCustom(true);
        return true;
      }
    } catch (err) {
      toast.error("원본 복사에 실패했습니다");
    }
    return false;
  }, [isCustom, workInstructionNo, routingVersionId, loadData]);

  // 작업항목 추가 모달 열기
  const openAddWorkItem = useCallback((phaseKey: string) => {
    setAddItemPhase(phaseKey);
    setAddItemTitle("");
    setAddItemRequired("Y");
    setEditingWorkItem(null);
    setAddItemOpen(true);
  }, []);

  // 작업항목 수정 모달 열기
  const openEditWorkItem = useCallback((item: WIWorkItem) => {
    setAddItemPhase(item.work_phase);
    setAddItemTitle(item.title);
    setAddItemRequired(item.is_required);
    setEditingWorkItem(item);
    setAddItemOpen(true);
  }, []);

  // 작업항목 추가/수정 처리
  const handleSaveWorkItem = useCallback(async () => {
    if (!addItemTitle.trim()) { toast.error("제목을 입력하세요"); return; }
    const ok = await ensureCustom();
    if (!ok || !currentProcess) return;

    if (editingWorkItem) {
      // 수정
      setProcesses(prev => {
        const next = [...prev];
        const workItems = [...next[selectedProcessIdx].workItems];
        const idx = workItems.findIndex(wi => wi.id === editingWorkItem.id);
        if (idx >= 0) {
          workItems[idx] = { ...workItems[idx], title: addItemTitle.trim(), is_required: addItemRequired };
        }
        next[selectedProcessIdx] = { ...next[selectedProcessIdx], workItems };
        return next;
      });
    } else {
      // 추가
      const phaseKey = addItemPhase === "IN" ? "IN" : addItemPhase;
      const phaseItems = currentProcess.workItems.filter(
        wi => wi.work_phase === phaseKey || (phaseKey === "IN" && wi.work_phase === "MAIN")
      );
      const newItem: WIWorkItem = {
        id: `temp-${Date.now()}`,
        routing_detail_id: currentProcess.routing_detail_id,
        work_phase: phaseKey,
        title: addItemTitle.trim(),
        is_required: addItemRequired,
        sort_order: phaseItems.length + 1,
        details: [],
      };

      setProcesses(prev => {
        const next = [...prev];
        next[selectedProcessIdx] = {
          ...next[selectedProcessIdx],
          workItems: [...next[selectedProcessIdx].workItems, newItem],
        };
        return next;
      });

      setSelectedWorkItemIdByPhase(prev => ({ ...prev, [addItemPhase]: newItem.id! }));
    }

    setAddItemOpen(false);
    setDirty(true);
  }, [addItemTitle, addItemRequired, addItemPhase, ensureCustom, currentProcess, selectedProcessIdx, editingWorkItem]);

  // 작업항목 삭제
  const handleDeleteWorkItem = useCallback(async (id: string, phaseKey: string) => {
    const ok = await ensureCustom();
    if (!ok) return;

    setProcesses(prev => {
      const next = [...prev];
      next[selectedProcessIdx] = {
        ...next[selectedProcessIdx],
        workItems: next[selectedProcessIdx].workItems.filter(wi => wi.id !== id),
      };
      return next;
    });
    if (selectedWorkItemIdByPhase[phaseKey] === id) {
      setSelectedWorkItemIdByPhase(prev => ({ ...prev, [phaseKey]: null }));
    }
    setDirty(true);
  }, [ensureCustom, selectedProcessIdx, selectedWorkItemIdByPhase]);

  // 상세 추가 모달 열기
  const openAddDetail = useCallback((phaseKey: string) => {
    setDetailModalPhase(phaseKey);
    setDetailModalMode("add");
    setEditingDetail(null);
    setDetailFormData({
      detail_type: DETAIL_TYPES[0].value,
      content: "",
      is_required: "Y",
    });
    setDetailModalOpen(true);
  }, []);

  // 상세 수정 모달 열기
  const openEditDetail = useCallback((detail: WIWorkItemDetail, phaseKey: string) => {
    setDetailModalPhase(phaseKey);
    setDetailModalMode("edit");
    setEditingDetail(detail);
    setDetailFormData({ ...detail });
    setDetailModalOpen(true);
  }, []);

  // 상세 추가/수정 처리
  const handleSaveDetail = useCallback(async () => {
    const type = detailFormData.detail_type || "";
    if (!type) return;

    // 유효성 검사 (내용이 필요한 유형)
    const needsContent = ["checklist", "procedure", "input", "equip_condition"];
    if (needsContent.includes(type) && !detailFormData.content?.trim()) {
      toast.error("내용을 입력하세요");
      return;
    }
    if (type === "inspection" && !detailFormData.content?.trim()) {
      toast.error("검사 항목명을 입력하세요");
      return;
    }

    const workItemId = selectedWorkItemIdByPhase[detailModalPhase];
    if (!workItemId) return;
    const ok = await ensureCustom();
    if (!ok) return;

    // content 자동 설정 (UI에서 직접 입력이 없는 유형들)
    const submitData = { ...detailFormData };
    if (type === "lookup") submitData.content = submitData.content || "품목 등록 문서 (자동 연동)";
    if (type === "equip_inspection") submitData.content = submitData.content || "설비점검";
    if (type === "production_result") submitData.content = submitData.content || "작업수량 / 불량수량 / 양품수량";
    if (type === "material_input") submitData.content = submitData.content || "BOM 구성 자재 (자동 연동)";

    setProcesses(prev => {
      const next = [...prev];
      const workItems = [...next[selectedProcessIdx].workItems];
      const wiIdx = workItems.findIndex(wi => wi.id === workItemId);
      if (wiIdx < 0) return prev;

      if (detailModalMode === "edit" && editingDetail) {
        // 수정
        const details = (workItems[wiIdx].details || []).map(d =>
          d.id === editingDetail.id ? { ...d, ...submitData } : d
        );
        workItems[wiIdx] = { ...workItems[wiIdx], details };
      } else {
        // 추가
        const newDetail: WIWorkItemDetail = {
          ...submitData,
          id: `temp-detail-${Date.now()}`,
          work_item_id: workItemId,
          sort_order: (workItems[wiIdx].details?.length || 0) + 1,
        };
        workItems[wiIdx] = {
          ...workItems[wiIdx],
          details: [...(workItems[wiIdx].details || []), newDetail],
          detail_count: (workItems[wiIdx].detail_count || 0) + 1,
        };
      }
      next[selectedProcessIdx] = { ...next[selectedProcessIdx], workItems };
      return next;
    });

    setDetailModalOpen(false);
    setDirty(true);
  }, [detailFormData, detailModalPhase, detailModalMode, editingDetail, selectedWorkItemIdByPhase, ensureCustom, selectedProcessIdx]);

  // 상세 삭제
  const handleDeleteDetail = useCallback(async (detailId: string, phaseKey: string) => {
    const workItemId = selectedWorkItemIdByPhase[phaseKey];
    if (!workItemId) return;
    const ok = await ensureCustom();
    if (!ok) return;

    setProcesses(prev => {
      const next = [...prev];
      const workItems = [...next[selectedProcessIdx].workItems];
      const wiIdx = workItems.findIndex(wi => wi.id === workItemId);
      if (wiIdx >= 0) {
        workItems[wiIdx] = {
          ...workItems[wiIdx],
          details: (workItems[wiIdx].details || []).filter(d => d.id !== detailId),
          detail_count: Math.max(0, (workItems[wiIdx].detail_count || 1) - 1),
        };
      }
      next[selectedProcessIdx] = { ...next[selectedProcessIdx], workItems };
      return next;
    });
    setDirty(true);
  }, [selectedWorkItemIdByPhase, ensureCustom, selectedProcessIdx]);

  // 저장
  const handleSave = useCallback(async () => {
    if (!currentProcess) return;
    setSaving(true);
    try {
      const ok = await ensureCustom();
      if (!ok) return;

      const res = await saveWIWorkStandard(
        workInstructionNo,
        currentProcess.routing_detail_id,
        currentProcess.workItems
      );
      if (res.success) {
        toast.success("공정작업기준이 저장되었습니다");
        setDirty(false);
        await loadData();
      } else {
        toast.error("저장에 실패했습니다");
      }
    } catch (err) {
      toast.error("저장 중 오류가 발생했습니다");
    } finally {
      setSaving(false);
    }
  }, [currentProcess, ensureCustom, workInstructionNo, loadData]);

  // 원본으로 초기화
  const handleReset = useCallback(async () => {
    if (!confirm("커스터마이징한 내용을 모두 삭제하고 원본으로 되돌리시겠습니까?")) return;
    try {
      const res = await resetWIWorkStandard(workInstructionNo);
      if (res.success) {
        toast.success("원본으로 초기화되었습니다");
        await loadData();
      }
    } catch (err) {
      toast.error("초기화에 실패했습니다");
    }
  }, [workInstructionNo, loadData]);

  const updateDetailField = (field: string, value: unknown) => {
    setDetailFormData(prev => ({ ...prev, [field]: value }));
  };

  return (
    <Dialog open={open} onOpenChange={v => { if (!v) onClose(); }}>
      <DialogContent className="max-w-[95vw] sm:max-w-[1200px] h-[85vh] 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">
            <ClipboardCheck className="w-4 h-4" />
            공정작업기준 수정 - {itemName}
            {routingName && <Badge variant="secondary" className="text-xs ml-2">{routingName}</Badge>}
            {isCustom && <Badge variant="outline" className="text-xs ml-1 border-amber-300 text-amber-700">커스텀</Badge>}
          </DialogTitle>
          <DialogDescription className="text-xs">
            작업지시 [{workInstructionNo}]에 대한 공정작업기준을 수정합니다. 원본에 영향을 주지 않습니다.
          </DialogDescription>
        </DialogHeader>

        {loading ? (
          <div className="flex-1 flex items-center justify-center">
            <Loader2 className="w-8 h-8 animate-spin text-muted-foreground" />
          </div>
        ) : processes.length === 0 ? (
          <div className="flex-1 flex flex-col items-center justify-center text-muted-foreground">
            <AlertCircle className="w-10 h-10 mb-3 opacity-30" />
            <p className="text-sm">라우팅에 등록된 공정이 없습니다</p>
          </div>
        ) : (
          <div className="flex-1 flex flex-col overflow-hidden">
            {/* 공정 탭 */}
            <div className="flex items-center gap-1 px-4 py-2 border-b bg-muted/30 overflow-x-auto shrink-0">
              {processes.map((proc, idx) => (
                <Button
                  key={proc.routing_detail_id}
                  variant={selectedProcessIdx === idx ? "default" : "ghost"}
                  size="sm"
                  className={cn("text-xs shrink-0 h-8", selectedProcessIdx === idx && "shadow-sm")}
                  onClick={() => {
                    setSelectedProcessIdx(idx);
                    setSelectedWorkItemIdByPhase({});
                  }}
                >
                  <span className="mr-1.5 font-mono text-[10px] opacity-70">{proc.seq_no}.</span>
                  {proc.process_name}
                  {proc.workItems.length > 0 && (
                    <Badge variant="secondary" className="ml-1.5 text-[10px] h-4 px-1">{proc.workItems.length}</Badge>
                  )}
                </Button>
              ))}
            </div>

            {/* Phase별 세로 섹션 */}
            <div className="flex-1 overflow-y-auto space-y-4 p-4">
              {PHASES.map(phase => {
                const phaseItems = workItemsByPhase[phase.key] || [];
                const selectedWiId = selectedWorkItemIdByPhase[phase.key] || null;
                const selectedWi = phaseItems.find(wi => wi.id === selectedWiId) || null;

                return (
                  <div key={phase.key} className="rounded-lg border bg-card">
                    {/* 섹션 헤더 */}
                    <div className="flex items-center justify-between border-b px-4 py-2.5">
                      <div className="flex items-center gap-2">
                        <h3 className="text-sm font-semibold">{phase.label}</h3>
                        <Badge variant="secondary" className="h-5 rounded-full px-2 text-[10px]">
                          {phaseItems.length}개 항목
                        </Badge>
                      </div>
                      <Button
                        variant="outline"
                        size="sm"
                        className="h-7 gap-1 text-xs"
                        onClick={() => openAddWorkItem(phase.key)}
                      >
                        <Plus className="h-3 w-3" />
                        작업항목 추가
                      </Button>
                    </div>

                    {/* 좌우 분할 */}
                    <div className="flex min-h-[140px]">
                      {/* 좌측: 240px 작업항목 카드 */}
                      <div className="w-[240px] shrink-0 border-r p-2">
                        {phaseItems.length === 0 ? (
                          <div className="flex flex-col items-center justify-center py-6 text-center">
                            <ClipboardList className="mb-1 h-6 w-6 text-muted-foreground/40" />
                            <p className="text-[11px] text-muted-foreground">등록된 항목이 없습니다</p>
                          </div>
                        ) : (
                          <div className="space-y-1.5">
                            {phaseItems.map(item => (
                              <div
                                key={item.id}
                                onClick={() => setSelectedWorkItemIdByPhase(prev => ({ ...prev, [phase.key]: item.id! }))}
                                className={cn(
                                  "group flex cursor-pointer items-start gap-2 rounded-lg border p-3 transition-all",
                                  "hover:border-primary/30 hover:shadow-sm",
                                  selectedWiId === item.id
                                    ? "border-primary bg-primary/5 shadow-sm"
                                    : "border-border bg-card"
                                )}
                              >
                                <GripVertical className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground/50" />
                                <div className="min-w-0 flex-1">
                                  <div className="flex items-center gap-2">
                                    <span className="truncate text-sm font-medium">{item.title}</span>
                                  </div>
                                  <div className="mt-1 flex items-center gap-2">
                                    <Badge variant="secondary" className="h-5 px-1.5 text-[10px] font-normal">
                                      {item.details?.length || item.detail_count || 0}개
                                    </Badge>
                                    <Badge
                                      variant={item.is_required === "Y" ? "default" : "outline"}
                                      className="h-5 px-1.5 text-[10px] font-normal"
                                    >
                                      {item.is_required === "Y" ? "필수" : "선택"}
                                    </Badge>
                                  </div>
                                </div>
                                <div className="flex shrink-0 gap-0.5 opacity-0 transition-opacity group-hover:opacity-100">
                                  <Button
                                    variant="ghost" size="icon" className="h-6 w-6"
                                    onClick={e => { e.stopPropagation(); openEditWorkItem(item); }}
                                  >
                                    <Pencil className="h-3 w-3" />
                                  </Button>
                                  <Button
                                    variant="ghost" size="icon" className="h-6 w-6 text-destructive hover:text-destructive"
                                    onClick={e => { e.stopPropagation(); handleDeleteWorkItem(item.id!, phase.key); }}
                                  >
                                    <Trash2 className="h-3 w-3" />
                                  </Button>
                                </div>
                              </div>
                            ))}
                          </div>
                        )}
                      </div>

                      {/* 우측: 상세 테이블 */}
                      <div className="flex-1 flex flex-col">
                        {!selectedWi ? (
                          <div className="flex h-full flex-col items-center justify-center text-center">
                            <p className="text-sm text-muted-foreground">왼쪽에서 항목을 선택하세요</p>
                          </div>
                        ) : (
                          <>
                            {/* 상세 헤더 */}
                            <div className="flex items-center justify-between border-b px-4 py-2">
                              <div className="flex items-center gap-2">
                                <span className="text-sm font-semibold">{selectedWi.title}</span>
                                <Badge variant="secondary" className="text-[10px]">
                                  {selectedWi.details?.length || 0}개
                                </Badge>
                              </div>
                              <Button
                                variant="outline" size="sm" className="h-7 gap-1 text-xs"
                                onClick={() => openAddDetail(phase.key)}
                              >
                                <Plus className="h-3 w-3" />
                                상세 추가
                              </Button>
                            </div>

                            {/* 테이블 */}
                            <div className="flex-1 overflow-y-auto">
                              <table className="w-full text-xs">
                                <thead className="sticky top-0 bg-muted/50">
                                  <tr className="border-b">
                                    <th className="w-12 px-2 py-2 text-center font-medium text-muted-foreground">순서</th>
                                    <th className="w-20 px-2 py-2 text-left font-medium text-muted-foreground">유형</th>
                                    <th className="px-2 py-2 text-left font-medium text-muted-foreground">내용</th>
                                    <th className="w-14 px-2 py-2 text-center font-medium text-muted-foreground">필수</th>
                                    <th className="w-16 px-2 py-2 text-center font-medium text-muted-foreground">관리</th>
                                  </tr>
                                </thead>
                                <tbody>
                                  {(selectedWi.details || []).map((detail, idx) => (
                                    <tr key={detail.id || idx} className="border-b transition-colors hover:bg-muted/30">
                                      <td className="px-2 py-1.5 text-center text-muted-foreground">{idx + 1}</td>
                                      <td className="px-2 py-1.5">
                                        <Badge variant="outline" className="text-[10px] font-normal">
                                          {getDetailTypeLabel(detail.detail_type || "checklist")}
                                        </Badge>
                                      </td>
                                      <td className="px-2 py-1.5">{getContentSummary(detail)}</td>
                                      <td className="px-2 py-1.5 text-center">
                                        <Badge
                                          variant={detail.is_required === "Y" ? "default" : "secondary"}
                                          className="text-[10px] font-normal"
                                        >
                                          {detail.is_required === "Y" ? "필수" : "선택"}
                                        </Badge>
                                      </td>
                                      <td className="px-2 py-1.5 text-center">
                                        <div className="flex justify-center gap-0.5">
                                          <Button
                                            variant="ghost" size="icon" className="h-6 w-6"
                                            onClick={() => openEditDetail(detail, phase.key)}
                                          >
                                            <Pencil className="h-3 w-3" />
                                          </Button>
                                          <Button
                                            variant="ghost" size="icon" className="h-6 w-6 text-destructive hover:text-destructive"
                                            onClick={() => handleDeleteDetail(detail.id!, phase.key)}
                                          >
                                            <Trash2 className="h-3 w-3" />
                                          </Button>
                                        </div>
                                      </td>
                                    </tr>
                                  ))}
                                </tbody>
                              </table>

                              {(!selectedWi.details || selectedWi.details.length === 0) && (
                                <div className="flex flex-col items-center justify-center py-8 text-center">
                                  <p className="text-xs text-muted-foreground">
                                    상세 항목이 없습니다. &quot;상세 추가&quot; 버튼을 클릭하여 추가하세요.
                                  </p>
                                </div>
                              )}
                            </div>
                          </>
                        )}
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        )}

        <DialogFooter className="px-6 py-3 border-t shrink-0 flex items-center justify-between">
          <div>
            {isCustom && (
              <Button variant="outline" size="sm" className="text-xs" onClick={handleReset}>
                <RotateCcw className="w-3.5 h-3.5 mr-1.5" /> 원본으로 초기화
              </Button>
            )}
          </div>
          <div className="flex items-center gap-2">
            <Button variant="outline" onClick={onClose}>닫기</Button>
            <Button onClick={handleSave} disabled={saving || (!dirty && isCustom)}>
              {saving ? <Loader2 className="w-4 h-4 mr-1.5 animate-spin" /> : <Save className="w-4 h-4 mr-1.5" />}
              저장
            </Button>
          </div>
        </DialogFooter>

        {/* 작업항목 추가/수정 다이얼로그 */}
        <Dialog open={addItemOpen} onOpenChange={setAddItemOpen}>
          <DialogContent className="max-w-[95vw] sm:max-w-[400px]" onClick={e => e.stopPropagation()}>
            <DialogHeader>
              <DialogTitle className="text-base">
                작업항목 {editingWorkItem ? "수정" : "추가"}
              </DialogTitle>
              <DialogDescription className="text-xs">
                {PHASES.find(p => p.key === addItemPhase)?.label} 단계에 작업항목을 {editingWorkItem ? "수정" : "추가"}합니다.
              </DialogDescription>
            </DialogHeader>
            <div className="space-y-3">
              <div>
                <Label className="text-xs">제목 *</Label>
                <Input value={addItemTitle} onChange={e => setAddItemTitle(e.target.value)} placeholder="작업항목 제목" className="h-8 text-xs mt-1" />
              </div>
              <div className="flex items-center gap-2">
                <Checkbox checked={addItemRequired === "Y"} onCheckedChange={v => setAddItemRequired(v ? "Y" : "N")} />
                <Label className="text-xs">필수 항목</Label>
              </div>
            </div>
            <DialogFooter className="gap-2">
              <Button variant="outline" size="sm" onClick={() => setAddItemOpen(false)}>취소</Button>
              <Button size="sm" onClick={handleSaveWorkItem}>{editingWorkItem ? "수정" : "추가"}</Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>

        {/* 상세 추가/수정 다이얼로그 (유형별 동적 필드) */}
        <Dialog open={detailModalOpen} onOpenChange={v => { if (!v) setDetailModalOpen(false); }}>
          <DialogContent className="max-w-[95vw] sm:max-w-[600px] max-h-[90vh] overflow-y-auto" onClick={e => e.stopPropagation()}>
            <DialogHeader>
              <DialogTitle className="text-base">
                상세 항목 {detailModalMode === "add" ? "추가" : "수정"}
              </DialogTitle>
              <DialogDescription className="text-xs">
                상세 항목의 유형을 선택하고 내용을 입력하세요
              </DialogDescription>
            </DialogHeader>

            <div className="space-y-4">
              {/* 유형 선택 */}
              <div>
                <Label className="text-xs">유형 <span className="text-destructive">*</span></Label>
                <Select
                  value={detailFormData.detail_type || ""}
                  onValueChange={v => {
                    setDetailFormData({
                      detail_type: v,
                      is_required: detailFormData.is_required || "Y",
                    });
                  }}
                >
                  <SelectTrigger className="mt-1 h-8 text-xs">
                    <SelectValue placeholder="선택하세요" />
                  </SelectTrigger>
                  <SelectContent>
                    {DETAIL_TYPES.map(dt => (
                      <SelectItem key={dt.value} value={dt.value} className="text-xs">{dt.label}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              {/* 체크리스트 */}
              {detailFormData.detail_type === "checklist" && (
                <div>
                  <Label className="text-xs">체크 내용 <span className="text-destructive">*</span></Label>
                  <Input
                    value={detailFormData.content || ""}
                    onChange={e => updateDetailField("content", e.target.value)}
                    placeholder="예: 전원 상태 확인"
                    className="mt-1 h-8 text-xs"
                  />
                </div>
              )}

              {/* 검사항목 */}
              {detailFormData.detail_type === "inspection" && (
                <>
                  <div>
                    <Label className="text-xs">검사 항목명 <span className="text-destructive">*</span></Label>
                    <Input
                      value={detailFormData.content || ""}
                      onChange={e => updateDetailField("content", e.target.value)}
                      placeholder="예: 외경 치수"
                      className="mt-1 h-8 text-xs"
                    />
                  </div>
                  <div className="grid grid-cols-2 gap-3">
                    <div>
                      <Label className="text-xs">검사 방법</Label>
                      <Input
                        value={detailFormData.inspection_method || ""}
                        onChange={e => updateDetailField("inspection_method", e.target.value)}
                        placeholder="예: 마이크로미터"
                        className="mt-1 h-8 text-xs"
                      />
                    </div>
                    <div>
                      <Label className="text-xs">단위</Label>
                      <Select
                        value={detailFormData.unit || ""}
                        onValueChange={v => updateDetailField("unit", v)}
                      >
                        <SelectTrigger className="mt-1 h-8 text-xs">
                          <SelectValue placeholder="단위 선택" />
                        </SelectTrigger>
                        <SelectContent>
                          {UNIT_OPTIONS.map(u => (
                            <SelectItem key={u} value={u}>{u}</SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                  </div>
                  <div className="rounded-lg border bg-muted/30 p-3">
                    <div className="flex items-center gap-2">
                      <div className="flex-1">
                        <Input
                          type="number"
                          step="any"
                          value={detailFormData.base_value || ""}
                          onChange={e => updateDetailField("base_value", e.target.value)}
                          placeholder="기준값"
                          className="h-8 text-xs"
                        />
                      </div>
                      <span className="text-sm font-semibold text-muted-foreground">&plusmn;</span>
                      <div className="flex-1">
                        <Input
                          type="number"
                          step="any"
                          value={detailFormData.tolerance || ""}
                          onChange={e => updateDetailField("tolerance", e.target.value)}
                          placeholder="오차범위"
                          className="h-8 text-xs"
                        />
                      </div>
                    </div>
                  </div>
                </>
              )}

              {/* 작업절차 */}
              {detailFormData.detail_type === "procedure" && (
                <>
                  <div>
                    <Label className="text-xs">작업 내용 <span className="text-destructive">*</span></Label>
                    <Input
                      value={detailFormData.content || ""}
                      onChange={e => updateDetailField("content", e.target.value)}
                      placeholder="예: 자재 투입"
                      className="mt-1 h-8 text-xs"
                    />
                  </div>
                  <div>
                    <Label className="text-xs">소요 시간 (분)</Label>
                    <Input
                      type="number"
                      value={detailFormData.duration_minutes ?? ""}
                      onChange={e => updateDetailField("duration_minutes", e.target.value ? Number(e.target.value) : undefined)}
                      placeholder="예: 5"
                      className="mt-1 h-8 text-xs"
                    />
                  </div>
                </>
              )}

              {/* 직접입력 */}
              {detailFormData.detail_type === "input" && (
                <>
                  <div>
                    <Label className="text-xs">입력 항목명 <span className="text-destructive">*</span></Label>
                    <Input
                      value={detailFormData.content || ""}
                      onChange={e => updateDetailField("content", e.target.value)}
                      placeholder="예: 작업자 의견"
                      className="mt-1 h-8 text-xs"
                    />
                  </div>
                  <div>
                    <Label className="text-xs">입력 타입</Label>
                    <Select
                      value={detailFormData.input_type || "text"}
                      onValueChange={v => updateDetailField("input_type", v)}
                    >
                      <SelectTrigger className="mt-1 h-8 text-xs">
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        {INPUT_TYPES.map(t => (
                          <SelectItem key={t.value} value={t.value}>{t.label}</SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>
                </>
              )}

              {/* 문서참조 */}
              {detailFormData.detail_type === "lookup" && (
                <div className="flex items-center gap-2 rounded-lg border border-blue-200 bg-blue-50 px-3 py-2.5">
                  <span className="text-xs text-blue-800">
                    해당 품목에 등록된 문서를 자동으로 불러옵니다.
                  </span>
                </div>
              )}

              {/* 설비점검 */}
              {detailFormData.detail_type === "equip_inspection" && (
                <div>
                  <Label className="text-xs">점검 내용</Label>
                  <Input
                    value={detailFormData.content || ""}
                    onChange={e => updateDetailField("content", e.target.value)}
                    placeholder="예: 설비 가동 전 안전 점검"
                    className="mt-1 h-8 text-xs"
                  />
                </div>
              )}

              {/* 설비조건 */}
              {detailFormData.detail_type === "equip_condition" && (
                <>
                  <div>
                    <Label className="text-xs">조건명 <span className="text-destructive">*</span></Label>
                    <Input
                      value={detailFormData.content || ""}
                      onChange={e => updateDetailField("content", e.target.value)}
                      placeholder="조건명 (예: 온도, 압력, RPM)"
                      className="mt-1 h-8 text-xs"
                    />
                  </div>
                  <div className="rounded-lg border bg-muted/30 p-3 space-y-3">
                    <div className="flex gap-2">
                      <div className="flex-[0.6]">
                        <Select
                          value={detailFormData.condition_unit || ""}
                          onValueChange={v => updateDetailField("condition_unit", v)}
                        >
                          <SelectTrigger className="h-8 text-xs">
                            <SelectValue placeholder="단위" />
                          </SelectTrigger>
                          <SelectContent>
                            {UNIT_OPTIONS.map(u => (
                              <SelectItem key={u} value={u}>{u}</SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      </div>
                    </div>
                    <div className="flex items-center gap-2">
                      <div className="flex-1">
                        <Input
                          type="number"
                          step="any"
                          value={detailFormData.condition_base_value || ""}
                          onChange={e => updateDetailField("condition_base_value", e.target.value)}
                          placeholder="기준값"
                          className="h-8 text-xs"
                        />
                      </div>
                      <span className="text-sm font-semibold text-muted-foreground">&plusmn;</span>
                      <div className="flex-1">
                        <Input
                          type="number"
                          step="any"
                          value={detailFormData.condition_tolerance || ""}
                          onChange={e => updateDetailField("condition_tolerance", e.target.value)}
                          placeholder="오차범위"
                          className="h-8 text-xs"
                        />
                      </div>
                    </div>
                  </div>
                </>
              )}

              {/* 실적등록 */}
              {detailFormData.detail_type === "production_result" && (
                <div className="rounded-lg border border-sky-200 bg-sky-50 p-3">
                  <p className="text-xs font-semibold text-sky-800">작업수량 / 불량수량 / 양품수량</p>
                  <p className="mt-1 text-[11px] text-muted-foreground">실적 입력 항목이 자동으로 생성됩니다.</p>
                </div>
              )}

              {/* 자재투입 */}
              {detailFormData.detail_type === "material_input" && (
                <div className="rounded-lg border border-sky-200 bg-sky-50 p-3">
                  <p className="text-xs font-semibold text-sky-800">BOM 구성 자재 (자동 연동)</p>
                  <p className="mt-1 text-[11px] text-muted-foreground">품목에 등록된 BOM 구성 자재가 자동으로 적용됩니다.</p>
                </div>
              )}

              {/* 필수 여부 (모든 유형 공통) */}
              {detailFormData.detail_type && (
                <div>
                  <Label className="text-xs">필수 여부</Label>
                  <Select
                    value={detailFormData.is_required || "Y"}
                    onValueChange={v => updateDetailField("is_required", v)}
                  >
                    <SelectTrigger className="mt-1 h-8 text-xs">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="Y">필수</SelectItem>
                      <SelectItem value="N">선택</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              )}

              {/* 비고 (모든 유형 공통) */}
              {detailFormData.detail_type && (
                <div>
                  <Label className="text-xs">비고</Label>
                  <Input
                    value={detailFormData.remark || ""}
                    onChange={e => updateDetailField("remark", e.target.value)}
                    placeholder="비고 입력"
                    className="mt-1 h-8 text-xs"
                  />
                </div>
              )}
            </div>

            <DialogFooter className="gap-2">
              <Button variant="outline" size="sm" onClick={() => setDetailModalOpen(false)}>취소</Button>
              <Button size="sm" onClick={handleSaveDetail}>{detailModalMode === "add" ? "추가" : "수정"}</Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>
      </DialogContent>
    </Dialog>
  );
}
