"use client";

import React, { useState, useMemo, useEffect, useRef } from "react";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Card, CardContent } from "@/components/ui/card";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
import { Plus, X, ChevronDown, ChevronRight } from "lucide-react";
import { SelectedItemsDetailInputConfig, AdditionalFieldDefinition, FieldGroup, DisplayItem, DisplayItemType, EmptyBehavior, DisplayFieldFormat, AutoDetectedFk } from "./types";
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from "@/components/ui/command";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Check, ChevronsUpDown } from "lucide-react";
import { cn } from "@/lib/utils";
import { getSecondLevelMenus, getCategoryColumns, getCategoryColumnsByMenu, getCategoryValues } from "@/lib/api/tableCategoryValue";
import { CalculationBuilder } from "./CalculationBuilder";

export interface SelectedItemsDetailInputConfigPanelProps {
  config: SelectedItemsDetailInputConfig;
  onChange: (config: Partial<SelectedItemsDetailInputConfig>) => void;
  sourceTableColumns?: Array<{ columnName: string; columnLabel?: string; dataType?: string; inputType?: string }>; // 🆕 원본 테이블 컬럼 (inputType 추가)
  targetTableColumns?: Array<{ columnName: string; columnLabel?: string; dataType?: string; inputType?: string; codeCategory?: string }>; // 🆕 대상 테이블 컬럼 (inputType, codeCategory 추가)
  allTables?: Array<{ tableName: string; displayName?: string }>;
  screenTableName?: string; // 🆕 현재 화면의 테이블명 (자동 설정용)
  onSourceTableChange?: (tableName: string) => void; // 🆕 원본 테이블 변경 콜백
  onTargetTableChange?: (tableName: string) => void; // 🆕 대상 테이블 변경 콜백 (기존 onTableChange 대체)
}

/**
 * SelectedItemsDetailInput 설정 패널
 * 컴포넌트의 설정값들을 편집할 수 있는 UI 제공
 */
export const SelectedItemsDetailInputConfigPanel: React.FC<SelectedItemsDetailInputConfigPanelProps> = ({
  config,
  onChange,
  sourceTableColumns = [], // 🆕 원본 테이블 컬럼
  targetTableColumns = [], // 🆕 대상 테이블 컬럼
  allTables = [],
  screenTableName, // 🆕 현재 화면의 테이블명
  onSourceTableChange, // 🆕 원본 테이블 변경 콜백
  onTargetTableChange, // 🆕 대상 테이블 변경 콜백
}) => {
  const [localFields, setLocalFields] = useState<AdditionalFieldDefinition[]>(config.additionalFields || []);
  const [displayColumns, setDisplayColumns] = useState<Array<{ name: string; label: string; width?: string }>>(config.displayColumns || []);
  const [fieldPopoverOpen, setFieldPopoverOpen] = useState<Record<number, boolean>>({});
  
  // 🆕 필드 그룹 상태
  const [localFieldGroups, setLocalFieldGroups] = useState<FieldGroup[]>(config.fieldGroups || []);
  
  // 🆕 그룹 입력값을 위한 로컬 상태 (포커스 유지용)
  const [localGroupInputs, setLocalGroupInputs] = useState<Record<string, { id?: string; title?: string; description?: string; order?: number }>>({});
  
  // 🆕 필드 입력값을 위한 로컬 상태 (포커스 유지용)
  const [localFieldInputs, setLocalFieldInputs] = useState<Record<number, { label?: string; placeholder?: string }>>({});
  
  // 🆕 표시 항목의 입력값을 위한 로컬 상태 (포커스 유지용)
  const [localDisplayItemInputs, setLocalDisplayItemInputs] = useState<Record<string, Record<number, { label?: string; value?: string }>>>({});
  
  // 🆕 부모 데이터 매핑의 기본값 입력을 위한 로컬 상태 (포커스 유지용)
  const [localMappingInputs, setLocalMappingInputs] = useState<Record<number, string>>({});
  
  
  // 🆕 그룹별 펼침/접힘 상태
  const [expandedGroups, setExpandedGroups] = useState<Record<string, boolean>>({});
  
  // 🆕 그룹별 표시 항목 설정 펼침/접힘 상태
  const [expandedDisplayItems, setExpandedDisplayItems] = useState<Record<string, boolean>>({});
  
  // 🆕 카테고리 매핑 아코디언 펼침/접힘 상태
  const [expandedCategoryMappings, setExpandedCategoryMappings] = useState<Record<string, boolean>>({
    discountType: false,
    roundingType: false,
    roundingUnit: false,
  });
  
  // 🆕 원본 테이블 선택 상태
  const [sourceTableSelectOpen, setSourceTableSelectOpen] = useState(false);
  const [sourceTableSearchValue, setSourceTableSearchValue] = useState("");
  
  // 🆕 대상 테이블 선택 상태 (기존 tableSelectOpen)
  const [tableSelectOpen, setTableSelectOpen] = useState(false);
  const [tableSearchValue, setTableSearchValue] = useState("");

  // 🆕 카테고리 매핑을 위한 상태
  const [secondLevelMenus, setSecondLevelMenus] = useState<Array<{ menuObjid: number; menuName: string; parentMenuName: string }>>([]);
  const [categoryColumns, setCategoryColumns] = useState<Record<string, Array<{ columnName: string; columnLabel: string }>>>({});
  const [categoryValues, setCategoryValues] = useState<Record<string, Array<{ valueCode: string; valueLabel: string }>>>({});
  
  // 🆕 부모 데이터 매핑: 각 매핑별 소스 테이블 컬럼 상태
  const [mappingSourceColumns, setMappingSourceColumns] = useState<Record<number, Array<{ columnName: string; columnLabel?: string; dataType?: string }>>>({});

  // 🆕 추가 입력 필드별 자동 채우기 테이블 컬럼 상태
  const [autoFillTableColumns, setAutoFillTableColumns] = useState<Record<number, Array<{ columnName: string; columnLabel?: string; dataType?: string }>>>({});

  // 🆕 원본/대상 테이블 컬럼 상태 (내부에서 로드)
  const [loadedSourceTableColumns, setLoadedSourceTableColumns] = useState<Array<{ columnName: string; columnLabel?: string; dataType?: string; inputType?: string }>>([]);
  const [loadedTargetTableColumns, setLoadedTargetTableColumns] = useState<Array<{ columnName: string; columnLabel?: string; dataType?: string; inputType?: string; codeCategory?: string; referenceTable?: string; referenceColumn?: string }>>([]);

  // FK 자동 감지 결과
  const [autoDetectedFks, setAutoDetectedFks] = useState<AutoDetectedFk[]>([]);

  // 🆕 원본 테이블 컬럼 로드
  useEffect(() => {
    if (!config.sourceTable) {
      setLoadedSourceTableColumns([]);
      return;
    }

    const loadColumns = async () => {
      try {
        console.log("🔍 원본 테이블 컬럼 로드:", config.sourceTable);
        const { tableManagementApi } = await import("@/lib/api/tableManagement");
        const response = await tableManagementApi.getColumnList(config.sourceTable);

        if (response.success && response.data) {
          const columns = response.data.columns || [];
          setLoadedSourceTableColumns(columns.map((col: any) => ({
            columnName: col.columnName,
            columnLabel: col.displayName || col.columnLabel || col.columnName,
            dataType: col.dataType,
            inputType: col.inputType, // 🔧 inputType 추가
          })));
          console.log("✅ 원본 테이블 컬럼 로드 성공:", columns.length);
        }
      } catch (error) {
        console.error("❌ 원본 테이블 컬럼 로드 오류:", error);
      }
    };

    loadColumns();
  }, [config.sourceTable]);

  // 🆕 대상 테이블 컬럼 로드 (referenceTable/referenceColumn 포함)
  useEffect(() => {
    if (!config.targetTable) {
      setLoadedTargetTableColumns([]);
      setAutoDetectedFks([]);
      return;
    }

    const loadColumns = async () => {
      try {
        console.log("🔍 대상 테이블 컬럼 로드:", config.targetTable);
        const { tableManagementApi } = await import("@/lib/api/tableManagement");
        const response = await tableManagementApi.getColumnList(config.targetTable);

        if (response.success && response.data) {
          const columns = response.data.columns || [];
          setLoadedTargetTableColumns(columns.map((col: any) => ({
            columnName: col.columnName,
            columnLabel: col.displayName || col.columnLabel || col.columnName,
            dataType: col.dataType,
            inputType: col.inputType,
            codeCategory: col.codeCategory,
            referenceTable: col.referenceTable,
            referenceColumn: col.referenceColumn,
          })));
          console.log("✅ 대상 테이블 컬럼 로드 성공:", columns.length);
        }
      } catch (error) {
        console.error("❌ 대상 테이블 컬럼 로드 오류:", error);
      }
    };

    loadColumns();
  }, [config.targetTable]);

  // FK 자동 감지 (ref로 무한 루프 방지)
  const fkAutoAppliedRef = useRef(false);

  // targetTable 컬럼이 로드되면 entity FK 컬럼 감지
  const detectedFks = useMemo<AutoDetectedFk[]>(() => {
    if (!config.targetTable || loadedTargetTableColumns.length === 0) return [];

    const entityFkColumns = loadedTargetTableColumns.filter(
      (col) => col.inputType === "entity" && col.referenceTable
    );
    if (entityFkColumns.length === 0) return [];

    return entityFkColumns.map((col) => {
      let mappingType: "source" | "parent" | "unknown" = "unknown";
      if (config.sourceTable && col.referenceTable === config.sourceTable) {
        mappingType = "source";
      } else if (config.sourceTable && col.referenceTable !== config.sourceTable) {
        mappingType = "parent";
      }
      return {
        columnName: col.columnName,
        columnLabel: col.columnLabel,
        referenceTable: col.referenceTable!,
        referenceColumn: col.referenceColumn || "id",
        mappingType,
      };
    });
  }, [config.targetTable, config.sourceTable, loadedTargetTableColumns]);

  // 감지 결과를 state에 반영
  useEffect(() => {
    setAutoDetectedFks(detectedFks);
  }, [detectedFks]);

  // 자동 매핑 적용 (최초 1회만, targetTable 변경 시 리셋)
  useEffect(() => {
    fkAutoAppliedRef.current = false;
  }, [config.targetTable]);

  useEffect(() => {
    if (fkAutoAppliedRef.current || detectedFks.length === 0) return;

    const sourceFk = detectedFks.find((fk) => fk.mappingType === "source");
    const parentFks = detectedFks.filter((fk) => fk.mappingType === "parent");
    let changed = false;

    // sourceKeyField 자동 설정
    if (sourceFk && !config.sourceKeyField) {
      console.log("🔗 sourceKeyField 자동 설정:", sourceFk.columnName);
      handleChange("sourceKeyField", sourceFk.columnName);
      changed = true;
    }

    // parentDataMapping 자동 생성 (기존에 없을 때만)
    if (parentFks.length > 0 && (!config.parentDataMapping || config.parentDataMapping.length === 0)) {
      const autoMappings = parentFks.map((fk) => ({
        sourceTable: fk.referenceTable,
        sourceField: "id",
        targetField: fk.columnName,
      }));
      console.log("🔗 parentDataMapping 자동 생성:", autoMappings);
      handleChange("parentDataMapping", autoMappings);
      changed = true;
    }

    if (changed) {
      fkAutoAppliedRef.current = true;
    }
  }, [detectedFks]);

  // 🆕 필드 그룹 변경 시 로컬 입력 상태 동기화
  useEffect(() => {
    setLocalFieldGroups(config.fieldGroups || []);
    
    // 로컬 입력 상태는 기존 값 보존하면서 새 그룹만 추가
    setLocalGroupInputs(prev => {
      const newInputs = { ...prev };
      (config.fieldGroups || []).forEach(group => {
        if (!(group.id in newInputs)) {
          newInputs[group.id] = {
            id: group.id,
            title: group.title,
            description: group.description,
            order: group.order,
          };
        }
      });
      return newInputs;
    });

    // 🔧 표시 항목이 있는 그룹은 아코디언을 열린 상태로 초기화
    setExpandedDisplayItems(prev => {
      const newExpanded = { ...prev };
      (config.fieldGroups || []).forEach(group => {
        // 이미 상태가 있으면 유지, 없으면 displayItems가 있을 때만 열기
        if (!(group.id in newExpanded) && group.displayItems && group.displayItems.length > 0) {
          newExpanded[group.id] = true;
        }
      });
      return newExpanded;
    });
  }, [config.fieldGroups]);

  // 🆕 초기 렌더링 시 기존 필드들의 autoFillFromTable 컬럼 로드
  useEffect(() => {
    if (!localFields || localFields.length === 0) return;

    localFields.forEach((field, index) => {
      if (field.autoFillFromTable && !autoFillTableColumns[index]) {
        console.log(`🔍 [초기화] 필드 ${index}의 기존 테이블 컬럼 로드:`, field.autoFillFromTable);
        loadAutoFillTableColumns(field.autoFillFromTable, index);
      }
    });
  }, []); // 초기 한 번만 실행

  // 🆕 자동 채우기 테이블 선택 시 컬럼 로드
  const loadAutoFillTableColumns = async (tableName: string, fieldIndex: number) => {
    if (!tableName) {
      setAutoFillTableColumns(prev => ({ ...prev, [fieldIndex]: [] }));
      return;
    }

    try {
      console.log(`🔍 [필드 ${fieldIndex}] 자동 채우기 테이블 컬럼 로드:`, tableName);
      
      const { tableManagementApi } = await import("@/lib/api/tableManagement");
      const response = await tableManagementApi.getColumnList(tableName);
      
      if (response.success && response.data) {
        const columns = response.data.columns || [];
        setAutoFillTableColumns(prev => ({
          ...prev,
          [fieldIndex]: columns.map((col: any) => ({
            columnName: col.columnName,
            columnLabel: col.displayName || col.columnLabel || col.columnName,
            dataType: col.dataType,
          }))
        }));
        console.log(`✅ [필드 ${fieldIndex}] 컬럼 로드 성공:`, columns.length);
      } else {
        console.error(`❌ [필드 ${fieldIndex}] 컬럼 로드 실패:`, response);
      }
    } catch (error) {
      console.error(`❌ [필드 ${fieldIndex}] 컬럼 로드 오류:`, error);
    }
  };

  // 🆕 소스 테이블 선택 시 컬럼 로드
  const loadMappingSourceColumns = async (tableName: string, mappingIndex: number) => {
    try {
      console.log(`🔍 [매핑 ${mappingIndex}] 소스 테이블 컬럼 로드:`, tableName);
      
      const { tableManagementApi } = await import("@/lib/api/tableManagement");
      const response = await tableManagementApi.getColumnList(tableName);
      
      if (response.success && response.data) {
        const columns = response.data.columns || [];
        setMappingSourceColumns(prev => ({
          ...prev,
          [mappingIndex]: columns.map((col: any) => ({
            columnName: col.columnName,
            columnLabel: col.displayName || col.columnLabel || col.columnName,
            dataType: col.dataType,
          }))
        }));
        console.log(`✅ [매핑 ${mappingIndex}] 컬럼 로드 성공:`, columns.length);
      } else {
        console.error(`❌ [매핑 ${mappingIndex}] 컬럼 로드 실패:`, response);
      }
    } catch (error) {
      console.error(`❌ [매핑 ${mappingIndex}] 컬럼 로드 오류:`, error);
    }
  };

  // 🆕 저장된 부모 데이터 매핑의 컬럼 자동 로드
  useEffect(() => {
    const loadSavedMappingColumns = async () => {
      if (!config.parentDataMapping || config.parentDataMapping.length === 0) {
        console.log("📭 [부모 데이터 매핑] 매핑이 없습니다");
        return;
      }

      console.log("🔍 [부모 데이터 매핑] 저장된 매핑 컬럼 자동 로드 시작:", config.parentDataMapping.length);
      
      for (let i = 0; i < config.parentDataMapping.length; i++) {
        const mapping = config.parentDataMapping[i];
        
        // 이미 로드된 컬럼이 있으면 스킵
        if (mappingSourceColumns[i] && mappingSourceColumns[i].length > 0) {
          console.log(`⏭️ [매핑 ${i}] 이미 로드된 컬럼이 있음`);
          continue;
        }
        
        // 소스 테이블이 선택되어 있으면 컬럼 로드
        if (mapping.sourceTable) {
          console.log(`📡 [매핑 ${i}] 소스 테이블 컬럼 자동 로드:`, mapping.sourceTable);
          await loadMappingSourceColumns(mapping.sourceTable, i);
        }
      }
    };

    loadSavedMappingColumns();
  }, [config.parentDataMapping]);

  // 2레벨 메뉴 목록 로드
  useEffect(() => {
    const loadMenus = async () => {
      const response = await getSecondLevelMenus();
      if (response.success && response.data) {
        setSecondLevelMenus(response.data);
      }
    };
    loadMenus();
  }, []);

  // 메뉴 선택 시 카테고리 목록 로드
  const handleMenuSelect = async (menuObjid: number, fieldType: "discountType" | "roundingType" | "roundingUnit") => {
    console.log("🔍 [handleMenuSelect] 시작", { menuObjid, fieldType });
    
    // 🔧 1단계: 아코디언 먼저 열기 (리렌더링 전에)
    setExpandedCategoryMappings(prev => {
      const newState = { ...prev, [fieldType]: true };
      console.log("🔄 [handleMenuSelect] 아코디언 열기:", newState);
      return newState;
    });
    
    // 🔧 2단계: 메뉴별 카테고리 컬럼 API 호출
    const response = await getCategoryColumnsByMenu(menuObjid);
    
    console.log("📥 [handleMenuSelect] API 응답:", response);
    
    if (response.success && response.data) {
      console.log("✅ [handleMenuSelect] 카테고리 컬럼 데이터:", {
        fieldType,
        columns: response.data,
        count: response.data.length
      });
      
      // 카테고리 컬럼 상태 업데이트
      setCategoryColumns(prev => {
        const newState = { ...prev, [fieldType]: response.data };
        console.log("🔄 [handleMenuSelect] categoryColumns 업데이트:", newState);
        return newState;
      });
    } else {
      console.error("❌ [handleMenuSelect] 카테고리 컬럼 로드 실패:", response);
    }
    
    // 🔧 3단계: valueMapping 업데이트 (마지막에)
    const newConfig = {
      ...config.autoCalculation,
      valueMapping: {
        ...config.autoCalculation.valueMapping,
        _selectedMenus: {
          ...(config.autoCalculation.valueMapping as any)?._selectedMenus,
          [fieldType]: menuObjid,
        },
      },
    };
    
    console.log("🔄 [handleMenuSelect] valueMapping 업데이트:", newConfig);
    handleChange("autoCalculation", newConfig);
  };

  // 카테고리 선택 시 카테고리 값 목록 로드
  const handleCategorySelect = async (columnName: string, menuObjid: number, fieldType: "discountType" | "roundingType" | "roundingUnit") => {
    console.log("🔍 [handleCategorySelect] 시작", { columnName, menuObjid, fieldType, targetTable: config.targetTable });
    
    if (!config.targetTable) {
      console.warn("⚠️ [handleCategorySelect] targetTable이 없습니다");
      return;
    }
    
    const response = await getCategoryValues(config.targetTable, columnName, false, menuObjid);
    
    console.log("📥 [handleCategorySelect] API 응답:", response);
    
    if (response.success && response.data) {
      console.log("✅ [handleCategorySelect] 카테고리 값 데이터:", {
        fieldType,
        values: response.data,
        count: response.data.length
      });
      
      setCategoryValues(prev => {
        const newState = { ...prev, [fieldType]: response.data };
        console.log("🔄 [handleCategorySelect] categoryValues 업데이트:", newState);
        return newState;
      });
    } else {
      console.error("❌ [handleCategorySelect] 카테고리 값 로드 실패:", response);
    }
    
    // 🔧 카테고리 선택 시 아코디언 열기 (이미 열려있을 수도 있음)
    setExpandedCategoryMappings(prev => {
      const newState = { ...prev, [fieldType]: true };
      console.log("🔄 [handleCategorySelect] 아코디언 상태:", newState);
      return newState;
    });
    
    // valueMapping 업데이트
    const newConfig = {
      ...config.autoCalculation,
      valueMapping: {
        ...config.autoCalculation.valueMapping,
        _selectedCategories: {
          ...(config.autoCalculation.valueMapping as any)?._selectedCategories,
          [fieldType]: columnName,
        },
      },
    };
    
    console.log("🔄 [handleCategorySelect] valueMapping 업데이트:", newConfig);
    handleChange("autoCalculation", newConfig);
  };

  // 🆕 저장된 설정에서 카테고리 정보 복원
  useEffect(() => {
    const loadSavedCategories = async () => {
      console.log("🔍 [loadSavedCategories] useEffect 실행", {
        hasTargetTable: !!config.targetTable,
        hasAutoCalc: !!config.autoCalculation,
        hasValueMapping: !!config.autoCalculation?.valueMapping
      });
      
      if (!config.targetTable || !config.autoCalculation?.valueMapping) {
        console.warn("⚠️ [loadSavedCategories] targetTable 또는 valueMapping이 없어 종료");
        return;
      }

      const savedMenus = (config.autoCalculation.valueMapping as any)?._selectedMenus;
      const savedCategories = (config.autoCalculation.valueMapping as any)?._selectedCategories;

      console.log("🔄 [loadSavedCategories] 저장된 카테고리 설정 복원 시작:", { savedMenus, savedCategories });

      // 각 필드 타입별로 저장된 카테고리 값 로드
      const fieldTypes: Array<"discountType" | "roundingType" | "roundingUnit"> = ["discountType", "roundingType", "roundingUnit"];
      
      // 🔧 복원할 아코디언 상태 준비
      const newExpandedState: Record<string, boolean> = {};

      for (const fieldType of fieldTypes) {
        const menuObjid = savedMenus?.[fieldType];
        const columnName = savedCategories?.[fieldType];

        console.log(`🔍 [loadSavedCategories] ${fieldType} 처리`, { menuObjid, columnName });

        // 🔧 메뉴만 선택된 경우에도 카테고리 컬럼 로드
        if (menuObjid) {
          console.log(`✅ [loadSavedCategories] ${fieldType} 메뉴 발견, 카테고리 컬럼 로드 시작:`, { menuObjid });

          // 🔧 메뉴가 선택되어 있으면 아코디언 열기
          newExpandedState[fieldType] = true;

          // 🔧 메뉴별 카테고리 컬럼 로드 (카테고리 선택 여부와 무관)
          console.log(`📡 [loadSavedCategories] ${fieldType} 카테고리 컬럼 API 호출`, { menuObjid });
          const columnsResponse = await getCategoryColumnsByMenu(menuObjid);
          console.log(`📥 [loadSavedCategories] ${fieldType} 컬럼 응답:`, columnsResponse);
          
          if (columnsResponse.success && columnsResponse.data) {
            setCategoryColumns(prev => {
              const newState = { ...prev, [fieldType]: columnsResponse.data };
              console.log(`🔄 [loadSavedCategories] ${fieldType} categoryColumns 업데이트:`, newState);
              return newState;
            });
          } else {
            console.error(`❌ [loadSavedCategories] ${fieldType} 컬럼 로드 실패:`, columnsResponse);
          }

          // 🔧 카테고리까지 선택된 경우에만 값 로드
          if (columnName) {
            console.log(`📡 [loadSavedCategories] ${fieldType} 카테고리 값 API 호출`, { columnName });
            const valuesResponse = await getCategoryValues(config.targetTable, columnName, false, menuObjid);
            console.log(`📥 [loadSavedCategories] ${fieldType} 값 응답:`, valuesResponse);
            
            if (valuesResponse.success && valuesResponse.data) {
              console.log(`✅ [loadSavedCategories] ${fieldType} 카테고리 값:`, valuesResponse.data);
              setCategoryValues(prev => {
                const newState = { ...prev, [fieldType]: valuesResponse.data };
                console.log(`🔄 [loadSavedCategories] ${fieldType} categoryValues 업데이트:`, newState);
                return newState;
              });
            } else {
              console.error(`❌ [loadSavedCategories] ${fieldType} 값 로드 실패:`, valuesResponse);
            }
          }
        }
      }
      
      // 🔧 저장된 설정이 있는 아코디언들 열기
      if (Object.keys(newExpandedState).length > 0) {
        console.log("🔓 [loadSavedCategories] 아코디언 열기:", newExpandedState);
        setExpandedCategoryMappings(prev => {
          const finalState = { ...prev, ...newExpandedState };
          console.log("🔄 [loadSavedCategories] 최종 아코디언 상태:", finalState);
          return finalState;
        });
      }
    };

    loadSavedCategories();
  }, [config.targetTable, config.autoCalculation?.valueMapping]);

  // 🆕 초기 로드 시 screenTableName을 targetTable로 자동 설정
  React.useEffect(() => {
    if (screenTableName && !config.targetTable) {
      console.log("✨ 현재 화면 테이블을 저장 대상 테이블로 자동 설정:", screenTableName);
      handleChange("targetTable", screenTableName);
      
      // 컬럼도 자동 로드
      if (onTargetTableChange) {
        onTargetTableChange(screenTableName);
      }
    }
  }, [screenTableName]); // config.targetTable은 의존성에서 제외 (한 번만 실행)

  const handleChange = (key: keyof SelectedItemsDetailInputConfig, value: any) => {
    // 🔧 기존 config와 병합하여 다른 속성 유지
    onChange({ ...config, [key]: value });
  };

  const handleFieldsChange = (fields: AdditionalFieldDefinition[]) => {
    setLocalFields(fields);
    handleChange("additionalFields", fields);
  };

  const handleDisplayColumnsChange = (columns: Array<{ name: string; label: string; width?: string }>) => {
    setDisplayColumns(columns);
    handleChange("displayColumns", columns);
  };

  // 필드 추가
  const addField = () => {
    const newField: AdditionalFieldDefinition = {
      name: `field_${localFields.length + 1}`,
      label: `필드 ${localFields.length + 1}`,
      type: "text",
    };
    handleFieldsChange([...localFields, newField]);
  };

  // 필드 제거
  const removeField = (index: number) => {
    // 로컬 입력 상태에서도 제거
    setLocalFieldInputs(prev => {
      const newInputs = { ...prev };
      delete newInputs[index];
      return newInputs;
    });
    handleFieldsChange(localFields.filter((_, i) => i !== index));
  };

  // 🆕 로컬 필드 입력 업데이트 (포커스 유지용)
  const updateFieldLocal = (index: number, field: 'label' | 'placeholder', value: string) => {
    setLocalFieldInputs(prev => ({
      ...prev,
      [index]: {
        ...prev[index],
        [field]: value
      }
    }));
  };

  // 🆕 실제 필드 데이터 업데이트 (onBlur 시 호출)
  const handleFieldBlur = (index: number) => {
    const localInput = localFieldInputs[index];
    if (localInput) {
      const newFields = [...localFields];
      newFields[index] = { ...newFields[index], ...localInput };
      handleFieldsChange(newFields);
    }
  };

  // 필드 수정 (Switch 같은 즉시 업데이트가 필요한 경우에만 사용)
  const updateField = (index: number, updates: Partial<AdditionalFieldDefinition>) => {
    const newFields = [...localFields];
    newFields[index] = { ...newFields[index], ...updates };
    handleFieldsChange(newFields);
  };

  // 🆕 필드 그룹 관리
  const handleFieldGroupsChange = (groups: FieldGroup[]) => {
    setLocalFieldGroups(groups);
    handleChange("fieldGroups", groups);
  };

  const addFieldGroup = () => {
    const newGroup: FieldGroup = {
      id: `group_${localFieldGroups.length + 1}`,
      title: `그룹 ${localFieldGroups.length + 1}`,
      order: localFieldGroups.length,
    };
    handleFieldGroupsChange([...localFieldGroups, newGroup]);
  };

  const removeFieldGroup = (groupId: string) => {
    // 로컬 입력 상태에서 해당 그룹 제거
    setLocalGroupInputs(prev => {
      const newInputs = { ...prev };
      delete newInputs[groupId];
      return newInputs;
    });
    
    // 그룹 삭제 시 해당 그룹에 속한 필드들의 groupId도 제거
    const updatedFields = localFields.map(field => 
      field.groupId === groupId ? { ...field, groupId: undefined } : field
    );
    setLocalFields(updatedFields);
    handleChange("additionalFields", updatedFields);
    handleFieldGroupsChange(localFieldGroups.filter(g => g.id !== groupId));
  };

  // 🆕 로컬 그룹 입력 업데이트 (포커스 유지용)
  const updateGroupLocal = (groupId: string, field: 'id' | 'title' | 'description' | 'order', value: any) => {
    setLocalGroupInputs(prev => ({
      ...prev,
      [groupId]: {
        ...prev[groupId],
        [field]: value
      }
    }));
  };

  // 🆕 실제 그룹 데이터 업데이트 (onBlur 시 호출)
  const handleGroupBlur = (groupId: string) => {
    const localInput = localGroupInputs[groupId];
    if (localInput) {
      const newGroups = localFieldGroups.map(g => 
        g.id === groupId ? { ...g, ...localInput } : g
      );
      handleFieldGroupsChange(newGroups);
    }
  };

  const updateFieldGroup = (groupId: string, updates: Partial<FieldGroup>) => {
    // 2. 실제 그룹 데이터 업데이트 (Switch 같은 즉시 업데이트가 필요한 경우에만 사용)
    const newGroups = localFieldGroups.map(g => 
      g.id === groupId ? { ...g, ...updates } : g
    );
    handleFieldGroupsChange(newGroups);
  };

  // 표시 컬럼 추가
  const addDisplayColumn = (columnName: string, columnLabel: string) => {
    if (!displayColumns.some(col => col.name === columnName)) {
      handleDisplayColumnsChange([...displayColumns, { name: columnName, label: columnLabel }]);
    }
  };

  // 표시 컬럼 제거
  const removeDisplayColumn = (columnName: string) => {
    handleDisplayColumnsChange(displayColumns.filter((col) => col.name !== columnName));
  };

  // 🆕 표시 컬럼용: 원본 테이블에서 사용되지 않은 컬럼 목록
  const availableColumns = useMemo(() => {
    // 🔧 로드된 컬럼 우선 사용, props로 받은 컬럼은 백업
    const columns = loadedSourceTableColumns.length > 0 ? loadedSourceTableColumns : sourceTableColumns;
    const usedColumns = new Set([...displayColumns.map(c => c.name), ...localFields.map((f) => f.name)]);
    return columns.filter((col) => !usedColumns.has(col.columnName));
  }, [loadedSourceTableColumns, sourceTableColumns, displayColumns, localFields]);

  // 🆕 추가 입력 필드용: 대상 테이블에서 사용되지 않은 컬럼 목록
  const availableTargetColumns = useMemo(() => {
    // 🔧 로드된 컬럼 우선 사용, props로 받은 컬럼은 백업
    const columns = loadedTargetTableColumns.length > 0 ? loadedTargetTableColumns : targetTableColumns;
    const usedColumns = new Set([...displayColumns.map(c => c.name), ...localFields.map((f) => f.name)]);
    return columns.filter((col) => !usedColumns.has(col.columnName));
  }, [loadedTargetTableColumns, targetTableColumns, displayColumns, localFields]);

  // 🆕 원본 테이블 필터링
  const filteredSourceTables = useMemo(() => {
    if (!sourceTableSearchValue) return allTables;
    const searchLower = sourceTableSearchValue.toLowerCase();
    return allTables.filter(
      (table) =>
        table.tableName.toLowerCase().includes(searchLower) || table.displayName?.toLowerCase().includes(searchLower),
    );
  }, [allTables, sourceTableSearchValue]);

  // 🆕 그룹별 항목 표시 설정 핸들러
  const addDisplayItemToGroup = (groupId: string, type: DisplayItemType) => {
    const newItem: DisplayItem = {
      type,
      id: `display-${Date.now()}`,
    };

    if (type === "field") {
      // 해당 그룹의 필드만 선택 가능하도록
      const groupFields = localFields.filter(f => f.groupId === groupId);
      newItem.fieldName = groupFields[0]?.name || "";
      newItem.format = "text";
      newItem.emptyBehavior = "default";
    } else if (type === "icon") {
      newItem.icon = "Circle";
    } else if (type === "text") {
      newItem.value = "텍스트";
    }

    const updatedGroups = localFieldGroups.map(g => {
      if (g.id === groupId) {
        return {
          ...g,
          displayItems: [...(g.displayItems || []), newItem]
        };
      }
      return g;
    });
    
    // 🔧 아이템 추가 시 해당 그룹의 아코디언을 열린 상태로 유지
    setExpandedDisplayItems(prev => ({
      ...prev,
      [groupId]: true
    }));
    
    setLocalFieldGroups(updatedGroups);
    handleChange("fieldGroups", updatedGroups);
  };

  const removeDisplayItemFromGroup = (groupId: string, itemIndex: number) => {
    const updatedGroups = localFieldGroups.map(g => {
      if (g.id === groupId) {
        return {
          ...g,
          displayItems: (g.displayItems || []).filter((_, i) => i !== itemIndex)
        };
      }
      return g;
    });
    
    setLocalFieldGroups(updatedGroups);
    handleChange("fieldGroups", updatedGroups);
  };

  const updateDisplayItemInGroup = (groupId: string, itemIndex: number, updates: Partial<DisplayItem>) => {
    const updatedGroups = localFieldGroups.map(g => {
      if (g.id === groupId) {
        const updatedItems = [...(g.displayItems || [])];
        updatedItems[itemIndex] = { ...updatedItems[itemIndex], ...updates };
        return {
          ...g,
          displayItems: updatedItems
        };
      }
      return g;
    });
    
    setLocalFieldGroups(updatedGroups);
    handleChange("fieldGroups", updatedGroups);
  };

  // 🆕 선택된 원본 테이블 표시명
  const selectedSourceTableLabel = useMemo(() => {
    if (!config.sourceTable) return "원본 테이블을 선택하세요";
    const table = allTables.find((t) => t.tableName === config.sourceTable);
    return table ? table.displayName || table.tableName : config.sourceTable;
  }, [config.sourceTable, allTables]);

  // 대상 테이블 필터링
  const filteredTables = useMemo(() => {
    if (!tableSearchValue) return allTables;
    const searchLower = tableSearchValue.toLowerCase();
    return allTables.filter(
      (table) =>
        table.tableName.toLowerCase().includes(searchLower) || table.displayName?.toLowerCase().includes(searchLower),
    );
  }, [allTables, tableSearchValue]);

  // 선택된 대상 테이블 표시명
  const selectedTableLabel = useMemo(() => {
    if (!config.targetTable) return "저장 대상 테이블을 선택하세요";
    const table = allTables.find((t) => t.tableName === config.targetTable);
    return table ? table.displayName || table.tableName : config.targetTable;
  }, [config.targetTable, allTables]);

  return (
    <div className="space-y-4">
      {/* 데이터 소스 ID */}
      <div className="space-y-2">
        <Label className="text-xs font-semibold sm:text-sm">
          데이터 소스 ID <span className="text-primary font-normal">(자동 설정됨)</span>
        </Label>
        <Input
          value={config.dataSourceId || ""}
          onChange={(e) => handleChange("dataSourceId", e.target.value)}
          placeholder="비워두면 URL 파라미터에서 자동 설정"
          className="h-7 text-xs sm:h-8 sm:text-sm"
        />
        <p className="text-[10px] text-primary font-medium sm:text-xs">
          ✨ URL 파라미터에서 자동으로 가져옵니다 (Button이 전달)
        </p>
        <p className="text-[10px] text-muted-foreground sm:text-xs">
          테스트용으로 직접 입력하려면 테이블명을 입력하세요
        </p>
      </div>

      {/* 🆕 원본 데이터 테이블 */}
      <div className="space-y-2">
        <Label className="text-xs font-semibold sm:text-sm">
          원본 데이터 테이블 <span className="text-destructive">*</span>
        </Label>
        <Popover open={sourceTableSelectOpen} onOpenChange={setSourceTableSelectOpen}>
          <PopoverTrigger asChild>
            <Button
              variant="outline"
              role="combobox"
              aria-expanded={sourceTableSelectOpen}
              className="h-8 w-full justify-between text-xs sm:text-sm"
            >
              {selectedSourceTableLabel}
              <ChevronsUpDown className="ml-2 h-3 w-3 shrink-0 opacity-50 sm:h-4 sm:w-4" />
            </Button>
          </PopoverTrigger>
          <PopoverContent className="w-full p-0" align="start">
            <Command>
              <CommandInput placeholder="테이블 검색..." value={sourceTableSearchValue} onValueChange={setSourceTableSearchValue} className="h-8 text-xs sm:text-sm" />
              <CommandEmpty>테이블을 찾을 수 없습니다.</CommandEmpty>
              <CommandGroup className="max-h-64 overflow-auto">
                {filteredSourceTables.map((table) => (
                  <CommandItem
                    key={table.tableName}
                    value={table.tableName}
                    onSelect={(currentValue) => {
                      handleChange("sourceTable", currentValue);
                      setSourceTableSelectOpen(false);
                      setSourceTableSearchValue("");
                      if (onSourceTableChange) {
                        onSourceTableChange(currentValue);
                      }
                    }}
                    className="text-xs sm:text-sm"
                  >
                    <Check
                      className={cn(
                        "mr-2 h-3 w-3 sm:h-4 sm:w-4",
                        config.sourceTable === table.tableName ? "opacity-100" : "opacity-0",
                      )}
                    />
                    {table.displayName || table.tableName}
                  </CommandItem>
                ))}
              </CommandGroup>
            </Command>
          </PopoverContent>
        </Popover>
        <p className="text-[10px] text-muted-foreground sm:text-xs">
          이전 화면에서 전달받은 데이터의 원본 테이블 (예: item_info)
        </p>
      </div>

      {/* 저장 대상 테이블 */}
      <div className="space-y-2">
        <Label className="text-xs font-semibold sm:text-sm">
          저장 대상 테이블 <span className="text-destructive">*</span>
        </Label>
        <Popover open={tableSelectOpen} onOpenChange={setTableSelectOpen}>
          <PopoverTrigger asChild>
            <Button
              variant="outline"
              role="combobox"
              aria-expanded={tableSelectOpen}
              className="h-7 w-full justify-between text-xs sm:h-8 sm:text-sm"
            >
              {selectedTableLabel}
              <ChevronsUpDown className="ml-2 h-3 w-3 shrink-0 opacity-50 sm:h-4 sm:w-4" />
            </Button>
          </PopoverTrigger>
          <PopoverContent className="w-full p-0" align="start">
            <Command>
              <CommandInput
                placeholder="테이블 검색..."
                value={tableSearchValue}
                onValueChange={setTableSearchValue}
                className="text-xs sm:text-sm"
              />
              <CommandEmpty className="text-xs sm:text-sm">테이블을 찾을 수 없습니다.</CommandEmpty>
              <CommandGroup className="max-h-48 overflow-auto sm:max-h-64">
                {filteredTables.map((table) => (
                  <CommandItem
                    key={table.tableName}
                    value={table.tableName}
                    onSelect={(currentValue) => {
                      handleChange("targetTable", currentValue);
                      setTableSelectOpen(false);
                      setTableSearchValue("");
                      if (onTargetTableChange) {
                        onTargetTableChange(currentValue);
                      }
                    }}
                    className="text-xs sm:text-sm"
                  >
                    <Check
                      className={cn(
                        "mr-2 h-3 w-3 sm:h-4 sm:w-4",
                        config.targetTable === table.tableName ? "opacity-100" : "opacity-0",
                      )}
                    />
                    {table.displayName || table.tableName}
                  </CommandItem>
                ))}
              </CommandGroup>
            </Command>
          </PopoverContent>
        </Popover>
        <p className="text-[10px] text-muted-foreground sm:text-xs">최종 데이터를 저장할 테이블</p>
      </div>

      {/* FK 자동 감지 결과 표시 */}
      {autoDetectedFks.length > 0 && (
        <div className="rounded-md border border-primary/20 bg-primary/10 p-3 dark:border-primary/30 dark:bg-primary/15">
          <p className="mb-2 text-xs font-medium text-primary dark:text-primary/80">
            FK 자동 감지됨 ({autoDetectedFks.length}건)
          </p>
          <div className="space-y-1">
            {autoDetectedFks.map((fk) => (
              <div key={fk.columnName} className="flex items-center gap-2 text-[10px] sm:text-xs">
                <span className={cn(
                  "rounded px-1.5 py-0.5 font-mono text-[9px]",
                  fk.mappingType === "source" 
                    ? "bg-emerald-100 text-emerald-700 dark:bg-emerald-900 dark:text-emerald-300" 
                    : fk.mappingType === "parent"
                    ? "bg-amber-100 text-orange-700 dark:bg-orange-900 dark:text-orange-300"
                    : "bg-muted text-muted-foreground dark:bg-foreground/90 dark:text-muted-foreground/70"
                )}>
                  {fk.mappingType === "source" ? "원본" : fk.mappingType === "parent" ? "부모" : "미분류"}
                </span>
                <span className="font-mono text-muted-foreground">{fk.columnName}</span>
                <span className="text-muted-foreground">-&gt;</span>
                <span className="font-mono">{fk.referenceTable}</span>
              </div>
            ))}
          </div>
          <p className="mt-2 text-[9px] text-primary dark:text-primary/80">
            엔티티 설정 기반 자동 매핑. sourceKeyField와 parentDataMapping이 자동으로 설정됩니다.
          </p>
        </div>
      )}

      {/* 표시할 원본 데이터 컬럼 */}
      <div className="space-y-2">
        <Label className="text-xs font-semibold sm:text-sm">표시할 원본 데이터 컬럼</Label>
        <div className="space-y-2">
          {displayColumns.map((col, index) => (
            <div key={index} className="flex items-center gap-2">
              <Input value={col.label || col.name} readOnly className="h-7 flex-1 text-xs sm:h-8 sm:text-sm" />
              <Button
                type="button"
                variant="ghost"
                size="icon"
                onClick={() => removeDisplayColumn(col.name)}
                className="h-6 w-6 text-destructive hover:bg-destructive/10 sm:h-7 sm:w-7"
              >
                <X className="h-3 w-3 sm:h-4 sm:w-4" />
              </Button>
            </div>
          ))}
          
          <Popover>
            <PopoverTrigger asChild>
              <Button
                type="button"
                variant="outline"
                size="sm"
                className="h-7 w-full border-dashed text-xs sm:text-sm"
              >
                <Plus className="mr-1 h-3 w-3 sm:h-4 sm:w-4" />
                컬럼 추가
              </Button>
            </PopoverTrigger>
            <PopoverContent className="w-full p-0" align="start">
              <Command>
                <CommandInput placeholder="컬럼 검색..." className="text-xs sm:text-sm" />
                <CommandEmpty className="text-xs sm:text-sm">사용 가능한 컬럼이 없습니다.</CommandEmpty>
                <CommandGroup className="max-h-48 overflow-auto sm:max-h-64">
                  {availableColumns.map((column) => (
                    <CommandItem
                      key={column.columnName}
                      value={column.columnName}
                      onSelect={() => addDisplayColumn(column.columnName, column.columnLabel || column.columnName)}
                      className="text-xs sm:text-sm"
                    >
                      <div>
                        <div className="font-medium">{column.columnLabel || column.columnName}</div>
                        {column.dataType && <div className="text-[10px] text-muted-foreground">{column.dataType}</div>}
                      </div>
                    </CommandItem>
                  ))}
                </CommandGroup>
              </Command>
            </PopoverContent>
          </Popover>
        </div>
        <p className="text-[10px] text-muted-foreground sm:text-xs">
          전달받은 원본 데이터 중 화면에 표시할 컬럼 (예: 품목코드, 품목명)
        </p>
      </div>

      {/* 추가 입력 필드 정의 */}
      <div className="space-y-2">
        <Label className="text-xs font-semibold sm:text-sm">추가 입력 필드 정의</Label>

        {localFields.map((field, index) => {
          return (
          <Card key={index} className="border-2">
            <CardContent className="space-y-2 pt-3 sm:space-y-3 sm:pt-4">
              <div className="flex items-center justify-between">
                <span className="text-xs font-semibold text-foreground sm:text-sm">필드 {index + 1}</span>
                <Button
                  type="button"
                  variant="ghost"
                  size="icon"
                  onClick={() => removeField(index)}
                  className="h-5 w-5 text-destructive hover:bg-destructive/10 sm:h-6 sm:w-6"
                >
                  <X className="h-2 w-2 sm:h-3 sm:w-3" />
                </Button>
              </div>

              <div className="grid grid-cols-2 gap-2 sm:gap-3">
                <div className="space-y-1">
                  <Label className="text-[10px] sm:text-xs">필드명 (컬럼)</Label>
                  <Popover
                    open={fieldPopoverOpen[index] || false}
                    onOpenChange={(open) => setFieldPopoverOpen({ ...fieldPopoverOpen, [index]: open })}
                  >
                    <PopoverTrigger asChild>
                      <Button
                        variant="outline"
                        role="combobox"
                        className="h-6 w-full justify-between text-[10px] sm:h-7 sm:text-xs"
                      >
                        {field.name || "컬럼 선택"}
                        <ChevronsUpDown className="ml-1 h-2 w-2 shrink-0 opacity-50 sm:h-3 sm:w-3" />
                      </Button>
                    </PopoverTrigger>
                    <PopoverContent className="w-[180px] p-0 sm:w-[200px]">
                      <Command>
                        <CommandInput placeholder="컬럼 검색..." className="h-6 text-[10px] sm:h-7 sm:text-xs" />
                        <CommandEmpty className="text-[10px] sm:text-xs">사용 가능한 컬럼이 없습니다.</CommandEmpty>
                        <CommandGroup className="max-h-[150px] overflow-auto sm:max-h-[200px]">
                          {availableTargetColumns.map((column) => (
                            <CommandItem
                              key={column.columnName}
                              value={column.columnName}
                              onSelect={() => {
                                updateField(index, {
                                  name: column.columnName,
                                  label: column.columnLabel || column.columnName,
                                  inputType: column.inputType || "text", // 🆕 inputType 포함
                                  codeCategory: column.codeCategory, // 🆕 codeCategory 포함
                                });
                                setFieldPopoverOpen({ ...fieldPopoverOpen, [index]: false });
                              }}
                              className="text-[10px] sm:text-xs"
                            >
                              <Check
                                className={cn(
                                  "mr-1 h-2 w-2 sm:mr-2 sm:h-3 sm:w-3",
                                  field.name === column.columnName ? "opacity-100" : "opacity-0",
                                )}
                              />
                              <div>
                                <div className="font-medium">{column.columnLabel}</div>
                                <div className="text-[9px] text-muted-foreground">{column.columnName}</div>
                              </div>
                            </CommandItem>
                          ))}
                        </CommandGroup>
                      </Command>
                    </PopoverContent>
                  </Popover>
                </div>

                <div className="space-y-1">
                  <Label className="text-[10px] sm:text-xs">라벨</Label>
                  <Input
                    value={localFieldInputs[index]?.label !== undefined ? localFieldInputs[index].label : field.label}
                    onChange={(e) => updateFieldLocal(index, 'label', e.target.value)}
                    onBlur={() => handleFieldBlur(index)}
                    placeholder="필드 라벨"
                    className="h-6 w-full text-[10px] sm:h-7 sm:text-xs"
                  />
                </div>
              </div>

              <div className="grid grid-cols-2 gap-2 sm:gap-3">
                <div className="space-y-1">
                  <Label className="text-[10px] sm:text-xs">타입 (자동)</Label>
                  <Input
                    value={field.inputType || field.type || "text"}
                    readOnly
                    disabled
                    className="h-6 w-full text-[10px] sm:h-7 sm:text-xs bg-muted"
                  />
                  <p className="text-[9px] text-primary sm:text-[10px]">
                    테이블 타입관리에서 자동 설정됨
                  </p>
                </div>

                <div className="space-y-1">
                  <Label className="text-[10px] sm:text-xs">Placeholder</Label>
                  <Input
                    value={localFieldInputs[index]?.placeholder !== undefined ? localFieldInputs[index].placeholder : (field.placeholder || "")}
                    onChange={(e) => updateFieldLocal(index, 'placeholder', e.target.value)}
                    onBlur={() => handleFieldBlur(index)}
                    placeholder="입력 안내"
                    className="h-6 w-full text-[10px] sm:h-7 sm:text-xs"
                  />
                </div>
              </div>

              {/* 🆕 원본 데이터 자동 채우기 */}
              <div className="space-y-2">
                <Label className="text-[10px] sm:text-xs">자동 채우기 (선택)</Label>
                
                {/* 테이블 선택 드롭다운 */}
                <Popover>
                  <PopoverTrigger asChild>
                    <Button
                      variant="outline"
                      role="combobox"
                      className="h-6 w-full justify-between text-[10px] sm:h-7 sm:text-xs"
                    >
                      {field.autoFillFromTable 
                        ? allTables.find(t => t.tableName === field.autoFillFromTable)?.displayName || field.autoFillFromTable
                        : "원본 테이블 (기본)"}
                      <ChevronsUpDown className="ml-1 h-2 w-2 shrink-0 opacity-50 sm:h-3 sm:w-3" />
                    </Button>
                  </PopoverTrigger>
                  <PopoverContent className="w-[250px] p-0 sm:w-[300px]">
                    <Command>
                      <CommandInput placeholder="테이블 검색..." className="h-6 text-[10px] sm:h-7 sm:text-xs" />
                      <CommandEmpty className="text-[10px] sm:text-xs">테이블을 찾을 수 없습니다.</CommandEmpty>
                      <CommandGroup className="max-h-[200px] overflow-auto">
                        <CommandItem
                          value=""
                          onSelect={() => {
                            updateField(index, { autoFillFromTable: undefined, autoFillFrom: undefined });
                            setAutoFillTableColumns(prev => ({ ...prev, [index]: [] }));
                          }}
                          className="text-[10px] sm:text-xs"
                        >
                          <Check
                            className={cn(
                              "mr-1 h-2 w-2 sm:mr-2 sm:h-3 sm:w-3",
                              !field.autoFillFromTable ? "opacity-100" : "opacity-0",
                            )}
                          />
                          원본 테이블 ({config.sourceTable || "미설정"})
                        </CommandItem>
                        {allTables.map((table) => (
                          <CommandItem
                            key={table.tableName}
                            value={table.tableName}
                            onSelect={(value) => {
                              updateField(index, { autoFillFromTable: value, autoFillFrom: undefined });
                              loadAutoFillTableColumns(value, index);
                            }}
                            className="text-[10px] sm:text-xs"
                          >
                            <Check
                              className={cn(
                                "mr-1 h-2 w-2 sm:mr-2 sm:h-3 sm:w-3",
                                field.autoFillFromTable === table.tableName ? "opacity-100" : "opacity-0",
                              )}
                            />
                            {table.displayName || table.tableName}
                          </CommandItem>
                        ))}
                      </CommandGroup>
                    </Command>
                  </PopoverContent>
                </Popover>
                <p className="text-[9px] text-muted-foreground sm:text-[10px]">
                  다른 테이블에서 가져올 경우 테이블 선택
                </p>
                
                {/* 필드 선택 */}
                <Popover>
                  <PopoverTrigger asChild>
                    <Button
                      variant="outline"
                      role="combobox"
                      className="h-6 w-full justify-between text-[10px] sm:h-7 sm:text-xs"
                    >
                      {(() => {
                        if (!field.autoFillFrom) return "필드 선택 안 함";
                        
                        // 선택된 테이블의 컬럼에서 찾기
                        const columns = field.autoFillFromTable 
                          ? (autoFillTableColumns[index] || [])
                          : (loadedSourceTableColumns.length > 0 ? loadedSourceTableColumns : sourceTableColumns);
                        
                        const found = columns.find(c => c.columnName === field.autoFillFrom);
                        return found?.columnLabel || field.autoFillFrom;
                      })()}
                      <ChevronsUpDown className="ml-1 h-2 w-2 shrink-0 opacity-50 sm:h-3 sm:w-3" />
                    </Button>
                  </PopoverTrigger>
                  <PopoverContent className="w-[180px] p-0 sm:w-[200px]">
                    <Command>
                      <CommandInput placeholder="컬럼 검색..." className="h-6 text-[10px] sm:h-7 sm:text-xs" />
                      <CommandEmpty className="text-[10px] sm:text-xs">
                        {field.autoFillFromTable ? "컬럼을 찾을 수 없습니다" : "원본 테이블을 먼저 선택하세요"}
                      </CommandEmpty>
                      <CommandGroup className="max-h-[150px] overflow-auto sm:max-h-[200px]">
                        <CommandItem
                          value=""
                          onSelect={() => updateField(index, { autoFillFrom: undefined })}
                          className="text-[10px] sm:text-xs"
                        >
                          <Check
                            className={cn(
                              "mr-1 h-2 w-2 sm:mr-2 sm:h-3 sm:w-3",
                              !field.autoFillFrom ? "opacity-100" : "opacity-0",
                            )}
                          />
                          선택 안 함
                        </CommandItem>
                        {(() => {
                          // 선택된 테이블의 컬럼 또는 기본 원본 테이블 컬럼
                          const columns = field.autoFillFromTable 
                            ? (autoFillTableColumns[index] || [])
                            : (loadedSourceTableColumns.length > 0 ? loadedSourceTableColumns : sourceTableColumns);
                          
                          return columns.map((column) => (
                            <CommandItem
                              key={column.columnName}
                              value={column.columnName}
                              onSelect={(value) => updateField(index, { autoFillFrom: value })}
                              className="text-[10px] sm:text-xs"
                            >
                              <Check
                                className={cn(
                                  "mr-1 h-2 w-2 sm:mr-2 sm:h-3 sm:w-3",
                                  field.autoFillFrom === column.columnName ? "opacity-100" : "opacity-0",
                                )}
                              />
                              <div>
                                <div className="font-medium">{column.columnLabel || column.columnName}</div>
                                {column.dataType && <div className="text-[8px] text-muted-foreground">{column.dataType}</div>}
                              </div>
                            </CommandItem>
                          ));
                        })()}
                      </CommandGroup>
                    </Command>
                  </PopoverContent>
                </Popover>
                
                <p className="text-[9px] text-primary sm:text-[10px]">
                  {field.autoFillFromTable 
                    ? `"${field.autoFillFromTable}" 테이블에서 자동 채우기`
                    : "주 데이터 소스에서 자동 채우기 (수정 가능)"
                  }
                </p>
              </div>

              {/* 🆕 필드 그룹 선택 */}
              {localFieldGroups.length > 0 && (
                <div className="space-y-1">
                  <Label className="text-[10px] sm:text-xs">필드 그룹 (선택사항)</Label>
                  <Select
                    value={field.groupId || "none"}
                    onValueChange={(value) => updateField(index, { groupId: value === "none" ? undefined : value })}
                  >
                    <SelectTrigger className="h-6 text-[10px] sm:h-7 sm:text-xs">
                      <SelectValue placeholder="그룹 없음" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="none" className="text-xs">그룹 없음</SelectItem>
                      {localFieldGroups.map((group) => (
                        <SelectItem key={group.id} value={group.id} className="text-xs">
                          {group.title} ({group.id})
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  <p className="text-[9px] text-muted-foreground sm:text-[10px]">
                    같은 그룹 ID를 가진 필드들은 같은 카드에 표시됩니다
                  </p>
                </div>
              )}

              <div className="flex items-center space-x-2">
                <Checkbox
                  id={`required-${index}`}
                  checked={field.required ?? false}
                  onCheckedChange={(checked) => updateField(index, { required: checked as boolean })}
                />
                <Label htmlFor={`required-${index}`} className="cursor-pointer text-[10px] font-normal sm:text-xs">
                  필수 입력
                </Label>
              </div>
            </CardContent>
          </Card>
          );
        })}

        <Button
          type="button"
          variant="outline"
          size="sm"
          onClick={addField}
          className="h-7 w-full border-dashed text-xs sm:text-sm"
        >
          <Plus className="mr-1 h-3 w-3 sm:mr-2 sm:h-4 sm:w-4" />
          필드 추가
        </Button>
      </div>

      {/* 🆕 필드 그룹 관리 */}
      <div className="space-y-2">
        <Label className="text-xs font-semibold sm:text-sm">필드 그룹 설정</Label>
        <p className="text-[10px] text-muted-foreground sm:text-xs">
          추가 입력 필드를 여러 카드로 나눠서 표시 (예: 거래처 정보, 단가 정보)
        </p>

        {localFieldGroups.map((group, index) => {
          const isGroupExpanded = expandedGroups[group.id] ?? true;
          
          return (
          <Collapsible
            key={group.id}
            open={isGroupExpanded}
            onOpenChange={(open) => setExpandedGroups(prev => ({ ...prev, [group.id]: open }))}
          >
            <Card className="border-2">
              <CardContent className="p-3 sm:p-4">
                <div className="flex items-center justify-between mb-2">
                  <CollapsibleTrigger asChild>
                    <Button variant="ghost" size="sm" className="h-auto p-0 hover:bg-transparent">
                      <div className="flex items-center gap-2">
                        {isGroupExpanded ? (
                          <ChevronDown className="h-4 w-4" />
                        ) : (
                          <ChevronRight className="h-4 w-4" />
                        )}
                        <span className="text-xs font-semibold sm:text-sm">
                          그룹 {index + 1}: {group.title || group.id}
                        </span>
                      </div>
                    </Button>
                  </CollapsibleTrigger>
                  <Button
                    type="button"
                    variant="ghost"
                    size="icon"
                    onClick={() => removeFieldGroup(group.id)}
                    className="h-6 w-6 text-destructive hover:text-destructive sm:h-7 sm:w-7"
                  >
                    <X className="h-3 w-3 sm:h-4 sm:w-4" />
                  </Button>
                </div>

                <CollapsibleContent className="space-y-2 sm:space-y-3 mt-2">
                  {/* 그룹 ID */}
              <div className="space-y-1">
                <Label className="text-[10px] sm:text-xs">그룹 ID</Label>
                <Input
                  value={localGroupInputs[group.id]?.id !== undefined ? localGroupInputs[group.id].id : group.id}
                  onChange={(e) => updateGroupLocal(group.id, 'id', e.target.value)}
                  onBlur={() => handleGroupBlur(group.id)}
                  className="h-7 text-xs sm:h-8 sm:text-sm"
                  placeholder="group_customer"
                />
              </div>

              {/* 그룹 제목 */}
              <div className="space-y-1">
                <Label className="text-[10px] sm:text-xs">그룹 제목</Label>
                <Input
                  value={localGroupInputs[group.id]?.title !== undefined ? localGroupInputs[group.id].title : group.title}
                  onChange={(e) => updateGroupLocal(group.id, 'title', e.target.value)}
                  onBlur={() => handleGroupBlur(group.id)}
                  className="h-7 text-xs sm:h-8 sm:text-sm"
                  placeholder="거래처 정보"
                />
              </div>

              {/* 그룹 설명 */}
              <div className="space-y-1">
                <Label className="text-[10px] sm:text-xs">그룹 설명 (선택사항)</Label>
                <Input
                  value={localGroupInputs[group.id]?.description !== undefined ? localGroupInputs[group.id].description : (group.description || "")}
                  onChange={(e) => updateGroupLocal(group.id, 'description', e.target.value)}
                  onBlur={() => handleGroupBlur(group.id)}
                  className="h-7 text-xs sm:h-8 sm:text-sm"
                  placeholder="거래처 관련 정보를 입력합니다"
                />
              </div>

              {/* 표시 순서 */}
              <div className="space-y-1">
                <Label className="text-[10px] sm:text-xs">표시 순서</Label>
                <Input
                  type="number"
                  value={localGroupInputs[group.id]?.order !== undefined ? localGroupInputs[group.id].order : (group.order || 0)}
                  onChange={(e) => updateGroupLocal(group.id, 'order', parseInt(e.target.value) || 0)}
                  onBlur={() => handleGroupBlur(group.id)}
                  className="h-7 text-xs sm:h-8 sm:text-sm"
                  min="0"
                />
              </div>

              {/* 🆕 이 그룹의 항목 표시 설정 */}
              <Collapsible
                open={expandedDisplayItems[group.id] ?? false}
                onOpenChange={(open) => setExpandedDisplayItems(prev => ({ ...prev, [group.id]: open }))}
              >
                <div className="rounded-lg border-2 border-dashed border-primary/30 bg-primary/5 p-2">
                  <CollapsibleTrigger asChild>
                    <Button variant="ghost" size="sm" className="h-auto w-full justify-start p-1 hover:bg-transparent">
                      <div className="flex items-center gap-1">
                        {expandedDisplayItems[group.id] ? (
                          <ChevronDown className="h-3 w-3" />
                        ) : (
                          <ChevronRight className="h-3 w-3" />
                        )}
                        <Label className="text-[10px] font-semibold sm:text-xs cursor-pointer">
                          항목 표시 설정 ({(group.displayItems || []).length}개)
                        </Label>
                      </div>
                    </Button>
                  </CollapsibleTrigger>
                
                <CollapsibleContent className="space-y-2 mt-2">
                  {/* 추가 버튼들 */}
                  <div className="flex gap-1 flex-wrap">
                    <Button
                      type="button"
                      size="sm"
                      variant="outline"
                      onClick={() => addDisplayItemToGroup(group.id, "icon")}
                      className="h-5 px-1.5 text-[8px] sm:h-6 sm:px-2 sm:text-[10px]"
                    >
                      <Plus className="mr-0.5 h-2.5 w-2.5 sm:mr-1 sm:h-3 sm:w-3" />
                      아이콘
                    </Button>
                    <Button
                      type="button"
                      size="sm"
                      variant="outline"
                      onClick={() => addDisplayItemToGroup(group.id, "field")}
                      className="h-5 px-1.5 text-[8px] sm:h-6 sm:px-2 sm:text-[10px]"
                    >
                      <Plus className="mr-0.5 h-2.5 w-2.5 sm:mr-1 sm:h-3 sm:w-3" />
                      필드
                    </Button>
                    <Button
                      type="button"
                      size="sm"
                      variant="outline"
                      onClick={() => addDisplayItemToGroup(group.id, "text")}
                      className="h-5 px-1.5 text-[8px] sm:h-6 sm:px-2 sm:text-[10px]"
                    >
                      <Plus className="mr-0.5 h-2.5 w-2.5 sm:mr-1 sm:h-3 sm:w-3" />
                      텍스트
                    </Button>
                  </div>

                  <p className="text-[9px] text-muted-foreground sm:text-[10px]">
                    이 그룹의 입력 항목이 추가되면 어떻게 표시될지 설정
                  </p>

                  {(!group.displayItems || group.displayItems.length === 0) ? (
                  <div className="rounded border border-dashed p-2 text-center text-[10px] text-muted-foreground">
                    미설정 (모든 필드를 " / "로 구분하여 표시)
                  </div>
                ) : (
                  <div className="space-y-1">
                    {group.displayItems.map((item, itemIndex) => (
                      <div key={item.id} className="rounded border bg-card p-2 space-y-1">
                        {/* 헤더 */}
                        <div className="flex items-center justify-between">
                          <span className="text-[9px] font-medium sm:text-[10px]">
                            {item.type === "icon" && "🎨"}
                            {item.type === "field" && "📝"}
                            {item.type === "text" && "💬"}
                            {item.type === "badge" && "🏷️"}
                          </span>
                          <Button
                            type="button"
                            variant="ghost"
                            size="sm"
                            onClick={() => removeDisplayItemFromGroup(group.id, itemIndex)}
                            className="h-4 w-4 p-0"
                          >
                            <X className="h-2 w-2" />
                          </Button>
                        </div>

                        {/* 아이콘 설정 */}
                        {item.type === "icon" && (
                          <Input
                            value={
                              localDisplayItemInputs[group.id]?.[itemIndex]?.value !== undefined
                                ? localDisplayItemInputs[group.id][itemIndex].value
                                : item.icon || ""
                            }
                            onChange={(e) => {
                              const newValue = e.target.value;
                              setLocalDisplayItemInputs(prev => ({
                                ...prev,
                                [group.id]: {
                                  ...prev[group.id],
                                  [itemIndex]: {
                                    ...prev[group.id]?.[itemIndex],
                                    value: newValue
                                  }
                                }
                              }));
                            }}
                            onBlur={() => {
                              const localValue = localDisplayItemInputs[group.id]?.[itemIndex]?.value;
                              if (localValue !== undefined) {
                                updateDisplayItemInGroup(group.id, itemIndex, { icon: localValue });
                              }
                            }}
                            placeholder="Building"
                            className="h-6 text-[9px] sm:text-[10px]"
                          />
                        )}

                        {/* 텍스트 설정 */}
                        {item.type === "text" && (
                          <Input
                            value={
                              localDisplayItemInputs[group.id]?.[itemIndex]?.value !== undefined
                                ? localDisplayItemInputs[group.id][itemIndex].value
                                : item.value || ""
                            }
                            onChange={(e) => {
                              const newValue = e.target.value;
                              // 로컬 상태 즉시 업데이트 (포커스 유지)
                              setLocalDisplayItemInputs(prev => ({
                                ...prev,
                                [group.id]: {
                                  ...prev[group.id],
                                  [itemIndex]: {
                                    ...prev[group.id]?.[itemIndex],
                                    value: newValue
                                  }
                                }
                              }));
                            }}
                            onBlur={() => {
                              const localValue = localDisplayItemInputs[group.id]?.[itemIndex]?.value;
                              if (localValue !== undefined) {
                                updateDisplayItemInGroup(group.id, itemIndex, { value: localValue });
                              }
                            }}
                            placeholder="| , / , -"
                            className="h-6 text-[9px] sm:text-[10px]"
                          />
                        )}

                        {/* 필드 설정 */}
                        {item.type === "field" && (
                          <div className="space-y-1">
                            {/* 필드 선택 */}
                            <Select
                              value={item.fieldName || ""}
                              onValueChange={(value) => updateDisplayItemInGroup(group.id, itemIndex, { fieldName: value })}
                            >
                              <SelectTrigger className="h-6 w-full text-[9px] sm:text-[10px]">
                                <SelectValue placeholder="필드 선택" />
                              </SelectTrigger>
                              <SelectContent>
                                {localFields.filter(f => f.groupId === group.id).map((field) => (
                                  <SelectItem key={field.name} value={field.name} className="text-[9px] sm:text-[10px]">
                                    {field.label || field.name}
                                  </SelectItem>
                                ))}
                              </SelectContent>
                            </Select>

                            {/* 라벨 */}
                            <Input
                              value={
                                localDisplayItemInputs[group.id]?.[itemIndex]?.label !== undefined
                                  ? localDisplayItemInputs[group.id][itemIndex].label
                                  : item.label || ""
                              }
                              onChange={(e) => {
                                const newValue = e.target.value;
                                // 로컬 상태 즉시 업데이트 (포커스 유지)
                                setLocalDisplayItemInputs(prev => ({
                                  ...prev,
                                  [group.id]: {
                                    ...prev[group.id],
                                    [itemIndex]: {
                                      ...prev[group.id]?.[itemIndex],
                                      label: newValue
                                    }
                                  }
                                }));
                              }}
                              onBlur={() => {
                                const localValue = localDisplayItemInputs[group.id]?.[itemIndex]?.label;
                                if (localValue !== undefined) {
                                  updateDisplayItemInGroup(group.id, itemIndex, { label: localValue });
                                }
                              }}
                              placeholder="라벨 (예: 거래처:)"
                              className="h-6 w-full text-[9px] sm:text-[10px]"
                            />

                            {/* 표시 형식 */}
                            <Select
                              value={item.format || "text"}
                              onValueChange={(value) => updateDisplayItemInGroup(group.id, itemIndex, { format: value as DisplayFieldFormat })}
                            >
                              <SelectTrigger className="h-6 w-full text-[9px] sm:text-[10px]">
                                <SelectValue />
                              </SelectTrigger>
                              <SelectContent>
                                <SelectItem value="text" className="text-[9px] sm:text-[10px]">텍스트</SelectItem>
                                <SelectItem value="currency" className="text-[9px] sm:text-[10px]">금액</SelectItem>
                                <SelectItem value="number" className="text-[9px] sm:text-[10px]">숫자</SelectItem>
                                <SelectItem value="date" className="text-[9px] sm:text-[10px]">날짜</SelectItem>
                                <SelectItem value="badge" className="text-[9px] sm:text-[10px]">배지</SelectItem>
                              </SelectContent>
                            </Select>

                            {/* 빈 값 처리 */}
                            <Select
                              value={item.emptyBehavior || "default"}
                              onValueChange={(value) => updateDisplayItemInGroup(group.id, itemIndex, { emptyBehavior: value as EmptyBehavior })}
                            >
                              <SelectTrigger className="h-6 w-full text-[9px] sm:text-[10px]">
                                <SelectValue />
                              </SelectTrigger>
                              <SelectContent>
                                <SelectItem value="hide" className="text-[9px] sm:text-[10px]">숨김</SelectItem>
                                <SelectItem value="default" className="text-[9px] sm:text-[10px]">기본값</SelectItem>
                                <SelectItem value="blank" className="text-[9px] sm:text-[10px]">빈칸</SelectItem>
                              </SelectContent>
                            </Select>

                            {/* 기본값 */}
                            {item.emptyBehavior === "default" && (
                              <Input
                                value={
                                  localDisplayItemInputs[group.id]?.[itemIndex]?.value !== undefined
                                    ? localDisplayItemInputs[group.id][itemIndex].value
                                    : item.defaultValue || ""
                                }
                                onChange={(e) => {
                                  const newValue = e.target.value;
                                  setLocalDisplayItemInputs(prev => ({
                                    ...prev,
                                    [group.id]: {
                                      ...prev[group.id],
                                      [itemIndex]: {
                                        ...prev[group.id]?.[itemIndex],
                                        value: newValue
                                      }
                                    }
                                  }));
                                }}
                                onBlur={() => {
                                  const localValue = localDisplayItemInputs[group.id]?.[itemIndex]?.value;
                                  if (localValue !== undefined) {
                                    updateDisplayItemInGroup(group.id, itemIndex, { defaultValue: localValue });
                                  }
                                }}
                                placeholder="미입력"
                                className="h-6 w-full text-[9px] sm:text-[10px]"
                              />
                            )}
                          </div>
                        )}
                      </div>
                    ))}
                  </div>
                  )}
                  </CollapsibleContent>
                  </div>
                </Collapsible>
                </CollapsibleContent>
              </CardContent>
            </Card>
          </Collapsible>
          );
        })}

        <Button
          type="button"
          variant="outline"
          size="sm"
          onClick={addFieldGroup}
          className="h-7 w-full border-dashed text-xs sm:text-sm"
        >
          <Plus className="mr-1 h-3 w-3 sm:mr-2 sm:h-4 sm:w-4" />
          그룹 추가
        </Button>
        
        {localFieldGroups.length > 0 && (
          <p className="text-[10px] text-amber-600 sm:text-xs">
            💡 추가 입력 필드의 "필드 그룹 ID"에 위에서 정의한 그룹 ID를 입력하세요
          </p>
        )}
      </div>

      {/* 입력 모드 설정 */}
      <div className="space-y-2">
        <Label className="text-xs font-semibold sm:text-sm">입력 모드</Label>
        <Select
          value={config.inputMode || "inline"}
          onValueChange={(value) => handleChange("inputMode", value as "inline" | "modal")}
        >
          <SelectTrigger className="h-7 text-xs sm:h-8 sm:text-sm">
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="inline" className="text-xs sm:text-sm">
              항상 표시 (Inline)
            </SelectItem>
            <SelectItem value="modal" className="text-xs sm:text-sm">
              추가 버튼으로 표시 (Modal)
            </SelectItem>
          </SelectContent>
        </Select>
        <p className="text-[10px] text-muted-foreground sm:text-xs">
          {config.inputMode === "modal" 
            ? "추가 버튼 클릭 시 입력창 표시, 완료 후 작은 카드로 표시" 
            : "모든 항목의 입력창을 항상 표시"}
        </p>
      </div>

      {/* 레이아웃 설정 */}
      <div className="space-y-2">
        <Label className="text-xs font-semibold sm:text-sm">레이아웃</Label>
        <Select
          value={config.layout || "grid"}
          onValueChange={(value) => handleChange("layout", value as "grid" | "card")}
        >
          <SelectTrigger className="h-7 text-xs sm:h-8 sm:text-sm">
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="grid" className="text-xs sm:text-sm">
              테이블 형식 (Grid)
            </SelectItem>
            <SelectItem value="card" className="text-xs sm:text-sm">
              카드 형식 (Card)
            </SelectItem>
          </SelectContent>
        </Select>
        <p className="text-[10px] text-muted-foreground sm:text-xs">
          {config.layout === "grid" ? "행 단위로 데이터를 표시합니다" : "각 항목을 카드로 표시합니다"}
        </p>
      </div>

      {/* 자동 계산 설정 */}
      <div className="space-y-3 rounded-lg border p-3 sm:p-4">
        <div className="flex items-center justify-between">
          <Label className="text-xs font-semibold sm:text-sm">자동 계산 설정</Label>
            <Checkbox
              id="enable-auto-calc"
              checked={!!config.autoCalculation}
              onCheckedChange={(checked) => {
                if (checked) {
                  handleChange("autoCalculation", {
                    targetField: "",
                    mode: "template",
                    inputFields: {
                      basePrice: "",
                      discountType: "",
                      discountValue: "",
                      roundingType: "",
                      roundingUnit: "",
                    },
                    calculationType: "price",
                    valueMapping: {},
                    calculationSteps: [],
                  });
                } else {
                  handleChange("autoCalculation", undefined);
                }
              }}
            />
        </div>

        {config.autoCalculation && (
          <div className="space-y-2 border-t pt-2">
            {/* 계산 모드 선택 */}
            <div className="space-y-1">
              <Label className="text-[10px] sm:text-xs">계산 방식</Label>
              <Select
                value={config.autoCalculation.mode || "template"}
                onValueChange={(value: "template" | "custom") => {
                  handleChange("autoCalculation", {
                    ...config.autoCalculation,
                    mode: value,
                  });
                }}
              >
                <SelectTrigger className="h-8 text-xs">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="template">템플릿 (가격 계산)</SelectItem>
                  <SelectItem value="custom">커스텀 (계산식 빌더)</SelectItem>
                </SelectContent>
              </Select>
            </div>

            {/* 템플릿 모드 */}
            {config.autoCalculation.mode === "template" && (
              <>
                {/* 계산 필드 선택 */}
                <div className="space-y-2 border-t pt-2 mt-2">
              <Label className="text-[10px] font-semibold sm:text-xs">계산에 사용할 필드 선택</Label>
              
              <div className="space-y-2">
                {/* 계산 결과 필드 */}
                <div className="space-y-1">
                  <Label className="text-[9px] sm:text-[10px]">계산 결과 필드</Label>
                  <Select
                    value={config.autoCalculation.targetField || ""}
                    onValueChange={(value) => handleChange("autoCalculation", {
                      ...config.autoCalculation,
                      targetField: value,
                    })}
                  >
                    <SelectTrigger className="h-7 text-xs">
                      <SelectValue placeholder="필드 선택" />
                    </SelectTrigger>
                    <SelectContent>
                      {(config.additionalFields || []).map((field) => (
                        <SelectItem key={field.name} value={field.name}>
                          {field.label || field.name}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>

                {/* 기준 단가 필드 */}
                <div className="space-y-1">
                  <Label className="text-[9px] sm:text-[10px]">기준 단가 필드</Label>
                  <Select
                    value={config.autoCalculation.inputFields?.basePrice || ""}
                    onValueChange={(value) => handleChange("autoCalculation", {
                      ...config.autoCalculation,
                      inputFields: {
                        ...config.autoCalculation.inputFields,
                        basePrice: value,
                      },
                    })}
                  >
                    <SelectTrigger className="h-7 text-xs">
                      <SelectValue placeholder="필드 선택" />
                    </SelectTrigger>
                    <SelectContent>
                      {(config.additionalFields || []).map((field) => (
                        <SelectItem key={field.name} value={field.name}>
                          {field.label || field.name}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>

                <div className="grid grid-cols-2 gap-2">
                  {/* 할인 방식 필드 */}
                  <div className="space-y-1">
                    <Label className="text-[9px] sm:text-[10px]">할인 방식</Label>
                    <Select
                      value={config.autoCalculation.inputFields?.discountType || ""}
                      onValueChange={(value) => handleChange("autoCalculation", {
                        ...config.autoCalculation,
                        inputFields: {
                          ...config.autoCalculation.inputFields,
                          discountType: value,
                        },
                      })}
                    >
                      <SelectTrigger className="h-7 text-xs">
                        <SelectValue placeholder="필드 선택" />
                      </SelectTrigger>
                      <SelectContent>
                        {(config.additionalFields || []).map((field) => (
                          <SelectItem key={field.name} value={field.name}>
                            {field.label || field.name}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>

                  {/* 할인값 필드 */}
                  <div className="space-y-1">
                    <Label className="text-[9px] sm:text-[10px]">할인값</Label>
                    <Select
                      value={config.autoCalculation.inputFields?.discountValue || ""}
                      onValueChange={(value) => handleChange("autoCalculation", {
                        ...config.autoCalculation,
                        inputFields: {
                          ...config.autoCalculation.inputFields,
                          discountValue: value,
                        },
                      })}
                    >
                      <SelectTrigger className="h-7 text-xs">
                        <SelectValue placeholder="필드 선택" />
                      </SelectTrigger>
                      <SelectContent>
                        {(config.additionalFields || []).map((field) => (
                          <SelectItem key={field.name} value={field.name}>
                            {field.label || field.name}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>
                </div>

                <div className="grid grid-cols-2 gap-2">
                  {/* 반올림 방식 필드 */}
                  <div className="space-y-1">
                    <Label className="text-[9px] sm:text-[10px]">반올림 방식</Label>
                    <Select
                      value={config.autoCalculation.inputFields?.roundingType || ""}
                      onValueChange={(value) => handleChange("autoCalculation", {
                        ...config.autoCalculation,
                        inputFields: {
                          ...config.autoCalculation.inputFields,
                          roundingType: value,
                        },
                      })}
                    >
                      <SelectTrigger className="h-7 text-xs">
                        <SelectValue placeholder="필드 선택" />
                      </SelectTrigger>
                      <SelectContent>
                        {(config.additionalFields || []).map((field) => (
                          <SelectItem key={field.name} value={field.name}>
                            {field.label || field.name}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>

                  {/* 반올림 단위 필드 */}
                  <div className="space-y-1">
                    <Label className="text-[9px] sm:text-[10px]">반올림 단위</Label>
                    <Select
                      value={config.autoCalculation.inputFields?.roundingUnit || ""}
                      onValueChange={(value) => handleChange("autoCalculation", {
                        ...config.autoCalculation,
                        inputFields: {
                          ...config.autoCalculation.inputFields,
                          roundingUnit: value,
                        },
                      })}
                    >
                      <SelectTrigger className="h-7 text-xs">
                        <SelectValue placeholder="필드 선택" />
                      </SelectTrigger>
                      <SelectContent>
                        {(config.additionalFields || []).map((field) => (
                          <SelectItem key={field.name} value={field.name}>
                            {field.label || field.name}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>
                </div>
              </div>
            </div>

            {/* 카테고리 값 매핑 */}
            <div className="space-y-3 border-t pt-3 mt-3">
              <Label className="text-[10px] font-semibold sm:text-xs">카테고리 값 매핑</Label>
              
              {/* 할인 방식 매핑 */}
              <Collapsible
                open={expandedCategoryMappings.discountType}
                onOpenChange={(open) => setExpandedCategoryMappings(prev => ({ ...prev, discountType: open }))}
              >
                <CollapsibleTrigger asChild>
                  <Button
                    variant="ghost"
                    className="flex w-full items-center justify-between p-2 hover:bg-muted"
                  >
                    <span className="text-xs font-medium">할인 방식 연산 매핑</span>
                    {expandedCategoryMappings.discountType ? (
                      <ChevronDown className="h-4 w-4" />
                    ) : (
                      <ChevronRight className="h-4 w-4" />
                    )}
                  </Button>
                </CollapsibleTrigger>
                <CollapsibleContent className="space-y-2 pt-2">
                  {/* 1단계: 메뉴 선택 */}
                  <div className="space-y-1">
                    <Label className="text-[9px] sm:text-[10px]">1단계: 메뉴 선택</Label>
                    <Select
                      value={String((config.autoCalculation.valueMapping as any)?._selectedMenus?.discountType || "")}
                      onValueChange={(value) => handleMenuSelect(Number(value), "discountType")}
                    >
                      <SelectTrigger className="h-7 text-xs">
                        <SelectValue placeholder="2레벨 메뉴 선택" />
                      </SelectTrigger>
                      <SelectContent>
                        {secondLevelMenus.map((menu) => (
                          <SelectItem key={menu.menuObjid} value={String(menu.menuObjid)}>
                            {menu.parentMenuName} &gt; {menu.menuName}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>

                  {/* 2단계: 카테고리 선택 */}
                  {(() => {
                    const hasSelectedMenu = !!(config.autoCalculation.valueMapping as any)?._selectedMenus?.discountType;
                    const columns = categoryColumns.discountType || [];
                    console.log("🎨 [렌더링] 2단계 카테고리 선택", {
                      hasSelectedMenu,
                      columns,
                      columnsCount: columns.length,
                      categoryColumnsState: categoryColumns
                    });
                    return hasSelectedMenu ? (
                      <div className="space-y-1">
                        <Label className="text-[9px] sm:text-[10px]">2단계: 카테고리 선택</Label>
                        <Select
                          value={(config.autoCalculation.valueMapping as any)?._selectedCategories?.discountType || ""}
                          onValueChange={(value) => handleCategorySelect(
                            value,
                            (config.autoCalculation.valueMapping as any)._selectedMenus.discountType,
                            "discountType"
                          )}
                        >
                          <SelectTrigger className="h-7 text-xs">
                            <SelectValue placeholder="카테고리 선택" />
                          </SelectTrigger>
                          <SelectContent>
                            {columns.map((col: any) => (
                              <SelectItem key={col.columnName} value={col.columnName}>
                                {col.columnLabel || col.columnName}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      </div>
                    ) : null;
                  })()}

                  {/* 3단계: 값 매핑 */}
                  {(config.autoCalculation.valueMapping as any)?._selectedCategories?.discountType && (
                    <div className="space-y-1">
                      <Label className="text-[9px] sm:text-[10px]">3단계: 카테고리 값 → 연산 매핑</Label>
                      {["할인없음", "할인율(%)", "할인금액"].map((label, idx) => {
                        const operations = ["none", "rate", "amount"];
                        return (
                          <div key={label} className="flex items-center gap-2">
                            <span className="text-xs w-20">{label}</span>
                            <span className="text-xs text-muted-foreground">→</span>
                            <Select
                              value={
                                Object.entries(config.autoCalculation.valueMapping?.discountType || {})
                                  .find(([_, op]) => op === operations[idx])?.[0] || ""
                              }
                              onValueChange={(value) => {
                                const newMapping = { ...config.autoCalculation.valueMapping?.discountType };
                                Object.keys(newMapping).forEach(key => {
                                  if (newMapping[key] === operations[idx]) delete newMapping[key];
                                });
                                if (value) {
                                  newMapping[value] = operations[idx];
                                }
                                handleChange("autoCalculation", {
                                  ...config.autoCalculation,
                                  valueMapping: {
                                    ...config.autoCalculation.valueMapping,
                                    discountType: newMapping,
                                  },
                                });
                              }}
                            >
                              <SelectTrigger className="h-7 flex-1 text-xs">
                                <SelectValue placeholder="값 선택" />
                              </SelectTrigger>
                              <SelectContent>
                                {(categoryValues.discountType || []).map((val: any) => (
                                  <SelectItem key={val.valueCode} value={val.valueCode}>
                                    {val.valueLabel}
                                  </SelectItem>
                                ))}
                              </SelectContent>
                            </Select>
                            <span className="text-[10px] text-muted-foreground w-12">{operations[idx]}</span>
                          </div>
                        );
                      })}
                    </div>
                  )}
                </CollapsibleContent>
              </Collapsible>

              {/* 반올림 방식 매핑 */}
              <Collapsible
                open={expandedCategoryMappings.roundingType}
                onOpenChange={(open) => setExpandedCategoryMappings(prev => ({ ...prev, roundingType: open }))}
              >
                <CollapsibleTrigger asChild>
                  <Button
                    variant="ghost"
                    className="flex w-full items-center justify-between p-2 hover:bg-muted"
                  >
                    <span className="text-xs font-medium">반올림 방식 연산 매핑</span>
                    {expandedCategoryMappings.roundingType ? (
                      <ChevronDown className="h-4 w-4" />
                    ) : (
                      <ChevronRight className="h-4 w-4" />
                    )}
                  </Button>
                </CollapsibleTrigger>
                <CollapsibleContent className="space-y-2 pt-2">
                  {/* 1단계: 메뉴 선택 */}
                  <div className="space-y-1">
                    <Label className="text-[9px] sm:text-[10px]">1단계: 메뉴 선택</Label>
                    <Select
                      value={String((config.autoCalculation.valueMapping as any)?._selectedMenus?.roundingType || "")}
                      onValueChange={(value) => handleMenuSelect(Number(value), "roundingType")}
                    >
                      <SelectTrigger className="h-7 text-xs">
                        <SelectValue placeholder="2레벨 메뉴 선택" />
                      </SelectTrigger>
                      <SelectContent>
                        {secondLevelMenus.map((menu) => (
                          <SelectItem key={menu.menuObjid} value={String(menu.menuObjid)}>
                            {menu.parentMenuName} &gt; {menu.menuName}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>

                  {/* 2단계: 카테고리 선택 */}
                  {(config.autoCalculation.valueMapping as any)?._selectedMenus?.roundingType && (
                    <div className="space-y-1">
                      <Label className="text-[9px] sm:text-[10px]">2단계: 카테고리 선택</Label>
                      <Select
                        value={(config.autoCalculation.valueMapping as any)?._selectedCategories?.roundingType || ""}
                        onValueChange={(value) => handleCategorySelect(
                          value,
                          (config.autoCalculation.valueMapping as any)._selectedMenus.roundingType,
                          "roundingType"
                        )}
                      >
                        <SelectTrigger className="h-7 text-xs">
                          <SelectValue placeholder="카테고리 선택" />
                        </SelectTrigger>
                        <SelectContent>
                          {(categoryColumns.roundingType || []).map((col: any) => (
                            <SelectItem key={col.columnName} value={col.columnName}>
                              {col.columnLabel || col.columnName}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                  )}

                  {/* 3단계: 값 매핑 */}
                  {(config.autoCalculation.valueMapping as any)?._selectedCategories?.roundingType && (
                    <div className="space-y-1">
                      <Label className="text-[9px] sm:text-[10px]">3단계: 카테고리 값 → 연산 매핑</Label>
                      {["반올림없음", "반올림", "절삭", "올림"].map((label, idx) => {
                        const operations = ["none", "round", "floor", "ceil"];
                        return (
                          <div key={label} className="flex items-center gap-2">
                            <span className="text-xs w-20">{label}</span>
                            <span className="text-xs text-muted-foreground">→</span>
                            <Select
                              value={
                                Object.entries(config.autoCalculation.valueMapping?.roundingType || {})
                                  .find(([_, op]) => op === operations[idx])?.[0] || ""
                              }
                              onValueChange={(value) => {
                                const newMapping = { ...config.autoCalculation.valueMapping?.roundingType };
                                Object.keys(newMapping).forEach(key => {
                                  if (newMapping[key] === operations[idx]) delete newMapping[key];
                                });
                                if (value) {
                                  newMapping[value] = operations[idx];
                                }
                                handleChange("autoCalculation", {
                                  ...config.autoCalculation,
                                  valueMapping: {
                                    ...config.autoCalculation.valueMapping,
                                    roundingType: newMapping,
                                  },
                                });
                              }}
                            >
                              <SelectTrigger className="h-7 flex-1 text-xs">
                                <SelectValue placeholder="값 선택" />
                              </SelectTrigger>
                              <SelectContent>
                                {(categoryValues.roundingType || []).map((val: any) => (
                                  <SelectItem key={val.valueCode} value={val.valueCode}>
                                    {val.valueLabel}
                                  </SelectItem>
                                ))}
                              </SelectContent>
                            </Select>
                            <span className="text-[10px] text-muted-foreground w-12">{operations[idx]}</span>
                          </div>
                        );
                      })}
                    </div>
                  )}
                </CollapsibleContent>
              </Collapsible>

              {/* 반올림 단위 매핑 */}
              <Collapsible
                open={expandedCategoryMappings.roundingUnit}
                onOpenChange={(open) => setExpandedCategoryMappings(prev => ({ ...prev, roundingUnit: open }))}
              >
                <CollapsibleTrigger asChild>
                  <Button
                    variant="ghost"
                    className="flex w-full items-center justify-between p-2 hover:bg-muted"
                  >
                    <span className="text-xs font-medium">반올림 단위 값 매핑</span>
                    {expandedCategoryMappings.roundingUnit ? (
                      <ChevronDown className="h-4 w-4" />
                    ) : (
                      <ChevronRight className="h-4 w-4" />
                    )}
                  </Button>
                </CollapsibleTrigger>
                <CollapsibleContent className="space-y-2 pt-2">
                  {/* 1단계: 메뉴 선택 */}
                  <div className="space-y-1">
                    <Label className="text-[9px] sm:text-[10px]">1단계: 메뉴 선택</Label>
                    <Select
                      value={String((config.autoCalculation.valueMapping as any)?._selectedMenus?.roundingUnit || "")}
                      onValueChange={(value) => handleMenuSelect(Number(value), "roundingUnit")}
                    >
                      <SelectTrigger className="h-7 text-xs">
                        <SelectValue placeholder="2레벨 메뉴 선택" />
                      </SelectTrigger>
                      <SelectContent>
                        {secondLevelMenus.map((menu) => (
                          <SelectItem key={menu.menuObjid} value={String(menu.menuObjid)}>
                            {menu.parentMenuName} &gt; {menu.menuName}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>

                  {/* 2단계: 카테고리 선택 */}
                  {(config.autoCalculation.valueMapping as any)?._selectedMenus?.roundingUnit && (
                    <div className="space-y-1">
                      <Label className="text-[9px] sm:text-[10px]">2단계: 카테고리 선택</Label>
                      <Select
                        value={(config.autoCalculation.valueMapping as any)?._selectedCategories?.roundingUnit || ""}
                        onValueChange={(value) => handleCategorySelect(
                          value,
                          (config.autoCalculation.valueMapping as any)._selectedMenus.roundingUnit,
                          "roundingUnit"
                        )}
                      >
                        <SelectTrigger className="h-7 text-xs">
                          <SelectValue placeholder="카테고리 선택" />
                        </SelectTrigger>
                        <SelectContent>
                          {(categoryColumns.roundingUnit || []).map((col: any) => (
                            <SelectItem key={col.columnName} value={col.columnName}>
                              {col.columnLabel || col.columnName}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                  )}

                  {/* 3단계: 값 매핑 */}
                  {(config.autoCalculation.valueMapping as any)?._selectedCategories?.roundingUnit && (
                    <div className="space-y-1">
                      <Label className="text-[9px] sm:text-[10px]">3단계: 카테고리 값 → 단위 값 매핑</Label>
                      {["1원", "10원", "100원", "1,000원"].map((label) => {
                        const unitValue = label === "1,000원" ? 1000 : parseInt(label);
                        return (
                          <div key={label} className="flex items-center gap-2">
                            <span className="text-xs w-20">{label}</span>
                            <span className="text-xs text-muted-foreground">→</span>
                            <Select
                              value={
                                Object.entries(config.autoCalculation.valueMapping?.roundingUnit || {})
                                  .find(([_, val]) => val === unitValue)?.[0] || ""
                              }
                              onValueChange={(value) => {
                                const newMapping = { ...config.autoCalculation.valueMapping?.roundingUnit };
                                Object.keys(newMapping).forEach(key => {
                                  if (newMapping[key] === unitValue) delete newMapping[key];
                                });
                                if (value) {
                                  newMapping[value] = unitValue;
                                }
                                handleChange("autoCalculation", {
                                  ...config.autoCalculation,
                                  valueMapping: {
                                    ...config.autoCalculation.valueMapping,
                                    roundingUnit: newMapping,
                                  },
                                });
                              }}
                            >
                              <SelectTrigger className="h-7 flex-1 text-xs">
                                <SelectValue placeholder="값 선택" />
                              </SelectTrigger>
                              <SelectContent>
                                {(categoryValues.roundingUnit || []).map((val: any) => (
                                  <SelectItem key={val.valueCode} value={val.valueCode}>
                                    {val.valueLabel}
                                  </SelectItem>
                                ))}
                              </SelectContent>
                            </Select>
                            <span className="text-[10px] text-muted-foreground w-12">{unitValue}</span>
                          </div>
                        );
                      })}
                    </div>
                  )}
                </CollapsibleContent>
              </Collapsible>

              <p className="text-[9px] text-muted-foreground sm:text-[10px]">
                💡 1단계: 메뉴 선택 → 2단계: 카테고리 선택 → 3단계: 값 매핑
              </p>
            </div>
              </>
            )}

            {/* 커스텀 모드 (계산식 빌더) */}
            {config.autoCalculation.mode === "custom" && (
              <div className="space-y-2 border-t pt-2 mt-2">
                <CalculationBuilder
                  steps={config.autoCalculation.calculationSteps || []}
                  availableFields={config.additionalFields || []}
                  onChange={(steps) => {
                    handleChange("autoCalculation", {
                      ...config.autoCalculation,
                      calculationSteps: steps,
                    });
                  }}
                />
              </div>
            )}
          </div>
        )}
      </div>

      {/* 옵션 */}
      <div className="space-y-2 rounded-lg border p-3 sm:p-4">
        <div className="flex items-center space-x-2">
          <Checkbox
            id="show-index"
            checked={config.showIndex ?? true}
            onCheckedChange={(checked) => handleChange("showIndex", checked as boolean)}
          />
          <Label htmlFor="show-index" className="cursor-pointer text-[10px] font-normal sm:text-xs">
            항목 번호 표시
          </Label>
        </div>

        <div className="flex items-center space-x-2">
          <Checkbox
            id="allow-remove"
            checked={config.allowRemove ?? false}
            onCheckedChange={(checked) => handleChange("allowRemove", checked as boolean)}
          />
          <Label htmlFor="allow-remove" className="cursor-pointer text-[10px] font-normal sm:text-xs">
            항목 삭제 허용
          </Label>
        </div>

        <div className="flex items-center space-x-2">
          <Checkbox
            id="disabled"
            checked={config.disabled ?? false}
            onCheckedChange={(checked) => handleChange("disabled", checked as boolean)}
          />
          <Label htmlFor="disabled" className="cursor-pointer text-[10px] font-normal sm:text-xs">
            비활성화 (읽기 전용)
          </Label>
        </div>
      </div>

      {/* 🆕 부모 데이터 매핑 */}
      <div className="space-y-2">
        <div className="flex items-center justify-between">
          <Label className="text-xs font-semibold sm:text-sm">부모 데이터 매핑</Label>
            <Button
              size="sm"
              variant="outline"
              className="h-7 text-xs"
              onClick={() => {
                const newMapping = {
                  sourceTable: "", // 사용자가 선택
                  sourceField: "",
                  targetField: "",
                  defaultValue: undefined,
                };
                handleChange("parentDataMapping", [
                  ...(config.parentDataMapping || []),
                  newMapping,
                ]);
              }}
            >
              <Plus className="mr-1 h-3 w-3" />
              추가
            </Button>
        </div>

        <p className="text-[9px] text-muted-foreground sm:text-[10px]">
          이전 화면(거래처 선택 등)에서 넘어온 데이터를 자동으로 매핑합니다.
        </p>

        <div className="space-y-2">
          {(config.parentDataMapping || []).map((mapping, index) => {
            const isAutoDetected = autoDetectedFks.some(
              (fk) => fk.mappingType === "parent" && fk.columnName === mapping.targetField
            );
            return (
            <Card key={index} className={cn("p-3", isAutoDetected && "border-orange-200 bg-amber-50/30 dark:border-orange-800 dark:bg-orange-950/30")}>
              <div className="space-y-2">
                {isAutoDetected && (
                  <span className="inline-block rounded bg-amber-100 px-1.5 py-0.5 text-[9px] font-medium text-orange-700 dark:bg-orange-900 dark:text-orange-300">
                    FK 자동 감지
                  </span>
                )}
                {/* 소스 테이블 선택 */}
                <div className="space-y-1">
                  <Label className="text-[9px] sm:text-[10px]">소스 테이블</Label>
                  <Popover>
                    <PopoverTrigger asChild>
                      <Button
                        variant="outline"
                        role="combobox"
                        className="h-7 w-full justify-between text-xs font-normal"
                      >
                        {mapping.sourceTable
                          ? allTables.find((t) => t.tableName === mapping.sourceTable)?.displayName ||
                            mapping.sourceTable
                          : "테이블 선택"}
                        <ChevronsUpDown className="ml-2 h-3 w-3 shrink-0 opacity-50" />
                      </Button>
                    </PopoverTrigger>
                    <PopoverContent className="w-[300px] p-0" align="start">
                      <Command>
                        <CommandInput placeholder="테이블 검색..." className="h-8 text-xs" />
                        <CommandList>
                          <CommandEmpty className="text-xs">테이블을 찾을 수 없습니다.</CommandEmpty>
                          <CommandGroup>
                            {allTables.map((table) => (
                              <CommandItem
                                key={table.tableName}
                                value={table.tableName}
                                onSelect={(currentValue) => {
                                  const updated = [...(config.parentDataMapping || [])];
                                  updated[index] = {
                                    ...updated[index],
                                    sourceTable: currentValue,
                                    sourceField: "", // 테이블 변경 시 필드 초기화
                                  };
                                  handleChange("parentDataMapping", updated);

                                  // 테이블 선택 시 컬럼 로드
                                  if (currentValue) {
                                    loadMappingSourceColumns(currentValue, index);
                                  }
                                }}
                                className="text-xs"
                              >
                                <Check
                                  className={cn(
                                    "mr-2 h-3 w-3",
                                    mapping.sourceTable === table.tableName ? "opacity-100" : "opacity-0"
                                  )}
                                />
                                {table.displayName || table.tableName}
                              </CommandItem>
                            ))}
                          </CommandGroup>
                        </CommandList>
                      </Command>
                    </PopoverContent>
                  </Popover>
                  <p className="text-[8px] text-muted-foreground">
                    품목, 거래처, 사용자 등 데이터를 가져올 테이블을 선택하세요
                  </p>
                </div>

                {/* 원본 필드 */}
                <div className="space-y-1">
                  <Label className="text-[9px] sm:text-[10px]">원본 필드</Label>
                  <Popover>
                    <PopoverTrigger asChild>
                      <Button
                        variant="outline"
                        role="combobox"
                        className="h-7 w-full justify-between text-xs font-normal"
                        disabled={!mapping.sourceTable}
                      >
                        {mapping.sourceField
                          ? mappingSourceColumns[index]?.find((c) => c.columnName === mapping.sourceField)
                              ?.columnLabel || mapping.sourceField
                          : "컬럼 선택"}
                        <ChevronsUpDown className="ml-2 h-3 w-3 shrink-0 opacity-50" />
                      </Button>
                    </PopoverTrigger>
                    <PopoverContent className="w-[300px] p-0" align="start">
                      <Command>
                        <CommandInput placeholder="컬럼 검색..." className="h-8 text-xs" />
                        <CommandList>
                          {!mapping.sourceTable ? (
                            <CommandEmpty className="text-xs">소스 테이블을 먼저 선택하세요</CommandEmpty>
                          ) : !mappingSourceColumns[index] || mappingSourceColumns[index].length === 0 ? (
                            <CommandEmpty className="text-xs">컬럼 로딩 중...</CommandEmpty>
                          ) : (
                            <>
                              <CommandEmpty className="text-xs">컬럼을 찾을 수 없습니다.</CommandEmpty>
                              <CommandGroup>
                                {mappingSourceColumns[index].map((col) => {
                                  const searchValue = `${col.columnLabel || col.columnName} ${col.columnName} ${col.dataType || ""}`.toLowerCase();
                                  return (
                                    <CommandItem
                                      key={col.columnName}
                                      value={searchValue}
                                      onSelect={() => {
                                        const updated = [...(config.parentDataMapping || [])];
                                        updated[index] = { ...updated[index], sourceField: col.columnName };
                                        handleChange("parentDataMapping", updated);
                                      }}
                                      className="text-xs"
                                    >
                                      <Check
                                        className={cn(
                                          "mr-2 h-3 w-3",
                                          mapping.sourceField === col.columnName ? "opacity-100" : "opacity-0"
                                        )}
                                      />
                                      <div className="flex flex-col">
                                        <span>{col.columnLabel || col.columnName}</span>
                                        {col.dataType && (
                                          <span className="text-[10px] text-muted-foreground">
                                            {col.dataType}
                                          </span>
                                        )}
                                      </div>
                                    </CommandItem>
                                  );
                                })}
                              </CommandGroup>
                            </>
                          )}
                        </CommandList>
                      </Command>
                    </PopoverContent>
                  </Popover>
                </div>

                {/* 저장 필드 (현재 화면 테이블 컬럼) */}
                <div className="space-y-1">
                  <Label className="text-[9px] sm:text-[10px]">저장 필드 (현재 테이블)</Label>
                  <Popover>
                    <PopoverTrigger asChild>
                      <Button
                        variant="outline"
                        role="combobox"
                        className="h-7 w-full justify-between text-xs font-normal"
                        disabled={!config.targetTable || loadedTargetTableColumns.length === 0}
                      >
                        {mapping.targetField
                          ? loadedTargetTableColumns.find((c) => c.columnName === mapping.targetField)?.columnLabel ||
                            mapping.targetField
                          : "저장 테이블 컬럼 선택"}
                        <ChevronsUpDown className="ml-2 h-3 w-3 shrink-0 opacity-50" />
                      </Button>
                    </PopoverTrigger>
                    <PopoverContent className="w-[300px] p-0" align="start">
                      <Command>
                        <CommandInput placeholder="컬럼 검색..." className="h-8 text-xs" />
                        <CommandList>
                          {!config.targetTable ? (
                            <CommandEmpty className="text-xs">저장 대상 테이블을 먼저 선택하세요</CommandEmpty>
                          ) : loadedTargetTableColumns.length === 0 ? (
                            <CommandEmpty className="text-xs">컬럼 로딩 중...</CommandEmpty>
                          ) : (
                            <>
                              <CommandEmpty className="text-xs">컬럼을 찾을 수 없습니다.</CommandEmpty>
                              <CommandGroup>
                                {loadedTargetTableColumns.map((col) => {
                                  const searchValue = `${col.columnLabel || col.columnName} ${col.columnName} ${col.dataType || ""}`.toLowerCase();
                                  return (
                                    <CommandItem
                                      key={col.columnName}
                                      value={searchValue}
                                      onSelect={() => {
                                        const updated = [...(config.parentDataMapping || [])];
                                        updated[index] = { ...updated[index], targetField: col.columnName };
                                        handleChange("parentDataMapping", updated);
                                      }}
                                      className="text-xs"
                                    >
                                      <Check
                                        className={cn(
                                          "mr-2 h-3 w-3",
                                          mapping.targetField === col.columnName ? "opacity-100" : "opacity-0"
                                        )}
                                      />
                                      <div className="flex flex-col">
                                        <span>{col.columnLabel || col.columnName}</span>
                                        {col.dataType && (
                                          <span className="text-[10px] text-muted-foreground">
                                            {col.dataType}
                                          </span>
                                        )}
                                      </div>
                                    </CommandItem>
                                  );
                                })}
                              </CommandGroup>
                            </>
                          )}
                        </CommandList>
                      </Command>
                    </PopoverContent>
                  </Popover>
                  <p className="text-[8px] text-muted-foreground">
                    현재 화면의 저장 대상 테이블 ({config.targetTable || "미선택"})의 컬럼
                  </p>
                </div>

                {/* 기본값 (선택사항) */}
                <div className="space-y-1">
                  <Label className="text-[9px] sm:text-[10px]">기본값 (선택사항)</Label>
                  <Input
                    value={localMappingInputs[index] !== undefined ? localMappingInputs[index] : mapping.defaultValue || ""}
                    onChange={(e) => {
                      const newValue = e.target.value;
                      setLocalMappingInputs(prev => ({ ...prev, [index]: newValue }));
                    }}
                    onBlur={() => {
                      const currentValue = localMappingInputs[index];
                      if (currentValue !== undefined) {
                        const updated = [...(config.parentDataMapping || [])];
                        updated[index] = { ...updated[index], defaultValue: currentValue || undefined };
                        handleChange("parentDataMapping", updated);
                      }
                    }}
                    placeholder="값이 없을 때 사용할 기본값"
                    className="h-7 text-xs"
                  />
                </div>

                {/* 삭제 버튼 */}
                <div className="flex justify-end pt-2">
                  <Button
                    size="sm"
                    variant="ghost"
                    className="h-7 text-xs text-destructive hover:bg-destructive/10 hover:text-destructive"
                    onClick={() => {
                      const updated = (config.parentDataMapping || []).filter((_, i) => i !== index);
                      handleChange("parentDataMapping", updated);
                    }}
                  >
                    <X className="mr-1 h-3 w-3" />
                    삭제
                  </Button>
                </div>
              </div>
            </Card>
            );
          })}
        </div>
      </div>

      {/* 사용 예시 */}
      <div className="rounded-lg bg-primary/10 p-2 text-xs sm:p-3 sm:text-sm">
        <p className="mb-1 font-medium text-primary">💡 사용 예시</p>
        <ul className="space-y-1 text-[10px] text-primary sm:text-xs">
          <li>• 품목 선택 모달 → 다음 버튼 → 거래처별 가격 입력</li>
          <li>• 사용자 선택 모달 → 다음 버튼 → 권한 및 부서 할당</li>
          <li>• 제품 선택 모달 → 다음 버튼 → 수량 및 납기일 입력</li>
        </ul>
      </div>
    </div>
  );
};

SelectedItemsDetailInputConfigPanel.displayName = "SelectedItemsDetailInputConfigPanel";

export default SelectedItemsDetailInputConfigPanel;
