"use client";

import React, { useState, useEffect, useCallback } from "react";
import { Search, Loader2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Checkbox } from "@/components/ui/checkbox";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/components/ui/dialog";
import { WorkItemDetail, DetailTypeDefinition, InspectionStandard } from "../types";
import { InspectionStandardLookup } from "./InspectionStandardLookup";
import { getBomMaterials, BomMaterial } from "@/lib/api/processInfo";

interface DetailFormModalProps {
  open: boolean;
  onClose: () => void;
  onSubmit: (data: Partial<WorkItemDetail>) => void;
  detailTypes: DetailTypeDefinition[];
  editData?: WorkItemDetail | null;
  mode: "add" | "edit";
  selectedItemCode?: string;
}

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 PLC_DATA_OPTIONS = [
  { value: "PLC_TEMP_01", label: "온도 (PLC_TEMP_01)" },
  { value: "PLC_PRES_01", label: "압력 (PLC_PRES_01)" },
  { value: "PLC_RPM_01", label: "회전수 (PLC_RPM_01)" },
  { value: "PLC_TORQ_01", label: "토크 (PLC_TORQ_01)" },
  { value: "PLC_SPD_01", label: "속도 (PLC_SPD_01)" },
  { value: "PLC_CUR_01", label: "전류 (PLC_CUR_01)" },
  { value: "PLC_VOLT_01", label: "전압 (PLC_VOLT_01)" },
  { value: "PLC_VIB_01", label: "진동 (PLC_VIB_01)" },
  { value: "PLC_HUM_01", label: "습도 (PLC_HUM_01)" },
  { value: "PLC_FLOW_01", label: "유량 (PLC_FLOW_01)" },
];

const PLC_PRODUCTION_OPTIONS = {
  work_qty: [
    { value: "PLC_CNT_01", label: "생산카운터 (PLC_CNT_01)" },
    { value: "PLC_CNT_02", label: "완료카운터 (PLC_CNT_02)" },
    { value: "PLC_QTY_01", label: "작업수량 (PLC_QTY_01)" },
  ],
  defect_qty: [
    { value: "PLC_NG_01", label: "불량카운터 (PLC_NG_01)" },
    { value: "PLC_NG_02", label: "NG감지기 (PLC_NG_02)" },
    { value: "PLC_REJ_01", label: "리젝트수 (PLC_REJ_01)" },
  ],
  good_qty: [
    { value: "PLC_OK_01", label: "양품카운터 (PLC_OK_01)" },
    { value: "PLC_OK_02", label: "합격카운터 (PLC_OK_02)" },
    { value: "PLC_GOOD_01", label: "양품수량 (PLC_GOOD_01)" },
  ],
};

export function DetailFormModal({
  open,
  onClose,
  onSubmit,
  detailTypes,
  editData,
  mode,
  selectedItemCode,
}: DetailFormModalProps) {
  const [formData, setFormData] = useState<Partial<WorkItemDetail>>({});
  const [inspectionLookupOpen, setInspectionLookupOpen] = useState(false);
  const [selectedInspection, setSelectedInspection] = useState<InspectionStandard | null>(null);
  const [bomMaterials, setBomMaterials] = useState<BomMaterial[]>([]);
  const [bomLoading, setBomLoading] = useState(false);
  const [bomChecked, setBomChecked] = useState<Set<string>>(new Set());

  const loadBomMaterials = useCallback(async () => {
    if (!selectedItemCode) {
      setBomMaterials([]);
      return;
    }
    setBomLoading(true);
    try {
      const res = await getBomMaterials(selectedItemCode);
      if (res.success && res.data) {
        setBomMaterials(res.data);
        setBomChecked(new Set(res.data.map((m) => m.child_item_id)));
      } else {
        setBomMaterials([]);
      }
    } catch {
      setBomMaterials([]);
    } finally {
      setBomLoading(false);
    }
  }, [selectedItemCode]);

  useEffect(() => {
    if (open) {
      if (mode === "edit" && editData) {
        setFormData({ ...editData });
        if (editData.inspection_code) {
          setSelectedInspection({
            id: "",
            inspection_code: editData.inspection_code,
            inspection_item: editData.content || "",
            inspection_method: editData.inspection_method || "",
            unit: editData.unit || "",
            lower_limit: editData.lower_limit || "",
            upper_limit: editData.upper_limit || "",
          });
        }
      } else {
        setFormData({
          detail_type: detailTypes[0]?.value || "",
          content: "",
          is_required: "Y",
        });
        setSelectedInspection(null);
      }
    }
  }, [open, mode, editData, detailTypes]);

  useEffect(() => {
    if (open && formData.detail_type === "material_input") {
      loadBomMaterials();
    }
  }, [open, formData.detail_type, loadBomMaterials]);

  const updateField = (field: string, value: any) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
  };

  const handleInspectionSelect = (item: InspectionStandard) => {
    setSelectedInspection(item);
    setFormData((prev) => ({
      ...prev,
      inspection_code: item.inspection_code,
      content: item.inspection_item,
      inspection_method: item.inspection_method,
      unit: item.unit,
      lower_limit: item.lower_limit || "",
      upper_limit: item.upper_limit || "",
    }));
  };

  const handleSubmit = () => {
    if (!formData.detail_type) return;

    const type = formData.detail_type;

    if (type === "checklist" && !formData.content?.trim()) return;
    if (type === "inspection") {
      if (!formData.process_inspection_apply) return;
      if (formData.process_inspection_apply === "none" && !formData.content?.trim()) return;
    }
    if (type === "procedure" && !formData.content?.trim()) return;
    if (type === "input" && !formData.content?.trim()) return;
    if (type === "equip_inspection" && !formData.equip_inspection_apply) return;
    if (type === "equip_condition" && !formData.content?.trim()) return;

    const submitData = { ...formData };

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

    onSubmit(submitData);
    onClose();
  };

  const currentType = formData.detail_type || "";

  return (
    <>
      <Dialog open={open} onOpenChange={(v) => !v && onClose()}>
        <DialogContent className="max-w-[95vw] sm:max-w-[600px] max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="text-base sm:text-lg">
              상세 항목 {mode === "add" ? "추가" : "수정"}
            </DialogTitle>
            <DialogDescription className="text-xs sm:text-sm">
              상세 항목의 유형을 선택하고 내용을 입력하세요
            </DialogDescription>
          </DialogHeader>

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

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

            {/* ============ 검사항목 ============ */}
            {currentType === "inspection" && (
              <>
                {/* 공정검사 적용 여부 */}
                <div>
                  <Label className="text-xs sm:text-sm">
                    공정검사 적용 <span className="text-destructive">*</span>
                  </Label>
                  <div className="mt-2 flex gap-4">
                    <label className="flex cursor-pointer items-center gap-2 text-xs sm:text-sm">
                      <input
                        type="radio"
                        name="processInspection"
                        checked={formData.process_inspection_apply === "apply"}
                        onChange={() => updateField("process_inspection_apply", "apply")}
                        className="h-4 w-4 accent-primary"
                      />
                      적용
                    </label>
                    <label className="flex cursor-pointer items-center gap-2 text-xs sm:text-sm">
                      <input
                        type="radio"
                        name="processInspection"
                        checked={formData.process_inspection_apply === "none"}
                        onChange={() => updateField("process_inspection_apply", "none")}
                        className="h-4 w-4 accent-primary"
                      />
                      미적용
                    </label>
                  </div>
                </div>

                {/* 적용 시: 품목별 검사정보 자동 연동 안내 */}
                {formData.process_inspection_apply === "apply" && (
                  <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>
                )}

                {/* 미적용 시: 수동 입력 */}
                {formData.process_inspection_apply === "none" && (
                  <>
                    <div>
                      <Label className="text-xs sm:text-sm">
                        검사 항목명 <span className="text-destructive">*</span>
                      </Label>
                      <Input
                        value={formData.content || ""}
                        onChange={(e) => updateField("content", e.target.value)}
                        placeholder="예: 외경 치수"
                        className="mt-1 h-8 text-xs sm:h-10 sm:text-sm"
                      />
                    </div>
                    <div className="grid grid-cols-2 gap-3">
                      <div>
                        <Label className="text-xs sm:text-sm">검사 방법</Label>
                        <Input
                          value={formData.inspection_method || ""}
                          onChange={(e) => updateField("inspection_method", e.target.value)}
                          placeholder="예: 마이크로미터"
                          className="mt-1 h-8 text-xs sm:h-10 sm:text-sm"
                        />
                      </div>
                      <div>
                        <Label className="text-xs sm:text-sm">단위</Label>
                        <Select
                          value={formData.unit || ""}
                          onValueChange={(v) => updateField("unit", v)}
                        >
                          <SelectTrigger className="mt-1 h-8 text-xs sm:h-10 sm:text-sm">
                            <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={formData.base_value || ""}
                            onChange={(e) => updateField("base_value", e.target.value)}
                            placeholder="기준값"
                            className="h-8 text-xs sm:h-10 sm:text-sm"
                          />
                        </div>
                        <span className="text-sm font-semibold text-muted-foreground">±</span>
                        <div className="flex-1">
                          <Input
                            type="number"
                            step="any"
                            value={formData.tolerance || ""}
                            onChange={(e) => updateField("tolerance", e.target.value)}
                            placeholder="오차범위"
                            className="h-8 text-xs sm:h-10 sm:text-sm"
                          />
                        </div>
                      </div>

                      {/* 자동수집 */}
                      <div className="mt-3 flex items-center gap-3 border-t pt-3">
                        <label className="flex shrink-0 cursor-pointer items-center gap-2 text-xs font-medium sm:text-sm">
                          <Checkbox
                            checked={formData.auto_collect === "Y"}
                            onCheckedChange={(checked) => {
                              updateField("auto_collect", checked ? "Y" : "N");
                              if (!checked) updateField("plc_data", "");
                            }}
                          />
                          자동수집
                        </label>
                        <Select
                          value={formData.plc_data || ""}
                          onValueChange={(v) => updateField("plc_data", v)}
                          disabled={formData.auto_collect !== "Y"}
                        >
                          <SelectTrigger className={`h-8 flex-1 text-xs sm:h-10 sm:text-sm ${formData.auto_collect !== "Y" ? "opacity-50" : ""}`}>
                            <SelectValue placeholder="수집데이터 선택" />
                          </SelectTrigger>
                          <SelectContent>
                            {PLC_DATA_OPTIONS.map((p) => (
                              <SelectItem key={p.value} value={p.value}>{p.label}</SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      </div>
                    </div>
                  </>
                )}
              </>
            )}

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

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

            {/* ============ 문서참조 ============ */}
            {currentType === "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-sm">📄</span>
                  <span className="text-xs text-blue-800">
                    해당 품목에 등록된 문서를 자동으로 불러옵니다.
                  </span>
                </div>
                <div>
                  <Label className="text-xs sm:text-sm">참조 문서 목록</Label>
                  <div className="mt-1 rounded-lg border p-3">
                    <p className="text-center text-xs text-muted-foreground">
                      품목이 선택되지 않았습니다.
                    </p>
                  </div>
                </div>
              </>
            )}

            {/* ============ 설비점검 ============ */}
            {currentType === "equip_inspection" && (
              <>
                <div className="flex items-center gap-2 rounded-lg border border-green-200 bg-green-50 px-3 py-2.5">
                  <span className="text-sm">🏭</span>
                  <span className="text-xs text-green-800">
                    공정에 지정된 설비를 자동 참조합니다.
                  </span>
                </div>

                <div>
                  <Label className="text-xs sm:text-sm">
                    설비점검 적용 <span className="text-destructive">*</span>
                  </Label>
                  <div className="mt-2 flex gap-4">
                    <label className="flex cursor-pointer items-center gap-2 text-xs sm:text-sm">
                      <input
                        type="radio"
                        name="equipInspApply"
                        checked={formData.equip_inspection_apply === "apply"}
                        onChange={() => updateField("equip_inspection_apply", "apply")}
                        className="h-4 w-4 accent-primary"
                      />
                      적용
                    </label>
                    <label className="flex cursor-pointer items-center gap-2 text-xs sm:text-sm">
                      <input
                        type="radio"
                        name="equipInspApply"
                        checked={formData.equip_inspection_apply === "none"}
                        onChange={() => updateField("equip_inspection_apply", "none")}
                        className="h-4 w-4 accent-primary"
                      />
                      미적용
                    </label>
                  </div>
                </div>

                {/* 적용 시: 설비 점검항목 자동 연동 */}
                {formData.equip_inspection_apply === "apply" && (
                  <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>
                )}
              </>
            )}

            {/* ============ 설비조건 ============ */}
            {currentType === "equip_condition" && (
              <>
                <div className="flex items-center gap-2 rounded-lg border border-green-200 bg-green-50 px-3 py-2.5">
                  <span className="text-sm">🏭</span>
                  <span className="text-xs text-green-800">
                    공정에 지정된 설비를 자동 참조합니다.
                  </span>
                </div>

                <div>
                  <Label className="text-xs sm:text-sm">
                    설비조건 <span className="text-destructive">*</span>
                  </Label>
                  <div className="mt-2 rounded-lg border bg-muted/30 p-3 space-y-3">
                    {/* 조건명 + 단위 */}
                    <div className="flex gap-2">
                      <div className="flex-[1.2]">
                        <Input
                          value={formData.content || ""}
                          onChange={(e) => updateField("content", e.target.value)}
                          placeholder="조건명 (예: 온도, 압력, RPM)"
                          className="h-8 text-xs sm:h-10 sm:text-sm"
                        />
                      </div>
                      <div className="flex-[0.6]">
                        <Select
                          value={formData.condition_unit || ""}
                          onValueChange={(v) => updateField("condition_unit", v)}
                        >
                          <SelectTrigger className="h-8 text-xs sm:h-10 sm:text-sm">
                            <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={formData.condition_base_value || ""}
                          onChange={(e) => updateField("condition_base_value", e.target.value)}
                          placeholder="기준값"
                          className="h-8 text-xs sm:h-10 sm:text-sm"
                        />
                      </div>
                      <span className="text-sm font-semibold text-muted-foreground">±</span>
                      <div className="flex-1">
                        <Input
                          type="number"
                          step="any"
                          value={formData.condition_tolerance || ""}
                          onChange={(e) => updateField("condition_tolerance", e.target.value)}
                          placeholder="오차범위"
                          className="h-8 text-xs sm:h-10 sm:text-sm"
                        />
                      </div>
                    </div>

                    {/* 자동수집 */}
                    <div className="flex items-center gap-3 border-t pt-3">
                      <label className="flex shrink-0 cursor-pointer items-center gap-2 text-xs font-medium sm:text-sm">
                        <Checkbox
                          checked={formData.condition_auto_collect === "Y"}
                          onCheckedChange={(checked) => {
                            updateField("condition_auto_collect", checked ? "Y" : "N");
                            if (!checked) updateField("condition_plc_data", "");
                          }}
                        />
                        자동수집
                      </label>
                      <Select
                        value={formData.condition_plc_data || ""}
                        onValueChange={(v) => updateField("condition_plc_data", v)}
                        disabled={formData.condition_auto_collect !== "Y"}
                      >
                        <SelectTrigger className={`h-8 flex-1 text-xs sm:h-10 sm:text-sm ${formData.condition_auto_collect !== "Y" ? "opacity-50" : ""}`}>
                          <SelectValue placeholder="수집데이터 선택" />
                        </SelectTrigger>
                        <SelectContent>
                          {PLC_DATA_OPTIONS.map((p) => (
                            <SelectItem key={p.value} value={p.value}>{p.label}</SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                  </div>
                </div>
              </>
            )}

            {/* ============ 실적등록 ============ */}
            {currentType === "production_result" && (
              <div>
                <Label className="text-xs sm:text-sm">실적등록 항목 설정</Label>
                <div className="mt-2 rounded-lg border bg-muted/30 p-3 space-y-0 divide-y">
                  {/* 작업수량 */}
                  <div className="flex items-center justify-between py-3 first:pt-0">
                    <div className="flex-1">
                      <span className="text-sm font-semibold">📦 작업수량</span>
                      <span className="ml-2 text-[11px] text-muted-foreground">생산된 전체 수량</span>
                    </div>
                    <div className="flex items-center gap-3">
                      <label className="flex shrink-0 cursor-pointer items-center gap-2 text-xs font-medium">
                        <Checkbox
                          checked={formData.work_qty_auto_collect === "Y"}
                          onCheckedChange={(checked) => {
                            updateField("work_qty_auto_collect", checked ? "Y" : "N");
                            if (!checked) updateField("work_qty_plc_data", "");
                          }}
                        />
                        자동수집
                      </label>
                      <Select
                        value={formData.work_qty_plc_data || ""}
                        onValueChange={(v) => updateField("work_qty_plc_data", v)}
                        disabled={formData.work_qty_auto_collect !== "Y"}
                      >
                        <SelectTrigger className={`h-8 w-[180px] text-xs ${formData.work_qty_auto_collect !== "Y" ? "opacity-50" : ""}`}>
                          <SelectValue placeholder="수집데이터 선택" />
                        </SelectTrigger>
                        <SelectContent>
                          {PLC_PRODUCTION_OPTIONS.work_qty.map((p) => (
                            <SelectItem key={p.value} value={p.value}>{p.label}</SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                  </div>

                  {/* 불량수량 */}
                  <div className="flex items-center justify-between py-3">
                    <div className="flex-1">
                      <span className="text-sm font-semibold">🚫 불량수량</span>
                      <span className="ml-2 text-[11px] text-muted-foreground">불량으로 판정된 수량</span>
                    </div>
                    <div className="flex items-center gap-3">
                      <label className="flex shrink-0 cursor-pointer items-center gap-2 text-xs font-medium">
                        <Checkbox
                          checked={formData.defect_qty_auto_collect === "Y"}
                          onCheckedChange={(checked) => {
                            updateField("defect_qty_auto_collect", checked ? "Y" : "N");
                            if (!checked) updateField("defect_qty_plc_data", "");
                          }}
                        />
                        자동수집
                      </label>
                      <Select
                        value={formData.defect_qty_plc_data || ""}
                        onValueChange={(v) => updateField("defect_qty_plc_data", v)}
                        disabled={formData.defect_qty_auto_collect !== "Y"}
                      >
                        <SelectTrigger className={`h-8 w-[180px] text-xs ${formData.defect_qty_auto_collect !== "Y" ? "opacity-50" : ""}`}>
                          <SelectValue placeholder="수집데이터 선택" />
                        </SelectTrigger>
                        <SelectContent>
                          {PLC_PRODUCTION_OPTIONS.defect_qty.map((p) => (
                            <SelectItem key={p.value} value={p.value}>{p.label}</SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                  </div>

                  {/* 양품수량 */}
                  <div className="flex items-center justify-between py-3 last:pb-0">
                    <div className="flex-1">
                      <span className="text-sm font-semibold">✅ 양품수량</span>
                      <span className="ml-2 text-[11px] text-muted-foreground">작업수량 - 불량수량</span>
                    </div>
                    <div className="flex items-center gap-3">
                      <label className="flex shrink-0 cursor-pointer items-center gap-2 text-xs font-medium">
                        <Checkbox
                          checked={formData.good_qty_auto_collect === "Y"}
                          onCheckedChange={(checked) => {
                            updateField("good_qty_auto_collect", checked ? "Y" : "N");
                            if (!checked) updateField("good_qty_plc_data", "");
                          }}
                        />
                        자동수집
                      </label>
                      <Select
                        value={formData.good_qty_plc_data || ""}
                        onValueChange={(v) => updateField("good_qty_plc_data", v)}
                        disabled={formData.good_qty_auto_collect !== "Y"}
                      >
                        <SelectTrigger className={`h-8 w-[180px] text-xs ${formData.good_qty_auto_collect !== "Y" ? "opacity-50" : ""}`}>
                          <SelectValue placeholder="수집데이터 선택" />
                        </SelectTrigger>
                        <SelectContent>
                          {PLC_PRODUCTION_OPTIONS.good_qty.map((p) => (
                            <SelectItem key={p.value} value={p.value}>{p.label}</SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                  </div>
                </div>
              </div>
            )}

            {/* ============ 자재투입 ============ */}
            {currentType === "material_input" && (
              <div>
                <Label className="text-xs sm:text-sm">자재투입 설정</Label>
                <div className="mt-2 rounded-lg border border-sky-200 bg-sky-50 p-3">
                  <div className="mb-2 flex items-center justify-between">
                    <p className="text-xs font-semibold text-sky-800">
                      📦 BOM 구성 자재 (자동 연동)
                    </p>
                    <span className="text-[11px] text-muted-foreground">
                      {bomMaterials.length > 0 ? `${bomMaterials.length}건` : ""}
                    </span>
                  </div>
                  <div className="max-h-[300px] overflow-y-auto rounded-lg border bg-white">
                    {bomLoading ? (
                      <div className="flex items-center justify-center gap-2 py-6">
                        <Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
                        <span className="text-xs text-muted-foreground">BOM 데이터를 불러오는 중...</span>
                      </div>
                    ) : !selectedItemCode ? (
                      <div className="py-5 text-center text-xs text-muted-foreground">
                        품목을 먼저 선택하세요.
                      </div>
                    ) : bomMaterials.length === 0 ? (
                      <div className="py-5 text-center text-xs text-muted-foreground">
                        해당 품목의 BOM 구성 자재가 없습니다.
                      </div>
                    ) : (
                      bomMaterials.map((mat) => {
                        const typeColor =
                          mat.child_item_type === "원자재" ? "#16a34a"
                          : mat.child_item_type === "반제품" ? "#2563eb"
                          : "#6b7280";
                        return (
                          <div
                            key={mat.id}
                            className="flex items-center gap-2.5 border-b px-3 py-2.5 last:border-b-0 hover:bg-sky-50/50"
                          >
                            <Checkbox
                              checked={bomChecked.has(mat.child_item_id)}
                              onCheckedChange={(checked) => {
                                setBomChecked((prev) => {
                                  const next = new Set(prev);
                                  if (checked) next.add(mat.child_item_id);
                                  else next.delete(mat.child_item_id);
                                  return next;
                                });
                              }}
                            />
                            <div className="min-w-0 flex-1">
                              <div className="flex items-center gap-1.5">
                                {mat.child_item_type && (
                                  <span
                                    className="rounded px-1.5 py-0.5 text-[10px] font-semibold text-white"
                                    style={{ backgroundColor: typeColor }}
                                  >
                                    {mat.child_item_type}
                                  </span>
                                )}
                                <span className="text-[11px] text-muted-foreground">
                                  {mat.child_item_code || "-"}
                                </span>
                                <span className="text-xs font-medium">
                                  {mat.child_item_name || "(이름 없음)"}
                                </span>
                              </div>
                              <div className="mt-0.5 text-[11px] text-muted-foreground">
                                소요량: {mat.quantity || "0"} {mat.detail_unit || mat.item_unit || ""}
                                {mat.process_type ? ` | 공정: ${mat.process_type}` : ""}
                              </div>
                            </div>
                          </div>
                        );
                      })
                    )}
                  </div>
                </div>
              </div>
            )}

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

          <DialogFooter className="gap-2 sm:gap-0">
            <Button
              variant="outline"
              onClick={onClose}
              className="h-8 flex-1 text-xs sm:h-10 sm:flex-none sm:text-sm"
            >
              취소
            </Button>
            <Button
              onClick={handleSubmit}
              className="h-8 flex-1 text-xs sm:h-10 sm:flex-none sm:text-sm"
            >
              {mode === "add" ? "추가" : "수정"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <InspectionStandardLookup
        open={inspectionLookupOpen}
        onClose={() => setInspectionLookupOpen(false)}
        onSelect={handleInspectionSelect}
      />
    </>
  );
}
