"use client";

import React, { useState, useMemo, useEffect } from "react";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem } from "@/components/ui/command";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Switch } from "@/components/ui/switch";
import { Plus, X, GripVertical, Check, ChevronsUpDown, Calculator, Database, ArrowUp, ArrowDown } from "lucide-react";
import {
  RepeaterFieldGroupConfig,
  RepeaterFieldDefinition,
  RepeaterFieldType,
  CalculationOperator,
  CalculationFormula,
  SubDataLookupConfig,
} from "@/types/repeater";
import { apiClient } from "@/lib/api/client";
import { ColumnInfo } from "@/types/screen";
import { cn } from "@/lib/utils";

export interface RepeaterConfigPanelProps {
  config: RepeaterFieldGroupConfig;
  onChange: (config: RepeaterFieldGroupConfig) => void;
  tableColumns?: ColumnInfo[];
  allTables?: Array<{ tableName: string; displayName?: string }>; // 전체 테이블 목록
  onTableChange?: (tableName: string) => void; // 테이블 변경 시 해당 테이블의 컬럼 로드
}

/**
 * 반복 필드 그룹 설정 패널
 */
export const RepeaterConfigPanel: React.FC<RepeaterConfigPanelProps> = ({
  config,
  onChange,
  tableColumns = [],
  allTables = [],
  onTableChange,
}) => {
  const [localFields, setLocalFields] = useState<RepeaterFieldDefinition[]>(config.fields || []);
  const [fieldNamePopoverOpen, setFieldNamePopoverOpen] = useState<Record<number, boolean>>({});

  // 로컬 입력 상태 (각 필드의 라벨, placeholder 등)
  const [localInputs, setLocalInputs] = useState<Record<number, { label: string; placeholder: string }>>({});

  // 설정 입력 필드의 로컬 상태
  const [localConfigInputs, setLocalConfigInputs] = useState({
    addButtonText: config.addButtonText || "",
  });

  // config 변경 시 로컬 상태 동기화
  useEffect(() => {
    setLocalConfigInputs({
      addButtonText: config.addButtonText || "",
    });
  }, [config.addButtonText]);

  // 이미 사용된 컬럼명 목록
  const usedColumnNames = useMemo(() => {
    return new Set(localFields.map((f) => f.name));
  }, [localFields]);

  // 사용 가능한 컬럼 목록 (이미 사용된 컬럼 제외, 현재 편집 중인 필드는 포함)
  const getAvailableColumns = (currentFieldName?: string) => {
    return tableColumns.filter((col) => !usedColumnNames.has(col.columnName) || col.columnName === currentFieldName);
  };

  const handleChange = (key: keyof RepeaterFieldGroupConfig, value: any) => {
    onChange({
      ...config,
      [key]: value,
    });
  };

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

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

  // 필드 제거
  const removeField = (index: number) => {
    handleFieldsChange(localFields.filter((_, i) => i !== index));
  };

  // 필드 순서 변경 (위로)
  const moveFieldUp = (index: number) => {
    if (index <= 0) return;
    const newFields = [...localFields];
    [newFields[index - 1], newFields[index]] = [newFields[index], newFields[index - 1]];
    handleFieldsChange(newFields);
  };

  // 필드 순서 변경 (아래로)
  const moveFieldDown = (index: number) => {
    if (index >= localFields.length - 1) return;
    const newFields = [...localFields];
    [newFields[index], newFields[index + 1]] = [newFields[index + 1], newFields[index]];
    handleFieldsChange(newFields);
  };

  // 드래그 앤 드롭 상태
  const [draggedFieldIndex, setDraggedFieldIndex] = useState<number | null>(null);

  // 필드 드래그 시작
  const handleFieldDragStart = (index: number) => {
    setDraggedFieldIndex(index);
  };

  // 필드 드래그 오버
  const handleFieldDragOver = (e: React.DragEvent, index: number) => {
    e.preventDefault();
  };

  // 필드 드롭
  const handleFieldDrop = (e: React.DragEvent, targetIndex: number) => {
    e.preventDefault();
    if (draggedFieldIndex === null || draggedFieldIndex === targetIndex) {
      setDraggedFieldIndex(null);
      return;
    }

    const newFields = [...localFields];
    const draggedField = newFields[draggedFieldIndex];
    newFields.splice(draggedFieldIndex, 1);
    newFields.splice(targetIndex, 0, draggedField);
    handleFieldsChange(newFields);
    setDraggedFieldIndex(null);
  };

  // 필드 드래그 종료
  const handleFieldDragEnd = () => {
    setDraggedFieldIndex(null);
  };

  // 필드 수정 (입력 중 - 로컬 상태만)
  const updateFieldLocal = (index: number, field: "label" | "placeholder", value: string) => {
    setLocalInputs((prev) => ({
      ...prev,
      [index]: {
        ...prev[index],
        [field]: value,
      },
    }));
  };

  // 필드 수정 완료 (onBlur - 실제 업데이트)
  const handleFieldBlur = (index: number) => {
    const localInput = localInputs[index];
    if (localInput) {
      const newFields = [...localFields];
      newFields[index] = {
        ...newFields[index],
        label: localInput.label,
        placeholder: localInput.placeholder,
      };
      handleFieldsChange(newFields);
    }
  };

  // 필드 수정 (즉시 반영 - 드롭다운, 체크박스 등)
  const updateField = (index: number, updates: Partial<RepeaterFieldDefinition>) => {
    const newFields = [...localFields];
    newFields[index] = { ...newFields[index], ...updates };
    handleFieldsChange(newFields);
  };

  // 테이블 선택 Combobox 상태
  const [tableSelectOpen, setTableSelectOpen] = useState(false);
  const [tableSearchValue, setTableSearchValue] = useState("");

  // 하위 데이터 조회 설정 상태
  const [subDataTableSelectOpen, setSubDataTableSelectOpen] = useState(false);
  const [subDataTableSearchValue, setSubDataTableSearchValue] = useState("");
  const [subDataTableColumns, setSubDataTableColumns] = useState<ColumnInfo[]>([]);
  const [subDataLinkColumnOpen, setSubDataLinkColumnOpen] = useState(false);
  const [subDataLinkColumnSearch, setSubDataLinkColumnSearch] = useState("");

  // 하위 데이터 조회 테이블 컬럼 로드
  const loadSubDataTableColumns = async (tableName: string) => {
    if (!tableName) {
      setSubDataTableColumns([]);
      return;
    }
    try {
      const response = await apiClient.get(`/table-management/tables/${tableName}/columns`);
      let columns: ColumnInfo[] = [];
      if (response.data?.success && response.data?.data) {
        if (Array.isArray(response.data.data.columns)) {
          columns = response.data.data.columns;
        } else if (Array.isArray(response.data.data)) {
          columns = response.data.data;
        }
      } else if (Array.isArray(response.data)) {
        columns = response.data;
      }
      setSubDataTableColumns(columns);
      console.log("[RepeaterConfigPanel] 하위 데이터 테이블 컬럼 로드:", { tableName, count: columns.length });
    } catch (error) {
      console.error("[RepeaterConfigPanel] 하위 데이터 테이블 컬럼 로드 실패:", error);
      setSubDataTableColumns([]);
    }
  };

  // 하위 데이터 테이블이 설정되어 있으면 컬럼 로드
  useEffect(() => {
    if (config.subDataLookup?.lookup?.tableName) {
      loadSubDataTableColumns(config.subDataLookup.lookup.tableName);
    }
  }, [config.subDataLookup?.lookup?.tableName]);

  // 필터링된 테이블 목록
  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]);

  // 하위 데이터 조회 테이블 표시명
  const selectedSubDataTableLabel = useMemo(() => {
    const tableName = config.subDataLookup?.lookup?.tableName;
    if (!tableName) return "테이블을 선택하세요";
    const table = allTables.find((t) => t.tableName === tableName);
    return table ? `${table.displayName || table.tableName} (${tableName})` : tableName;
  }, [config.subDataLookup?.lookup?.tableName, allTables]);

  // 필터링된 하위 데이터 테이블 컬럼
  const filteredSubDataColumns = useMemo(() => {
    if (!subDataLinkColumnSearch) return subDataTableColumns;
    const searchLower = subDataLinkColumnSearch.toLowerCase();
    return subDataTableColumns.filter(
      (col) =>
        col.columnName.toLowerCase().includes(searchLower) ||
        (col.columnLabel && col.columnLabel.toLowerCase().includes(searchLower)),
    );
  }, [subDataTableColumns, subDataLinkColumnSearch]);

  // 하위 데이터 조회 설정 변경 핸들러
  const handleSubDataLookupChange = (path: string, value: any) => {
    const currentConfig = config.subDataLookup || {
      enabled: false,
      lookup: { tableName: "", linkColumn: "", displayColumns: [] },
      selection: { mode: "single", requiredFields: [], requiredMode: "all" },
      conditionalInput: { targetField: "" },
      ui: { expandMode: "inline", maxHeight: "150px", showSummary: true },
    };

    // 경로를 따라 중첩 객체 업데이트
    const pathParts = path.split(".");
    let target: any = { ...currentConfig };
    const newConfig = target;

    for (let i = 0; i < pathParts.length - 1; i++) {
      const part = pathParts[i];
      target[part] = { ...target[part] };
      target = target[part];
    }
    target[pathParts[pathParts.length - 1]] = value;

    onChange({
      ...config,
      subDataLookup: newConfig as SubDataLookupConfig,
    });
  };

  // 표시 컬럼 토글 핸들러
  const handleDisplayColumnToggle = (columnName: string, checked: boolean) => {
    const currentColumns = config.subDataLookup?.lookup?.displayColumns || [];
    let newColumns: string[];
    if (checked) {
      newColumns = [...currentColumns, columnName];
    } else {
      newColumns = currentColumns.filter((c) => c !== columnName);
    }
    handleSubDataLookupChange("lookup.displayColumns", newColumns);
  };

  // 필수 선택 필드 토글 핸들러
  const handleRequiredFieldToggle = (fieldName: string, checked: boolean) => {
    const currentFields = config.subDataLookup?.selection?.requiredFields || [];
    let newFields: string[];
    if (checked) {
      newFields = [...currentFields, fieldName];
    } else {
      newFields = currentFields.filter((f) => f !== fieldName);
    }
    handleSubDataLookupChange("selection.requiredFields", newFields);
  };

  // 컬럼 라벨 업데이트 핸들러
  const handleColumnLabelChange = (columnName: string, label: string) => {
    const currentLabels = config.subDataLookup?.lookup?.columnLabels || {};
    handleSubDataLookupChange("lookup.columnLabels", {
      ...currentLabels,
      [columnName]: label,
    });
  };

  // 표시 컬럼 순서 가져오기 (columnOrder가 있으면 사용, 없으면 displayColumns 순서)
  const getOrderedDisplayColumns = (): string[] => {
    const displayColumns = config.subDataLookup?.lookup?.displayColumns || [];
    const columnOrder = config.subDataLookup?.lookup?.columnOrder;
    
    if (columnOrder && columnOrder.length > 0) {
      // columnOrder에 있는 컬럼만, 순서대로 반환 (displayColumns에 있는 것만)
      const orderedCols = columnOrder.filter(col => displayColumns.includes(col));
      // columnOrder에 없지만 displayColumns에 있는 컬럼 추가
      const remainingCols = displayColumns.filter(col => !columnOrder.includes(col));
      return [...orderedCols, ...remainingCols];
    }
    return displayColumns;
  };

  // 표시 컬럼 순서 변경 핸들러 (위로)
  const handleDisplayColumnMoveUp = (columnName: string) => {
    const orderedColumns = getOrderedDisplayColumns();
    const index = orderedColumns.indexOf(columnName);
    if (index <= 0) return;
    
    const newOrder = [...orderedColumns];
    [newOrder[index - 1], newOrder[index]] = [newOrder[index], newOrder[index - 1]];
    handleSubDataLookupChange("lookup.columnOrder", newOrder);
  };

  // 표시 컬럼 순서 변경 핸들러 (아래로)
  const handleDisplayColumnMoveDown = (columnName: string) => {
    const orderedColumns = getOrderedDisplayColumns();
    const index = orderedColumns.indexOf(columnName);
    if (index < 0 || index >= orderedColumns.length - 1) return;
    
    const newOrder = [...orderedColumns];
    [newOrder[index], newOrder[index + 1]] = [newOrder[index + 1], newOrder[index]];
    handleSubDataLookupChange("lookup.columnOrder", newOrder);
  };

  // 표시 컬럼 토글 시 columnOrder도 업데이트
  const handleDisplayColumnToggleWithOrder = (columnName: string, checked: boolean) => {
    const currentColumns = config.subDataLookup?.lookup?.displayColumns || [];
    const currentOrder = config.subDataLookup?.lookup?.columnOrder || [];
    
    let newColumns: string[];
    let newOrder: string[];
    
    if (checked) {
      newColumns = [...currentColumns, columnName];
      newOrder = [...currentOrder, columnName];
    } else {
      newColumns = currentColumns.filter((c) => c !== columnName);
      newOrder = currentOrder.filter((c) => c !== columnName);
    }
    
    // displayColumns, columnOrder 함께 업데이트
    const newConfig = { ...config.subDataLookup } as SubDataLookupConfig;
    if (!newConfig.lookup) {
      newConfig.lookup = { tableName: "", linkColumn: "", displayColumns: [] };
    }
    newConfig.lookup.displayColumns = newColumns;
    newConfig.lookup.columnOrder = newOrder;
    
    onChange({
      ...config,
      subDataLookup: newConfig,
    });
  };


  return (
    <div className="space-y-4">
      {/* 대상 테이블 선택 */}
      <div className="space-y-2">
        <Label className="text-sm font-semibold">저장 대상 테이블</Label>
        <Popover open={tableSelectOpen} onOpenChange={setTableSelectOpen}>
          <PopoverTrigger asChild>
            <Button
              variant="outline"
              role="combobox"
              aria-expanded={tableSelectOpen}
              className="w-full justify-between"
            >
              {selectedTableLabel}
              <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
            </Button>
          </PopoverTrigger>
          <PopoverContent className="w-full p-0" align="start">
            <Command>
              <CommandInput placeholder="테이블 검색..." value={tableSearchValue} onValueChange={setTableSearchValue} />
              <CommandEmpty>테이블을 찾을 수 없습니다.</CommandEmpty>
              <CommandGroup className="max-h-64 overflow-auto">
                {filteredTables.map((table) => (
                  <CommandItem
                    key={table.tableName}
                    value={table.tableName}
                    onSelect={(currentValue) => {
                      handleChange("targetTable", currentValue);
                      setTableSelectOpen(false);
                      setTableSearchValue("");
                      // 선택된 테이블의 컬럼 로드
                      if (onTableChange) {
                        onTableChange(currentValue);
                      }
                    }}
                  >
                    <Check
                      className={cn(
                        "mr-2 h-4 w-4",
                        config.targetTable === table.tableName ? "opacity-100" : "opacity-0",
                      )}
                    />
                    {table.displayName || table.tableName}
                  </CommandItem>
                ))}
              </CommandGroup>
            </Command>
          </PopoverContent>
        </Popover>
        <p className="text-xs text-muted-foreground">반복 필드 데이터를 저장할 테이블을 선택하세요.</p>
      </div>

      {/* 그룹화 컬럼 설정 */}
      <div className="space-y-2">
        <Label className="text-sm font-semibold">수정 시 그룹화 컬럼 (선택)</Label>
        <Select
          value={config.groupByColumn || "__none__"}
          onValueChange={(value) => handleChange("groupByColumn", value === "__none__" ? undefined : value)}
        >
          <SelectTrigger className="h-9">
            <SelectValue placeholder="그룹화 컬럼 선택 (선택사항)" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="__none__">사용 안함</SelectItem>
            {tableColumns.map((col) => (
              <SelectItem key={col.columnName} value={col.columnName}>
                {col.columnLabel || col.columnName}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
        <p className="text-xs text-muted-foreground">
          수정 모드에서 이 컬럼 값을 기준으로 관련된 모든 데이터를 조회합니다.
          <br />
          예: 입고번호를 선택하면 같은 입고번호를 가진 모든 품목이 표시됩니다.
        </p>
      </div>

      {/* 🆕 FK 컬럼 설정 (분할 패널용) */}
      <div className="space-y-2">
        <Label className="text-sm font-semibold">FK 연결 컬럼 (분할 패널용)</Label>
        <Select
          value={(config as any).fkColumn || "__none__"}
          onValueChange={(value) => handleChange("fkColumn" as any, value === "__none__" ? undefined : value)}
        >
          <SelectTrigger className="h-9">
            <SelectValue placeholder="FK 컬럼 선택 (선택사항)" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="__none__">사용 안함 (그룹화 컬럼 사용)</SelectItem>
            {tableColumns.map((col) => (
              <SelectItem key={col.columnName} value={col.columnName}>
                {col.columnLabel || col.columnName}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
        <p className="text-xs text-muted-foreground">
          분할 패널에서 좌측 테이블 선택 시 이 컬럼을 기준으로 데이터를 필터링합니다.
          <br />
          예: serial_no를 선택하면 좌측에서 선택한 장비의 serial_no에 해당하는 데이터만 표시됩니다.
        </p>
      </div>

      {/* 하위 데이터 조회 설정 */}
      <div className="space-y-3 rounded-lg border-2 border-purple-200 bg-purple-50/30 p-3">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-2">
            <Database className="h-4 w-4 text-purple-600" />
            <Label className="text-sm font-semibold text-purple-800">하위 데이터 조회</Label>
          </div>
          <Switch
            checked={config.subDataLookup?.enabled ?? false}
            onCheckedChange={(checked) => handleSubDataLookupChange("enabled", checked)}
          />
        </div>
        <p className="text-xs text-purple-600">
          품목 선택 시 재고/단가 등 관련 데이터를 조회하고 선택할 수 있습니다.
        </p>

        {config.subDataLookup?.enabled && (
          <div className="space-y-4 pt-2">
            {/* 조회 테이블 선택 */}
            <div className="space-y-2">
              <Label className="text-xs font-medium text-purple-700">조회 테이블</Label>
              <Popover open={subDataTableSelectOpen} onOpenChange={setSubDataTableSelectOpen}>
                <PopoverTrigger asChild>
                  <Button
                    variant="outline"
                    role="combobox"
                    aria-expanded={subDataTableSelectOpen}
                    className="h-9 w-full justify-between text-xs"
                  >
                    {selectedSubDataTableLabel}
                    <ChevronsUpDown className="ml-2 h-3 w-3 shrink-0 opacity-50" />
                  </Button>
                </PopoverTrigger>
                <PopoverContent className="w-full p-0" align="start">
                  <Command>
                    <CommandInput
                      placeholder="테이블 검색..."
                      value={subDataTableSearchValue}
                      onValueChange={setSubDataTableSearchValue}
                      className="h-8 text-xs"
                    />
                    <CommandEmpty>테이블을 찾을 수 없습니다.</CommandEmpty>
                    <CommandGroup className="max-h-48 overflow-auto">
                      {allTables
                        .filter((table) => {
                          if (!subDataTableSearchValue) return true;
                          const searchLower = subDataTableSearchValue.toLowerCase();
                          return (
                            table.tableName.toLowerCase().includes(searchLower) ||
                            (table.displayName && table.displayName.toLowerCase().includes(searchLower))
                          );
                        })
                        .map((table) => (
                          <CommandItem
                            key={table.tableName}
                            value={table.tableName}
                            onSelect={(currentValue) => {
                              handleSubDataLookupChange("lookup.tableName", currentValue);
                              loadSubDataTableColumns(currentValue);
                              setSubDataTableSelectOpen(false);
                              setSubDataTableSearchValue("");
                            }}
                            className="text-xs"
                          >
                            <Check
                              className={cn(
                                "mr-2 h-3 w-3",
                                config.subDataLookup?.lookup?.tableName === table.tableName
                                  ? "opacity-100"
                                  : "opacity-0",
                              )}
                            />
                            <div>
                              <div className="font-medium">{table.displayName || table.tableName}</div>
                              <div className="text-muted-foreground">{table.tableName}</div>
                            </div>
                          </CommandItem>
                        ))}
                    </CommandGroup>
                  </Command>
                </PopoverContent>
              </Popover>
              <p className="text-[10px] text-purple-500">예: inventory (재고), price_list (단가표)</p>
            </div>

            {/* 연결 컬럼 선택 */}
            {config.subDataLookup?.lookup?.tableName && (
              <div className="space-y-2">
                <Label className="text-xs font-medium text-purple-700">연결 컬럼</Label>
                <Popover open={subDataLinkColumnOpen} onOpenChange={setSubDataLinkColumnOpen}>
                  <PopoverTrigger asChild>
                    <Button
                      variant="outline"
                      role="combobox"
                      aria-expanded={subDataLinkColumnOpen}
                      className="h-9 w-full justify-between text-xs"
                    >
                      {config.subDataLookup?.lookup?.linkColumn
                        ? (() => {
                            const col = subDataTableColumns.find(
                              (c) => c.columnName === config.subDataLookup?.lookup?.linkColumn,
                            );
                            return col
                              ? `${col.columnLabel || col.columnName} (${col.columnName})`
                              : config.subDataLookup?.lookup?.linkColumn;
                          })()
                        : "연결 컬럼 선택"}
                      <ChevronsUpDown className="ml-2 h-3 w-3 shrink-0 opacity-50" />
                    </Button>
                  </PopoverTrigger>
                  <PopoverContent className="w-full p-0" align="start">
                    <Command>
                      <CommandInput
                        placeholder="컬럼 검색..."
                        value={subDataLinkColumnSearch}
                        onValueChange={setSubDataLinkColumnSearch}
                        className="h-8 text-xs"
                      />
                      <CommandEmpty>컬럼을 찾을 수 없습니다.</CommandEmpty>
                      <CommandGroup className="max-h-48 overflow-auto">
                        {filteredSubDataColumns.map((col) => (
                          <CommandItem
                            key={col.columnName}
                            value={col.columnName}
                            onSelect={(currentValue) => {
                              handleSubDataLookupChange("lookup.linkColumn", currentValue);
                              setSubDataLinkColumnOpen(false);
                              setSubDataLinkColumnSearch("");
                            }}
                            className="text-xs"
                          >
                            <Check
                              className={cn(
                                "mr-2 h-3 w-3",
                                config.subDataLookup?.lookup?.linkColumn === col.columnName
                                  ? "opacity-100"
                                  : "opacity-0",
                              )}
                            />
                            <div>
                              <div className="font-medium">{col.columnLabel || col.columnName}</div>
                              <div className="text-muted-foreground">{col.columnName}</div>
                            </div>
                          </CommandItem>
                        ))}
                      </CommandGroup>
                    </Command>
                  </PopoverContent>
                </Popover>
                <p className="text-[10px] text-purple-500">상위 데이터와 연결할 컬럼 (예: item_code)</p>
              </div>
            )}

            {/* 표시 컬럼 선택 */}
            {config.subDataLookup?.lookup?.tableName && subDataTableColumns.length > 0 && (
              <div className="space-y-2">
                <Label className="text-xs font-medium text-purple-700">표시 컬럼</Label>
                <div className="max-h-32 space-y-1 overflow-y-auto rounded border bg-white p-2">
                  {subDataTableColumns.map((col) => {
                    const isSelected = config.subDataLookup?.lookup?.displayColumns?.includes(col.columnName);
                    return (
                      <div key={col.columnName} className="flex items-center gap-2">
                        <Checkbox
                          id={`display-col-${col.columnName}`}
                          checked={isSelected}
                          onCheckedChange={(checked) => handleDisplayColumnToggleWithOrder(col.columnName, checked as boolean)}
                        />
                        <Label
                          htmlFor={`display-col-${col.columnName}`}
                          className="flex-1 cursor-pointer text-xs font-normal"
                        >
                          {col.columnLabel || col.columnName}
                          <span className="ml-1 text-muted-foreground/70">({col.columnName})</span>
                        </Label>
                      </div>
                    );
                  })}
                </div>
                <p className="text-[10px] text-purple-500">조회 결과에 표시할 컬럼들 (예: 창고, 위치, 수량)</p>
              </div>
            )}

            {/* 컬럼 설정 (순서 + 라벨 + 저장 컬럼) */}
            {(config.subDataLookup?.lookup?.displayColumns?.length || 0) > 0 && (
              <div className="space-y-2">
                <Label className="text-xs font-medium text-purple-700">컬럼 설정</Label>
                <p className="text-[10px] text-purple-500">순서, 라벨, 저장 여부를 설정하세요</p>
                <div className="space-y-1.5 rounded border bg-white p-2">
                  {getOrderedDisplayColumns().map((colName, index) => {
                    const col = subDataTableColumns.find((c) => c.columnName === colName);
                    const currentLabel = config.subDataLookup?.lookup?.columnLabels?.[colName] || "";
                    const orderedColumns = getOrderedDisplayColumns();
                    const isFirst = index === 0;
                    const isLast = index === orderedColumns.length - 1;
                    
                    return (
                      <div key={colName} className="rounded bg-purple-50 p-2">
                        {/* 상단: 순서 버튼 + 번호 + 컬럼명 */}
                        <div className="flex items-center gap-2">
                          {/* 순서 변경 버튼 */}
                          <div className="flex items-center gap-0.5">
                            <Button
                              type="button"
                              variant="ghost"
                              size="sm"
                              className="h-5 w-5 p-0"
                              onClick={() => handleDisplayColumnMoveUp(colName)}
                              disabled={isFirst}
                            >
                              <ArrowUp className={cn("h-3 w-3", isFirst ? "text-muted-foreground/50" : "text-purple-600")} />
                            </Button>
                            <Button
                              type="button"
                              variant="ghost"
                              size="sm"
                              className="h-5 w-5 p-0"
                              onClick={() => handleDisplayColumnMoveDown(colName)}
                              disabled={isLast}
                            >
                              <ArrowDown className={cn("h-3 w-3", isLast ? "text-muted-foreground/50" : "text-purple-600")} />
                            </Button>
                          </div>
                          
                          {/* 순서 번호 */}
                          <span className="w-4 text-center text-xs font-medium text-purple-600">{index + 1}</span>
                          
                          {/* 컬럼명 */}
                          <div className="flex-1 text-xs">
                            <span className="font-medium">{col?.columnLabel || colName}</span>
                            <span className="ml-1 text-muted-foreground/70">({colName})</span>
                          </div>
                        </div>
                        
                        {/* 중단: 라벨 입력 */}
                        <div className="mt-1.5 flex items-center gap-2">
                          <span className="text-[10px] text-muted-foreground whitespace-nowrap">표시 라벨:</span>
                          <Input
                            value={currentLabel}
                            onChange={(e) => handleColumnLabelChange(colName, e.target.value)}
                            placeholder={col?.columnLabel || colName}
                            className="h-6 flex-1 text-xs"
                          />
                        </div>
                        
                      </div>
                    );
                  })}
                </div>
                <p className="text-[10px] text-purple-500">
                  * 저장 설정은 필드 정의에서 "하위 데이터 조회에서 값 가져오기"로 설정하세요
                </p>
              </div>
            )}

            {/* 선택 설정 */}
            {(config.subDataLookup?.lookup?.displayColumns?.length || 0) > 0 && (
              <div className="space-y-3 border-t border-purple-200 pt-3">
                <Label className="text-xs font-medium text-purple-700">선택 설정</Label>

                {/* 선택 모드 */}
                <div className="space-y-2">
                  <Label className="text-[10px] text-purple-600">선택 모드</Label>
                  <Select
                    value={config.subDataLookup?.selection?.mode || "single"}
                    onValueChange={(v) => handleSubDataLookupChange("selection.mode", v)}
                  >
                    <SelectTrigger className="h-8 text-xs">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="single" className="text-xs">
                        단일 선택
                      </SelectItem>
                      <SelectItem value="multiple" className="text-xs">
                        다중 선택
                      </SelectItem>
                    </SelectContent>
                  </Select>
                </div>

                {/* 필수 선택 필드 */}
                <div className="space-y-2">
                  <Label className="text-[10px] text-purple-600">필수 선택 필드</Label>
                  <div className="flex flex-wrap gap-2">
                    {config.subDataLookup?.lookup?.displayColumns?.map((colName) => {
                      const col = subDataTableColumns.find((c) => c.columnName === colName);
                      const isRequired = config.subDataLookup?.selection?.requiredFields?.includes(colName);
                      return (
                        <div key={colName} className="flex items-center gap-1">
                          <Checkbox
                            id={`required-field-${colName}`}
                            checked={isRequired}
                            onCheckedChange={(checked) => handleRequiredFieldToggle(colName, checked as boolean)}
                          />
                          <Label htmlFor={`required-field-${colName}`} className="cursor-pointer text-xs font-normal">
                            {col?.columnLabel || colName}
                          </Label>
                        </div>
                      );
                    })}
                  </div>
                  <p className="text-[10px] text-purple-500">이 필드들이 선택되어야 입력이 활성화됩니다</p>
                </div>

                {/* 필수 조건 */}
                {(config.subDataLookup?.selection?.requiredFields?.length || 0) > 1 && (
                  <div className="space-y-2">
                    <Label className="text-[10px] text-purple-600">필수 조건</Label>
                    <Select
                      value={config.subDataLookup?.selection?.requiredMode || "all"}
                      onValueChange={(v) => handleSubDataLookupChange("selection.requiredMode", v)}
                    >
                      <SelectTrigger className="h-8 text-xs">
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="all" className="text-xs">
                          모두 선택해야 함
                        </SelectItem>
                        <SelectItem value="any" className="text-xs">
                          하나만 선택해도 됨
                        </SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                )}
              </div>
            )}

            {/* 조건부 입력 설정 */}
            {(config.subDataLookup?.lookup?.displayColumns?.length || 0) > 0 && (
              <div className="space-y-3 border-t border-purple-200 pt-3">
                <Label className="text-xs font-medium text-purple-700">조건부 입력 설정</Label>

                {/* 활성화 대상 필드 */}
                <div className="space-y-2">
                  <Label className="text-[10px] text-purple-600">활성화 대상 필드</Label>
                  <Select
                    value={config.subDataLookup?.conditionalInput?.targetField || "__none__"}
                    onValueChange={(v) =>
                      handleSubDataLookupChange("conditionalInput.targetField", v === "__none__" ? "" : v)
                    }
                  >
                    <SelectTrigger className="h-8 text-xs">
                      <SelectValue placeholder="필드 선택" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="__none__" className="text-xs">
                        선택 안함
                      </SelectItem>
                      {localFields.length === 0 ? (
                        <SelectItem value="__empty__" disabled className="text-xs text-muted-foreground/70">
                          필드 정의에서 먼저 필드를 추가하세요
                        </SelectItem>
                      ) : (
                        localFields.map((f) => (
                          <SelectItem key={f.name} value={f.name} className="text-xs">
                            {f.label || f.name} ({f.name})
                          </SelectItem>
                        ))
                      )}
                    </SelectContent>
                  </Select>
                  <p className="text-[10px] text-purple-500">
                    하위 데이터 선택 후 입력이 활성화될 필드 (예: 출고수량)
                    {localFields.length === 0 && (
                      <span className="ml-1 text-amber-600">* 필드 정의 필요</span>
                    )}
                  </p>
                </div>

                {/* 최대값 참조 필드 */}
                <div className="space-y-2">
                  <Label className="text-[10px] text-purple-600">최대값 참조 필드 (선택)</Label>
                  <Select
                    value={config.subDataLookup?.conditionalInput?.maxValueField || "__none__"}
                    onValueChange={(v) =>
                      handleSubDataLookupChange("conditionalInput.maxValueField", v === "__none__" ? undefined : v)
                    }
                  >
                    <SelectTrigger className="h-8 text-xs">
                      <SelectValue placeholder="필드 선택" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="__none__" className="text-xs">
                        사용 안함
                      </SelectItem>
                      {subDataTableColumns.map((col) => (
                        <SelectItem key={col.columnName} value={col.columnName} className="text-xs">
                          {col.columnLabel || col.columnName} ({col.columnName})
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  <p className="text-[10px] text-purple-500">입력 최대값을 제한할 하위 데이터 필드 (예: 재고수량)</p>
                </div>

                {/* 경고 임계값 */}
                {config.subDataLookup?.conditionalInput?.maxValueField && (
                  <div className="space-y-2">
                    <Label className="text-[10px] text-purple-600">경고 임계값 (%)</Label>
                    <Input
                      type="number"
                      min={0}
                      max={100}
                      value={config.subDataLookup?.conditionalInput?.warningThreshold ?? 90}
                      onChange={(e) =>
                        handleSubDataLookupChange("conditionalInput.warningThreshold", parseInt(e.target.value) || 90)
                      }
                      className="h-8 text-xs"
                    />
                    <p className="text-[10px] text-purple-500">이 비율 이상 입력 시 경고 표시 (예: 90%)</p>
                  </div>
                )}
              </div>
            )}

            {/* UI 설정 */}
            {(config.subDataLookup?.lookup?.displayColumns?.length || 0) > 0 && (
              <div className="space-y-3 border-t border-purple-200 pt-3">
                <Label className="text-xs font-medium text-purple-700">UI 설정</Label>

                {/* 확장 방식 */}
                <div className="space-y-2">
                  <Label className="text-[10px] text-purple-600">확장 방식</Label>
                  <Select
                    value={config.subDataLookup?.ui?.expandMode || "inline"}
                    onValueChange={(v) => handleSubDataLookupChange("ui.expandMode", v)}
                  >
                    <SelectTrigger className="h-8 text-xs">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="inline" className="text-xs">
                        인라인 (행 아래 확장)
                      </SelectItem>
                      <SelectItem value="modal" className="text-xs">
                        모달 (팝업)
                      </SelectItem>
                    </SelectContent>
                  </Select>
                </div>

                {/* 최대 높이 */}
                {config.subDataLookup?.ui?.expandMode === "inline" && (
                  <div className="space-y-2">
                    <Label className="text-[10px] text-purple-600">최대 높이</Label>
                    <Input
                      value={config.subDataLookup?.ui?.maxHeight || "150px"}
                      onChange={(e) => handleSubDataLookupChange("ui.maxHeight", e.target.value)}
                      placeholder="150px"
                      className="h-8 text-xs"
                    />
                  </div>
                )}

                {/* 요약 정보 표시 */}
                <div className="flex items-center space-x-2">
                  <Checkbox
                    id="sub-data-show-summary"
                    checked={config.subDataLookup?.ui?.showSummary ?? true}
                    onCheckedChange={(checked) => handleSubDataLookupChange("ui.showSummary", checked)}
                  />
                  <Label htmlFor="sub-data-show-summary" className="cursor-pointer text-xs font-normal">
                    요약 정보 표시
                  </Label>
                </div>
              </div>
            )}

            {/* 설정 요약 */}
            {config.subDataLookup?.lookup?.tableName && (
              <div className="rounded bg-purple-100 p-2 text-xs">
                <p className="font-medium text-purple-800">설정 요약</p>
                <ul className="mt-1 space-y-0.5 text-purple-700">
                  <li>조회 테이블: {config.subDataLookup?.lookup?.tableName || "-"}</li>
                  <li>연결 컬럼: {config.subDataLookup?.lookup?.linkColumn || "-"}</li>
                  <li>표시 컬럼: {config.subDataLookup?.lookup?.displayColumns?.join(", ") || "-"}</li>
                  <li>필수 선택: {config.subDataLookup?.selection?.requiredFields?.join(", ") || "-"}</li>
                  <li>활성화 필드: {config.subDataLookup?.conditionalInput?.targetField || "-"}</li>
                </ul>
              </div>
            )}
          </div>
        )}
      </div>

      {/* 필드 정의 */}
      <div className="space-y-3">
        <div className="flex items-center justify-between">
          <Label className="text-sm font-semibold">필드 정의</Label>
          <span className="text-xs text-muted-foreground">드래그하거나 화살표로 순서 변경</span>
        </div>

        {localFields.map((field, index) => (
          <Card
            key={`${field.name}-${index}`}
            className={cn(
              "border-2 transition-all",
              draggedFieldIndex === index && "opacity-50 border-primary/60",
              draggedFieldIndex !== null && draggedFieldIndex !== index && "border-dashed",
            )}
            draggable
            onDragStart={() => handleFieldDragStart(index)}
            onDragOver={(e) => handleFieldDragOver(e, index)}
            onDrop={(e) => handleFieldDrop(e, index)}
            onDragEnd={handleFieldDragEnd}
          >
            <CardContent className="space-y-3 pt-4">
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-2">
                  {/* 드래그 핸들 */}
                  <GripVertical className="h-4 w-4 cursor-move text-muted-foreground/70 hover:text-muted-foreground" />
                  <span className="text-sm font-semibold text-foreground">필드 {index + 1}</span>
                </div>
                <div className="flex items-center gap-1">
                  {/* 순서 변경 버튼 */}
                  <Button
                    type="button"
                    variant="ghost"
                    size="icon"
                    onClick={() => moveFieldUp(index)}
                    disabled={index === 0}
                    className="h-6 w-6 text-muted-foreground hover:bg-muted disabled:opacity-30"
                    title="위로 이동"
                  >
                    <ArrowUp className="h-3 w-3" />
                  </Button>
                  <Button
                    type="button"
                    variant="ghost"
                    size="icon"
                    onClick={() => moveFieldDown(index)}
                    disabled={index === localFields.length - 1}
                    className="h-6 w-6 text-muted-foreground hover:bg-muted disabled:opacity-30"
                    title="아래로 이동"
                  >
                    <ArrowDown className="h-3 w-3" />
                  </Button>
                  {/* 삭제 버튼 */}
                  <Button
                    type="button"
                    variant="ghost"
                    size="icon"
                    onClick={() => removeField(index)}
                    className="h-6 w-6 text-destructive hover:bg-destructive/10"
                    title="삭제"
                  >
                    <X className="h-3 w-3" />
                  </Button>
                </div>
              </div>

              <div className="grid grid-cols-2 gap-3">
                <div className="space-y-1">
                  <Label className="text-xs">필드명 (컬럼)</Label>
                  <Popover
                    open={fieldNamePopoverOpen[index] || false}
                    onOpenChange={(open) => setFieldNamePopoverOpen({ ...fieldNamePopoverOpen, [index]: open })}
                  >
                    <PopoverTrigger asChild>
                      <Button variant="outline" role="combobox" className="h-8 w-full justify-between text-xs">
                        {field.name || "컬럼 선택"}
                        <ChevronsUpDown className="ml-2 h-3 w-3 shrink-0 opacity-50" />
                      </Button>
                    </PopoverTrigger>
                    <PopoverContent className="w-[200px] p-0">
                      <Command>
                        <CommandInput placeholder="컬럼 검색..." className="h-8 text-xs" />
                        <CommandEmpty>사용 가능한 컬럼이 없습니다.</CommandEmpty>
                        <CommandGroup className="max-h-[200px] overflow-auto">
                          {getAvailableColumns(field.name).map((column) => (
                            <CommandItem
                              key={column.columnName}
                              value={column.columnName}
                              onSelect={() => {
                                // input_type (DB에서 설정한 타입) 우선 사용, 없으면 webType/widgetType
                                const col = column as any;
                                const fieldType =
                                  col.input_type || col.inputType || col.webType || col.widgetType || "text";

                                console.log("🔍 [RepeaterConfigPanel] 필드 타입 결정:", {
                                  columnName: column.columnName,
                                  input_type: col.input_type,
                                  inputType: col.inputType,
                                  webType: col.webType,
                                  widgetType: col.widgetType,
                                  finalType: fieldType,
                                });

                                updateField(index, {
                                  name: column.columnName,
                                  label: column.columnLabel || column.columnName,
                                  type: fieldType as RepeaterFieldType,
                                });
                                // 로컬 입력 상태도 업데이트
                                setLocalInputs((prev) => ({
                                  ...prev,
                                  [index]: {
                                    label: column.columnLabel || column.columnName,
                                    placeholder: prev[index]?.placeholder || "",
                                  },
                                }));
                                setFieldNamePopoverOpen({ ...fieldNamePopoverOpen, [index]: false });
                              }}
                              className="text-xs"
                            >
                              <Check
                                className={cn(
                                  "mr-2 h-3 w-3",
                                  field.name === column.columnName ? "opacity-100" : "opacity-0",
                                )}
                              />
                              <div>
                                <div className="font-medium">{column.columnLabel}</div>
                                <div className="text-muted-foreground">{column.columnName}</div>
                              </div>
                            </CommandItem>
                          ))}
                        </CommandGroup>
                      </Command>
                    </PopoverContent>
                  </Popover>
                </div>

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

              <div className="grid grid-cols-2 gap-3">
                <div className="space-y-1">
                  <Label className="text-xs">타입</Label>
                  <Select
                    value={field.type}
                    onValueChange={(value) => updateField(index, { type: value as RepeaterFieldType })}
                  >
                    <SelectTrigger className="h-8 w-full">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      {/* 테이블 타입 관리에서 사용하는 input_type 목록 */}
                      <SelectItem value="text">텍스트 (text)</SelectItem>
                      <SelectItem value="number">숫자 (number)</SelectItem>
                      <SelectItem value="textarea">텍스트영역 (textarea)</SelectItem>
                      <SelectItem value="date">날짜 (date)</SelectItem>
                      <SelectItem value="select">선택박스 (select)</SelectItem>
                      <SelectItem value="checkbox">체크박스 (checkbox)</SelectItem>
                      <SelectItem value="radio">라디오 (radio)</SelectItem>
                      <SelectItem value="category">카테고리 (category)</SelectItem>
                      <SelectItem value="entity">엔티티 참조 (entity)</SelectItem>
                      <SelectItem value="code">공통코드 (code)</SelectItem>
                      <SelectItem value="image">이미지 (image)</SelectItem>
                      <SelectItem value="direct">직접입력 (direct)</SelectItem>
                      <SelectItem value="calculated">
                        <span className="flex items-center gap-1">
                          <Calculator className="h-3 w-3" />
                          계산식 (calculated)
                        </span>
                      </SelectItem>
                    </SelectContent>
                  </Select>
                </div>

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

              {/* 계산식 타입일 때 계산식 설정 */}
              {field.type === "calculated" && (
                <div className="space-y-3 rounded-lg border border-primary/20 bg-primary/10 p-3">
                  <div className="flex items-center gap-2">
                    <Calculator className="h-4 w-4 text-primary" />
                    <Label className="text-xs font-semibold text-primary">계산식 설정</Label>
                  </div>

                  {/* 필드 1 선택 */}
                  <div className="space-y-1">
                    <Label className="text-[10px] text-primary">필드 1</Label>
                    <Select
                      value={field.formula?.field1 || ""}
                      onValueChange={(value) =>
                        updateField(index, {
                          formula: { ...field.formula, field1: value } as CalculationFormula,
                        })
                      }
                    >
                      <SelectTrigger className="h-8 text-xs">
                        <SelectValue placeholder="필드 선택" />
                      </SelectTrigger>
                      <SelectContent className="z-[9999]">
                        {localFields
                          .filter((f, i) => i !== index && f.type !== "calculated" && f.type !== "category")
                          .map((f) => (
                            <SelectItem key={f.name} value={f.name} className="text-xs">
                              {f.label || f.name}
                            </SelectItem>
                          ))}
                      </SelectContent>
                    </Select>
                  </div>

                  {/* 연산자 선택 */}
                  <div className="space-y-1">
                    <Label className="text-[10px] text-primary">연산자</Label>
                    <Select
                      value={field.formula?.operator || "+"}
                      onValueChange={(value) =>
                        updateField(index, {
                          formula: { ...field.formula, operator: value as CalculationOperator } as CalculationFormula,
                        })
                      }
                    >
                      <SelectTrigger className="h-8 text-xs">
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent className="z-[9999]">
                        <SelectItem value="+" className="text-xs">
                          + 더하기
                        </SelectItem>
                        <SelectItem value="-" className="text-xs">
                          - 빼기
                        </SelectItem>
                        <SelectItem value="*" className="text-xs">
                          × 곱하기
                        </SelectItem>
                        <SelectItem value="/" className="text-xs">
                          ÷ 나누기
                        </SelectItem>
                        <SelectItem value="%" className="text-xs">
                          % 나머지
                        </SelectItem>
                        <SelectItem value="round" className="text-xs">
                          반올림
                        </SelectItem>
                        <SelectItem value="floor" className="text-xs">
                          내림
                        </SelectItem>
                        <SelectItem value="ceil" className="text-xs">
                          올림
                        </SelectItem>
                      </SelectContent>
                    </Select>
                  </div>

                  {/* 두 번째 필드 또는 상수값 */}
                  {!["round", "floor", "ceil", "abs"].includes(field.formula?.operator || "") ? (
                    <div className="space-y-1">
                      <Label className="text-[10px] text-primary">필드 2 / 상수</Label>
                      <Select
                        value={
                          field.formula?.field2 ||
                          (field.formula?.constantValue !== undefined ? `__const__${field.formula.constantValue}` : "")
                        }
                        onValueChange={(value) => {
                          if (value.startsWith("__const__")) {
                            updateField(index, {
                              formula: {
                                ...field.formula,
                                field2: undefined,
                                constantValue: 0,
                              } as CalculationFormula,
                            });
                          } else {
                            updateField(index, {
                              formula: {
                                ...field.formula,
                                field2: value,
                                constantValue: undefined,
                              } as CalculationFormula,
                            });
                          }
                        }}
                      >
                        <SelectTrigger className="h-8 text-xs">
                          <SelectValue placeholder="필드 선택" />
                        </SelectTrigger>
                        <SelectContent className="z-[9999]">
                          {localFields
                            .filter((f, i) => i !== index && f.type !== "calculated" && f.type !== "category")
                            .map((f) => (
                              <SelectItem key={f.name} value={f.name} className="text-xs">
                                {f.label || f.name}
                              </SelectItem>
                            ))}
                          <SelectItem value="__const__0" className="text-xs text-primary">
                            상수값 입력
                          </SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                  ) : (
                    <div className="space-y-1">
                      <Label className="text-[10px] text-primary">소수점 자릿수</Label>
                      <Input
                        type="number"
                        min={0}
                        max={10}
                        value={field.formula?.decimalPlaces ?? 0}
                        onChange={(e) =>
                          updateField(index, {
                            formula: {
                              ...field.formula,
                              decimalPlaces: parseInt(e.target.value) || 0,
                            } as CalculationFormula,
                          })
                        }
                        className="h-8 text-xs"
                      />
                    </div>
                  )}

                  {/* 상수값 입력 필드 */}
                  {field.formula?.constantValue !== undefined && (
                    <div className="space-y-1">
                      <Label className="text-[10px] text-primary">상수값</Label>
                      <Input
                        type="number"
                        value={field.formula.constantValue}
                        onChange={(e) =>
                          updateField(index, {
                            formula: {
                              ...field.formula,
                              constantValue: parseFloat(e.target.value) || 0,
                            } as CalculationFormula,
                          })
                        }
                        placeholder="숫자 입력"
                        className="h-8 text-xs"
                      />
                    </div>
                  )}

                  {/* 숫자 포맷 설정 */}
                  <div className="space-y-2 border-t border-primary/20 pt-2">
                    <Label className="text-[10px] text-primary">숫자 표시 형식</Label>
                    <div className="flex items-center gap-4">
                      <div className="flex items-center space-x-2">
                        <Checkbox
                          id={`thousand-sep-${index}`}
                          checked={field.numberFormat?.useThousandSeparator ?? true}
                          onCheckedChange={(checked) =>
                            updateField(index, {
                              numberFormat: { ...field.numberFormat, useThousandSeparator: checked as boolean },
                            })
                          }
                        />
                        <Label htmlFor={`thousand-sep-${index}`} className="cursor-pointer text-[10px]">
                          천 단위 구분자
                        </Label>
                      </div>
                      <div className="flex items-center gap-1">
                        <Label className="text-[10px]">소수점:</Label>
                        <Input
                          value={field.numberFormat?.decimalPlaces ?? 0}
                          onChange={(e) =>
                            updateField(index, {
                              numberFormat: { ...field.numberFormat, decimalPlaces: parseInt(e.target.value) || 0 },
                            })
                          }
                          type="number"
                          min={0}
                          max={10}
                          className="h-6 w-12 text-[10px]"
                        />
                      </div>
                    </div>
                    <div className="grid grid-cols-2 gap-2">
                      <Input
                        value={field.numberFormat?.prefix || ""}
                        onChange={(e) =>
                          updateField(index, {
                            numberFormat: { ...field.numberFormat, prefix: e.target.value },
                          })
                        }
                        placeholder="접두사 (₩)"
                        className="h-7 text-[10px]"
                      />
                      <Input
                        value={field.numberFormat?.suffix || ""}
                        onChange={(e) =>
                          updateField(index, {
                            numberFormat: { ...field.numberFormat, suffix: e.target.value },
                          })
                        }
                        placeholder="접미사 (원)"
                        className="h-7 text-[10px]"
                      />
                    </div>
                  </div>

                  {/* 계산식 미리보기 */}
                  <div className="rounded bg-white p-2 text-xs">
                    <span className="text-muted-foreground">계산식: </span>
                    <code className="font-mono text-primary">
                      {field.formula?.field1 || "필드1"} {field.formula?.operator || "+"}{" "}
                      {field.formula?.field2 ||
                        (field.formula?.constantValue !== undefined ? field.formula.constantValue : "필드2")}
                    </code>
                  </div>
                </div>
              )}

              {/* 숫자 타입일 때 숫자 표시 형식 설정 */}
              {field.type === "number" && (
                <div className="space-y-2 rounded-lg border border-border bg-muted p-3">
                  <Label className="text-xs font-semibold text-foreground">숫자 표시 형식</Label>
                  <div className="flex items-center gap-4">
                    <div className="flex items-center space-x-2">
                      <Checkbox
                        id={`number-thousand-sep-${index}`}
                        checked={field.numberFormat?.useThousandSeparator ?? false}
                        onCheckedChange={(checked) =>
                          updateField(index, {
                            numberFormat: { ...field.numberFormat, useThousandSeparator: checked as boolean },
                          })
                        }
                      />
                      <Label htmlFor={`number-thousand-sep-${index}`} className="cursor-pointer text-[10px]">
                        천 단위 구분자
                      </Label>
                    </div>
                    <div className="flex items-center gap-1">
                      <Label className="text-[10px]">소수점:</Label>
                      <Input
                        value={field.numberFormat?.decimalPlaces ?? 0}
                        onChange={(e) =>
                          updateField(index, {
                            numberFormat: { ...field.numberFormat, decimalPlaces: parseInt(e.target.value) || 0 },
                          })
                        }
                        type="number"
                        min={0}
                        max={10}
                        className="h-6 w-12 text-[10px]"
                      />
                    </div>
                  </div>
                  <div className="grid grid-cols-2 gap-2">
                    <Input
                      value={field.numberFormat?.prefix || ""}
                      onChange={(e) =>
                        updateField(index, {
                          numberFormat: { ...field.numberFormat, prefix: e.target.value },
                        })
                      }
                      placeholder="접두사 (₩)"
                      className="h-7 text-[10px]"
                    />
                    <Input
                      value={field.numberFormat?.suffix || ""}
                      onChange={(e) =>
                        updateField(index, {
                          numberFormat: { ...field.numberFormat, suffix: e.target.value },
                        })
                      }
                      placeholder="접미사 (원)"
                      className="h-7 text-[10px]"
                    />
                  </div>
                </div>
              )}

              {/* 카테고리 타입일 때 카테고리 코드 입력 */}
              {field.type === "category" && (
                <div className="space-y-1">
                  <Label className="text-xs">카테고리 코드</Label>
                  <Input
                    value={field.categoryCode || field.name || ""}
                    onChange={(e) => updateField(index, { categoryCode: e.target.value })}
                    placeholder="카테고리 코드 (예: INBOUND_TYPE)"
                    className="h-8 w-full text-xs"
                  />
                  <p className="text-muted-foreground text-[10px]">
                    카테고리 관리에서 설정한 색상으로 배지가 표시됩니다
                  </p>
                </div>
              )}

              {/* 카테고리 타입이 아닐 때만 표시 모드 선택 */}
              {field.type !== "category" && (
                <div className="space-y-3">
                  <div className="grid grid-cols-2 gap-3">
                    <div className="space-y-1">
                      <Label className="text-xs">표시 모드</Label>
                      <Select
                        value={field.displayMode || "input"}
                        onValueChange={(value) => updateField(index, { displayMode: value as any })}
                      >
                        <SelectTrigger className="h-8 w-full">
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="input">입력 (편집 가능)</SelectItem>
                          <SelectItem value="readonly">읽기전용 (텍스트)</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>

                    <div className="flex items-center space-x-4 pt-5">
                      <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-xs font-normal">
                          필수
                        </Label>
                      </div>
                    </div>
                  </div>

                  {/* 숨김 체크박스 */}
                  <div className="flex items-center space-x-2">
                    <Checkbox
                      id={`hidden-${index}`}
                      checked={field.isHidden ?? false}
                      onCheckedChange={(checked) => updateField(index, { isHidden: checked as boolean })}
                    />
                    <Label htmlFor={`hidden-${index}`} className="cursor-pointer text-xs font-normal">
                      숨김 (테이블에 표시 안 함)
                    </Label>
                  </div>

                  {/* 하위 데이터 조회에서 값 가져오기 */}
                  {config.subDataLookup?.enabled && (
                    <div className="space-y-2 rounded border border-purple-200 bg-purple-50 p-2">
                      <div className="flex items-center space-x-2">
                        <Checkbox
                          id={`subdata-${index}`}
                          checked={field.subDataSource?.enabled ?? false}
                          onCheckedChange={(checked) => {
                            updateField(index, {
                              subDataSource: {
                                enabled: checked as boolean,
                                sourceColumn: field.subDataSource?.sourceColumn || "",
                              },
                            });
                          }}
                        />
                        <Label htmlFor={`subdata-${index}`} className="cursor-pointer text-xs font-normal text-purple-700">
                          하위 데이터 조회에서 값 가져오기
                        </Label>
                      </div>

                      {field.subDataSource?.enabled && (
                        <div className="ml-5 space-y-1">
                          <Label className="text-[10px] text-purple-600">소스 컬럼</Label>
                          <Select
                            value={field.subDataSource?.sourceColumn || ""}
                            onValueChange={(value) => {
                              updateField(index, {
                                subDataSource: {
                                  enabled: true,
                                  sourceColumn: value,
                                },
                              });
                            }}
                          >
                            <SelectTrigger className="h-7 text-xs">
                              <SelectValue placeholder="컬럼 선택" />
                            </SelectTrigger>
                            <SelectContent>
                              {(config.subDataLookup?.lookup?.displayColumns || []).map((colName) => {
                                const label = config.subDataLookup?.lookup?.columnLabels?.[colName] || colName;
                                return (
                                  <SelectItem key={colName} value={colName} className="text-xs">
                                    {label} ({colName})
                                  </SelectItem>
                                );
                              })}
                            </SelectContent>
                          </Select>
                          <p className="text-[10px] text-purple-500">
                            재고 조회 결과에서 이 컬럼의 값을 가져옵니다
                          </p>
                        </div>
                      )}
                    </div>
                  )}
                </div>
              )}

              {/* 카테고리 타입일 때는 필수만 표시 */}
              {field.type === "category" && (
                <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-xs font-normal">
                    필수 입력
                  </Label>
                </div>
              )}
            </CardContent>
          </Card>
        ))}

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

      {/* 항목 설정 */}
      <div className="space-y-3">
        <Label className="text-sm font-semibold">항목 설정</Label>

        <div className="grid grid-cols-2 gap-3">
          <div className="space-y-2">
            <Label htmlFor="repeater-min-items" className="text-xs">
              최소 항목 수
            </Label>
            <Input
              id="repeater-min-items"
              type="number"
              min={0}
              max={config.maxItems || 100}
              value={config.minItems || 0}
              onChange={(e) => handleChange("minItems", parseInt(e.target.value) || 0)}
              className="h-8"
            />
          </div>

          <div className="space-y-2">
            <Label htmlFor="repeater-max-items" className="text-xs">
              최대 항목 수
            </Label>
            <Input
              id="repeater-max-items"
              type="number"
              min={config.minItems || 0}
              max={100}
              value={config.maxItems || 10}
              onChange={(e) => handleChange("maxItems", parseInt(e.target.value) || 10)}
              className="h-8"
            />
          </div>
        </div>

        <div className="space-y-2">
          <Label htmlFor="repeater-add-button-text" className="text-xs">
            추가 버튼 텍스트
          </Label>
          <Input
            id="repeater-add-button-text"
            type="text"
            value={localConfigInputs.addButtonText}
            onChange={(e) => setLocalConfigInputs({ ...localConfigInputs, addButtonText: e.target.value })}
            onBlur={() => handleChange("addButtonText", localConfigInputs.addButtonText)}
            placeholder="항목 추가"
            className="h-8"
          />
        </div>
      </div>

      {/* 레이아웃 설정 */}
      <div className="space-y-3">
        <Label className="text-sm font-semibold">레이아웃</Label>

        <div className="space-y-2">
          <Label htmlFor="repeater-layout" className="text-xs">
            표시 형식
          </Label>
          <Select
            value={config.layout || "grid"}
            onValueChange={(value) => handleChange("layout", value as "grid" | "card")}
          >
            <SelectTrigger id="repeater-layout" className="h-8">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="grid">테이블 형식 (Grid/Table)</SelectItem>
              <SelectItem value="card">카드 형식 (Card)</SelectItem>
            </SelectContent>
          </Select>
          <p className="text-muted-foreground text-xs">
            {config.layout === "grid"
              ? "행 단위로 데이터를 표시합니다 (테이블 형태)"
              : "각 항목을 카드로 표시합니다 (접기/펼치기 가능)"}
          </p>
        </div>
      </div>

      {/* 옵션 */}
      <div className="space-y-3 rounded-lg border p-4">
        <div className="flex items-center space-x-2">
          <Checkbox
            id="repeater-allow-reorder"
            checked={config.allowReorder ?? true}
            onCheckedChange={(checked) => handleChange("allowReorder", checked as boolean)}
          />
          <Label htmlFor="repeater-allow-reorder" className="cursor-pointer text-xs font-normal">
            순서 변경 허용 (드래그 앤 드롭)
          </Label>
        </div>

        <div className="flex items-center space-x-2">
          <Checkbox
            id="repeater-show-index"
            checked={config.showIndex ?? true}
            onCheckedChange={(checked) => handleChange("showIndex", checked as boolean)}
          />
          <Label htmlFor="repeater-show-index" className="cursor-pointer text-xs font-normal">
            항목 번호 표시
          </Label>
        </div>

        {config.layout === "card" && (
          <>
            <div className="flex items-center space-x-2">
              <Checkbox
                id="repeater-collapsible"
                checked={config.collapsible ?? false}
                onCheckedChange={(checked) => handleChange("collapsible", checked as boolean)}
              />
              <Label htmlFor="repeater-collapsible" className="cursor-pointer text-xs font-normal">
                항목 접기/펼치기 가능 (카드 모드 전용)
              </Label>
            </div>

            <div className="flex items-center space-x-2">
              <Checkbox
                id="repeater-show-divider"
                checked={config.showDivider ?? true}
                onCheckedChange={(checked) => handleChange("showDivider", checked as boolean)}
              />
              <Label htmlFor="repeater-show-divider" className="cursor-pointer text-xs font-normal">
                항목 구분선 표시 (카드 모드 전용)
              </Label>
            </div>
          </>
        )}
      </div>

      {/* 사용 예시 */}
      <div className="rounded-lg bg-primary/10 p-3 text-sm">
        <p className="mb-1 font-medium text-primary">💡 사용 예시</p>
        <ul className="space-y-1 text-xs text-primary">
          <li>• 담당자 정보 (이름, 전화번호, 이메일)</li>
          <li>• 학력 정보 (학교명, 전공, 졸업년도)</li>
          <li>• 경력 사항 (회사명, 직책, 기간)</li>
          <li>• 주소 목록 (주소, 우편번호, 상세주소)</li>
        </ul>
      </div>
    </div>
  );
};

RepeaterConfigPanel.displayName = "RepeaterConfigPanel";
