"use client";

/**
 * UnifiedRepeater 설정 패널
 *
 * 렌더링 모드별 설정:
 * - inline: 현재 화면 테이블 컬럼 직접 입력
 * - modal: 엔티티 선택 + 추가 입력 (FK 저장 + 추가 컬럼 입력)
 */

import React, { useState, useEffect, useMemo, useCallback } from "react";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Separator } from "@/components/ui/separator";
import { Checkbox } from "@/components/ui/checkbox";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import {
  Database,
  Link2,
  Plus,
  Trash2,
  GripVertical,
  ArrowRight,
  Calculator,
} from "lucide-react";
import { tableTypeApi } from "@/lib/api/screen";
import { cn } from "@/lib/utils";
import {
  UnifiedRepeaterConfig,
  RepeaterColumnConfig,
  DEFAULT_REPEATER_CONFIG,
  RENDER_MODE_OPTIONS,
  MODAL_SIZE_OPTIONS,
  COLUMN_WIDTH_OPTIONS,
  ColumnWidthOption,
} from "@/types/unified-repeater";

interface UnifiedRepeaterConfigPanelProps {
  config: UnifiedRepeaterConfig;
  onChange: (config: UnifiedRepeaterConfig) => void;
  currentTableName?: string;
  screenTableName?: string;
  tableColumns?: any[];
}

interface ColumnOption {
  columnName: string;
  displayName: string;
  inputType?: string;
  detailSettings?: {
    codeGroup?: string;
    referenceTable?: string;
    referenceColumn?: string;
    displayColumn?: string;
    format?: string;
  };
}

interface EntityColumnOption {
  columnName: string;
  displayName: string;
  referenceTable?: string;
  referenceColumn?: string;
  displayColumn?: string;
}

interface CalculationRule {
  id: string;
  targetColumn: string;
  formula: string;
  label?: string;
}

export const UnifiedRepeaterConfigPanel: React.FC<UnifiedRepeaterConfigPanelProps> = ({
  config: propConfig,
  onChange,
  currentTableName: propCurrentTableName,
  screenTableName,
}) => {
  const currentTableName = screenTableName || propCurrentTableName;
  
  // config 안전하게 초기화
  const config: UnifiedRepeaterConfig = useMemo(() => ({
    ...DEFAULT_REPEATER_CONFIG,
    ...propConfig,
    renderMode: propConfig?.renderMode || DEFAULT_REPEATER_CONFIG.renderMode,
    dataSource: {
      ...DEFAULT_REPEATER_CONFIG.dataSource,
      ...propConfig?.dataSource,
    },
    columns: propConfig?.columns || [],
    modal: {
      ...DEFAULT_REPEATER_CONFIG.modal,
      ...propConfig?.modal,
    },
    features: {
      ...DEFAULT_REPEATER_CONFIG.features,
      ...propConfig?.features,
    },
  }), [propConfig]);

  // 상태 관리
  const [currentTableColumns, setCurrentTableColumns] = useState<ColumnOption[]>([]); // 현재 테이블 컬럼
  const [entityColumns, setEntityColumns] = useState<EntityColumnOption[]>([]); // 엔티티 타입 컬럼
  const [sourceTableColumns, setSourceTableColumns] = useState<ColumnOption[]>([]); // 소스(엔티티) 테이블 컬럼
  const [calculationRules, setCalculationRules] = useState<CalculationRule[]>([]);

  const [loadingColumns, setLoadingColumns] = useState(false);
  const [loadingSourceColumns, setLoadingSourceColumns] = useState(false);

  // 설정 업데이트 헬퍼
  const updateConfig = useCallback(
    (updates: Partial<UnifiedRepeaterConfig>) => {
      onChange({ ...config, ...updates });
    },
    [config, onChange],
  );

  const updateDataSource = useCallback(
    (field: string, value: any) => {
      updateConfig({
        dataSource: { ...config.dataSource, [field]: value },
      });
    },
    [config.dataSource, updateConfig],
  );

  const updateModal = useCallback(
    (field: string, value: any) => {
      updateConfig({
        modal: { ...config.modal, [field]: value },
      });
    },
    [config.modal, updateConfig],
  );

  const updateFeatures = useCallback(
    (field: string, value: boolean) => {
      updateConfig({
        features: { ...config.features, [field]: value },
      });
    },
    [config.features, updateConfig],
  );

  // 현재 화면 테이블 컬럼 로드 + 엔티티 컬럼 감지
  useEffect(() => {
    const loadCurrentTableColumns = async () => {
      if (!currentTableName) {
        setCurrentTableColumns([]);
        setEntityColumns([]);
        return;
      }

      setLoadingColumns(true);
      try {
        const columnData = await tableTypeApi.getColumns(currentTableName);
        const cols: ColumnOption[] = [];
        const entityCols: EntityColumnOption[] = [];

        for (const c of columnData) {
          // detailSettings 파싱
          let detailSettings: any = null;
          if (c.detailSettings) {
            try {
              detailSettings = typeof c.detailSettings === "string" 
                ? JSON.parse(c.detailSettings) 
                : c.detailSettings;
            } catch (e) {
              console.warn("detailSettings 파싱 실패:", c.detailSettings);
            }
          }

          const col: ColumnOption = {
            columnName: c.columnName || c.column_name,
            displayName: c.displayName || c.columnLabel || c.columnName || c.column_name,
            inputType: c.inputType || c.input_type,
            detailSettings: detailSettings ? {
              codeGroup: detailSettings.codeGroup,
              referenceTable: detailSettings.referenceTable,
              referenceColumn: detailSettings.referenceColumn,
              displayColumn: detailSettings.displayColumn,
              format: detailSettings.format,
            } : undefined,
          };
          cols.push(col);

          // 엔티티 타입 컬럼 감지
          if (col.inputType === "entity") {
            const referenceTable = detailSettings?.referenceTable || c.referenceTable;
            const referenceColumn = detailSettings?.referenceColumn || c.referenceColumn || "id";
            const displayColumn = detailSettings?.displayColumn || c.displayColumn;
            
            if (referenceTable) {
              entityCols.push({
                columnName: col.columnName,
                displayName: col.displayName,
                referenceTable,
                referenceColumn,
                displayColumn,
              });
            }
          }
        }

        setCurrentTableColumns(cols);
        setEntityColumns(entityCols);
      } catch (error) {
        console.error("현재 테이블 컬럼 로드 실패:", error);
        setCurrentTableColumns([]);
        setEntityColumns([]);
      } finally {
        setLoadingColumns(false);
      }
    };
    loadCurrentTableColumns();
  }, [currentTableName]);

  // 소스(엔티티) 테이블 컬럼 로드 (모달 모드일 때)
  useEffect(() => {
    const loadSourceTableColumns = async () => {
      const sourceTable = config.dataSource?.sourceTable;
      if (!sourceTable) {
        setSourceTableColumns([]);
        return;
      }

      setLoadingSourceColumns(true);
      try {
        const columnData = await tableTypeApi.getColumns(sourceTable);
        const cols: ColumnOption[] = columnData.map((c: any) => ({
          columnName: c.columnName || c.column_name,
          displayName: c.displayName || c.columnLabel || c.columnName || c.column_name,
          inputType: c.inputType || c.input_type,
        }));
        setSourceTableColumns(cols);
      } catch (error) {
        console.error("소스 테이블 컬럼 로드 실패:", error);
        setSourceTableColumns([]);
      } finally {
        setLoadingSourceColumns(false);
      }
    };
    
    if (config.renderMode === "modal") {
      loadSourceTableColumns();
    }
  }, [config.dataSource?.sourceTable, config.renderMode]);

  // 컬럼 토글 (현재 테이블 컬럼 - 입력용)
  const toggleInputColumn = (column: ColumnOption) => {
    const existingIndex = config.columns.findIndex((c) => c.key === column.columnName);
    if (existingIndex >= 0) {
      const newColumns = config.columns.filter((c) => c.key !== column.columnName);
      updateConfig({ columns: newColumns });
    } else {
      // 컬럼의 inputType과 detailSettings 정보 포함
      const newColumn: RepeaterColumnConfig = {
        key: column.columnName,
        title: column.displayName,
        width: "auto",
        visible: true,
        editable: true,
        inputType: column.inputType || "text",
        detailSettings: column.detailSettings ? {
          codeGroup: column.detailSettings.codeGroup,
          referenceTable: column.detailSettings.referenceTable,
          referenceColumn: column.detailSettings.referenceColumn,
          displayColumn: column.detailSettings.displayColumn,
          format: column.detailSettings.format,
        } : undefined,
      };
      updateConfig({ columns: [...config.columns, newColumn] });
    }
  };

  // 소스 컬럼 토글 (모달에 표시용 - 라벨 포함)
  const toggleSourceDisplayColumn = (column: ColumnOption) => {
    const sourceDisplayColumns = config.modal?.sourceDisplayColumns || [];
    const exists = sourceDisplayColumns.some(c => c.key === column.columnName);
    
    if (exists) {
      updateModal("sourceDisplayColumns", sourceDisplayColumns.filter(c => c.key !== column.columnName));
    } else {
      updateModal("sourceDisplayColumns", [
        ...sourceDisplayColumns, 
        { key: column.columnName, label: column.displayName }
      ]);
    }
  };

  const isColumnAdded = (columnName: string) => {
    return config.columns.some((c) => c.key === columnName);
  };

  const isSourceColumnSelected = (columnName: string) => {
    return (config.modal?.sourceDisplayColumns || []).some(c => c.key === columnName);
  };

  // 컬럼 속성 업데이트
  const updateColumnProp = (key: string, field: keyof RepeaterColumnConfig, value: any) => {
    const newColumns = config.columns.map((col) => (col.key === key ? { ...col, [field]: value } : col));
    updateConfig({ columns: newColumns });
  };

  // 계산 규칙 추가
  const addCalculationRule = () => {
    setCalculationRules(prev => [
      ...prev,
      { id: `calc_${Date.now()}`, targetColumn: "", formula: "" }
    ]);
  };

  // 계산 규칙 삭제
  const removeCalculationRule = (id: string) => {
    setCalculationRules(prev => prev.filter(r => r.id !== id));
  };

  // 계산 규칙 업데이트
  const updateCalculationRule = (id: string, field: keyof CalculationRule, value: string) => {
    setCalculationRules(prev => 
      prev.map(r => r.id === id ? { ...r, [field]: value } : r)
    );
  };

  // 엔티티 컬럼 선택 시 소스 테이블 자동 설정
  const handleEntityColumnSelect = (columnName: string) => {
    const selectedEntity = entityColumns.find(c => c.columnName === columnName);
    
    if (selectedEntity) {
      console.log("엔티티 컬럼 선택:", selectedEntity);
      
      // 소스 테이블 컬럼에서 라벨 정보 찾기
      const displayColInfo = sourceTableColumns.find(c => c.columnName === selectedEntity.displayColumn);
      const displayLabel = displayColInfo?.displayName || selectedEntity.displayColumn || "";
      
      updateConfig({
        dataSource: {
          ...config.dataSource,
          sourceTable: selectedEntity.referenceTable || "",
          foreignKey: selectedEntity.columnName,
          referenceKey: selectedEntity.referenceColumn || "id",
          displayColumn: selectedEntity.displayColumn,
        },
        modal: {
          ...config.modal,
          searchFields: selectedEntity.displayColumn ? [selectedEntity.displayColumn] : [],
          // 라벨 포함 형식으로 저장
          sourceDisplayColumns: selectedEntity.displayColumn 
            ? [{ key: selectedEntity.displayColumn, label: displayLabel }] 
            : [],
        },
      });
    }
  };

  // 모드 여부
  const isInlineMode = config.renderMode === "inline";
  const isModalMode = config.renderMode === "modal";

  // 엔티티 컬럼 제외한 입력 가능 컬럼 (FK 컬럼 제외)
  const inputableColumns = useMemo(() => {
    const fkColumn = config.dataSource?.foreignKey;
    return currentTableColumns.filter(col => 
      col.columnName !== fkColumn && // FK 컬럼 제외
      col.inputType !== "entity" // 다른 엔티티 컬럼도 제외 (필요시)
    );
  }, [currentTableColumns, config.dataSource?.foreignKey]);

  return (
    <div className="space-y-4">
      <Tabs defaultValue="basic" className="w-full">
        <TabsList className="grid w-full grid-cols-3">
          <TabsTrigger value="basic" className="text-xs">기본</TabsTrigger>
          <TabsTrigger value="columns" className="text-xs">컬럼</TabsTrigger>
          <TabsTrigger value="modal" className="text-xs" disabled={!isModalMode}>모달</TabsTrigger>
        </TabsList>

        {/* 기본 설정 탭 */}
        <TabsContent value="basic" className="mt-4 space-y-4">
          {/* 렌더링 모드 */}
          <div className="space-y-2">
            <Label className="text-xs font-medium">렌더링 모드</Label>
            <Select value={config.renderMode} onValueChange={(value) => updateConfig({ renderMode: value as any })}>
              <SelectTrigger className="h-8 text-xs">
                <SelectValue placeholder="모드 선택" />
              </SelectTrigger>
              <SelectContent>
                {RENDER_MODE_OPTIONS.map((opt) => (
                  <SelectItem key={opt.value} value={opt.value}>
                    <div className="flex flex-col">
                      <span>{opt.label}</span>
                      <span className="text-[10px] text-gray-400">
                        {opt.value === "inline" && "현재 테이블 컬럼 직접 입력"}
                        {opt.value === "modal" && "엔티티 선택 후 추가 정보 입력"}
                        {opt.value === "button" && "버튼으로 관련 화면 열기"}
                      </span>
                    </div>
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          <Separator />

          {/* 현재 화면 정보 */}
          <div className="space-y-2">
            <Label className="text-xs font-medium">현재 화면</Label>
            {currentTableName ? (
              <div className="rounded border border-blue-200 bg-blue-50 p-2">
                <p className="text-xs text-blue-700 font-medium">{currentTableName}</p>
                <p className="text-[10px] text-blue-500">
                  컬럼 {currentTableColumns.length}개 / 엔티티 {entityColumns.length}개
                </p>
              </div>
            ) : (
              <div className="rounded border border-amber-200 bg-amber-50 p-2">
                <p className="text-[10px] text-amber-600">화면에 테이블을 먼저 설정해주세요</p>
              </div>
            )}
          </div>

          {/* 모달 모드: 엔티티 컬럼 선택 */}
          {isModalMode && (
            <>
              <Separator />
              <div className="space-y-2">
                <Label className="text-xs font-medium">엔티티 선택</Label>
                <p className="text-[10px] text-muted-foreground">
                  모달에서 검색할 엔티티를 선택하세요 (FK만 저장됨)
                </p>
                
                {entityColumns.length > 0 ? (
                  <Select
                    value={config.dataSource?.foreignKey || ""}
                    onValueChange={handleEntityColumnSelect}
                    disabled={!currentTableName}
                  >
                    <SelectTrigger className="h-8 text-xs">
                      <SelectValue placeholder="엔티티 컬럼 선택" />
                    </SelectTrigger>
                    <SelectContent>
                      {entityColumns.map((col) => (
                        <SelectItem key={col.columnName} value={col.columnName}>
                          <div className="flex items-center gap-2">
                            <Link2 className="h-3 w-3 text-blue-500" />
                            <span>{col.displayName}</span>
                            <ArrowRight className="h-3 w-3 text-gray-400" />
                            <span className="text-gray-500">{col.referenceTable}</span>
                          </div>
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                ) : (
                  <div className="rounded border border-gray-200 bg-gray-50 p-2">
                    <p className="text-[10px] text-gray-500">
                      {loadingColumns ? "로딩 중..." : "엔티티 타입 컬럼이 없습니다"}
                    </p>
                  </div>
                )}
                
                {/* 선택된 엔티티 정보 */}
                {config.dataSource?.sourceTable && (
                  <div className="rounded border border-green-200 bg-green-50 p-2 space-y-1">
                    <p className="text-xs text-green-700 font-medium">선택된 엔티티</p>
                    <div className="text-[10px] text-green-600">
                      <p>검색 테이블: {config.dataSource.sourceTable}</p>
                      <p>저장 컬럼: {config.dataSource.foreignKey} (FK)</p>
                    </div>
                  </div>
                )}
              </div>
            </>
          )}

          <Separator />

          {/* 기능 옵션 */}
          <div className="space-y-3">
            <Label className="text-xs font-medium">기능 옵션</Label>
            <div className="grid grid-cols-2 gap-2">
              <div className="flex items-center space-x-2">
                <Checkbox
                  id="showAddButton"
                  checked={config.features?.showAddButton ?? true}
                  onCheckedChange={(checked) => updateFeatures("showAddButton", !!checked)}
                />
                <label htmlFor="showAddButton" className="text-xs">추가 버튼</label>
              </div>

              <div className="flex items-center space-x-2">
                <Checkbox
                  id="showDeleteButton"
                  checked={config.features?.showDeleteButton ?? true}
                  onCheckedChange={(checked) => updateFeatures("showDeleteButton", !!checked)}
                />
                <label htmlFor="showDeleteButton" className="text-xs">삭제 버튼</label>
              </div>

              <div className="flex items-center space-x-2">
                <Checkbox
                  id="inlineEdit"
                  checked={config.features?.inlineEdit ?? false}
                  onCheckedChange={(checked) => updateFeatures("inlineEdit", !!checked)}
                />
                <label htmlFor="inlineEdit" className="text-xs">인라인 편집</label>
              </div>

              <div className="flex items-center space-x-2">
                <Checkbox
                  id="multiSelect"
                  checked={config.features?.multiSelect ?? true}
                  onCheckedChange={(checked) => updateFeatures("multiSelect", !!checked)}
                />
                <label htmlFor="multiSelect" className="text-xs">다중 선택</label>
              </div>

              <div className="flex items-center space-x-2">
                <Checkbox
                  id="showRowNumber"
                  checked={config.features?.showRowNumber ?? false}
                  onCheckedChange={(checked) => updateFeatures("showRowNumber", !!checked)}
                />
                <label htmlFor="showRowNumber" className="text-xs">행 번호</label>
              </div>

              <div className="flex items-center space-x-2">
                <Checkbox
                  id="selectable"
                  checked={config.features?.selectable ?? false}
                  onCheckedChange={(checked) => updateFeatures("selectable", !!checked)}
                />
                <label htmlFor="selectable" className="text-xs">행 선택</label>
              </div>
            </div>
          </div>
        </TabsContent>

        {/* 컬럼 설정 탭 */}
        <TabsContent value="columns" className="mt-4 space-y-4">
          {/* 모달 모드: 모달에 표시할 컬럼 */}
          {isModalMode && config.dataSource?.sourceTable && (
            <>
              <div className="space-y-2">
                <Label className="text-xs font-medium">모달 표시 컬럼</Label>
                <p className="text-[10px] text-muted-foreground">
                  검색 모달에서 보여줄 컬럼 (보기용)
                </p>
                
                {loadingSourceColumns ? (
                  <p className="text-muted-foreground py-2 text-xs">로딩 중...</p>
                ) : sourceTableColumns.length === 0 ? (
                  <p className="text-muted-foreground py-2 text-xs">컬럼 정보가 없습니다</p>
                ) : (
                  <div className="max-h-32 space-y-1 overflow-y-auto rounded-md border p-2">
                    {sourceTableColumns.map((column) => (
                      <div
                        key={column.columnName}
                        className={cn(
                          "hover:bg-muted/50 flex cursor-pointer items-center gap-2 rounded px-2 py-1",
                          isSourceColumnSelected(column.columnName) && "bg-blue-50",
                        )}
                        onClick={() => toggleSourceDisplayColumn(column)}
                      >
                        <Checkbox
                          checked={isSourceColumnSelected(column.columnName)}
                          onCheckedChange={() => toggleSourceDisplayColumn(column)}
                          className="pointer-events-none h-3.5 w-3.5"
                        />
                        <span className="truncate text-xs">{column.displayName}</span>
                      </div>
                    ))}
                  </div>
                )}
              </div>
              <Separator />
            </>
          )}

          {/* 추가 입력 컬럼 (현재 테이블에서 FK 제외) */}
          <div className="space-y-2">
            <Label className="text-xs font-medium">
              {isModalMode ? "추가 입력 컬럼" : "입력 컬럼"}
            </Label>
            <p className="text-[10px] text-muted-foreground">
              {isModalMode 
                ? "엔티티 선택 후 추가로 입력받을 컬럼 (수량, 단가 등)"
                : "직접 입력받을 컬럼을 선택하세요"
              }
            </p>
            
            {loadingColumns ? (
              <p className="text-muted-foreground py-2 text-xs">로딩 중...</p>
            ) : inputableColumns.length === 0 ? (
              <p className="text-muted-foreground py-2 text-xs">
                {isModalMode ? "추가 입력 가능한 컬럼이 없습니다" : "컬럼 정보가 없습니다"}
              </p>
            ) : (
              <div className="max-h-48 space-y-1 overflow-y-auto rounded-md border p-2">
                {inputableColumns.map((column) => (
                  <div
                    key={column.columnName}
                    className={cn(
                      "hover:bg-muted/50 flex cursor-pointer items-center gap-2 rounded px-2 py-1",
                      isColumnAdded(column.columnName) && "bg-primary/10",
                    )}
                    onClick={() => toggleInputColumn(column)}
                  >
                    <Checkbox
                      checked={isColumnAdded(column.columnName)}
                      onCheckedChange={() => toggleInputColumn(column)}
                      className="pointer-events-none h-3.5 w-3.5"
                    />
                    <Database className="text-muted-foreground h-3 w-3" />
                    <span className="truncate text-xs">{column.displayName}</span>
                    <span className="text-[10px] text-gray-400 ml-auto">{column.inputType}</span>
                  </div>
                ))}
              </div>
            )}
          </div>

          {/* 선택된 컬럼 상세 설정 */}
          {config.columns.length > 0 && (
            <>
              <Separator />
              <div className="space-y-2">
                <Label className="text-xs font-medium">선택된 컬럼 ({config.columns.length}개)</Label>
                <div className="max-h-40 space-y-1 overflow-y-auto">
                  {config.columns.map((col) => (
                    <div key={col.key} className="bg-muted/30 flex items-center gap-2 rounded-md border p-2">
                      <GripVertical className="text-muted-foreground h-3 w-3 cursor-grab" />
                      <Database className="text-muted-foreground h-3 w-3 flex-shrink-0" />
                      <Input
                        value={col.title}
                        onChange={(e) => updateColumnProp(col.key, "title", e.target.value)}
                        placeholder="제목"
                        className="h-6 flex-1 text-xs"
                      />
                      <Select
                        value={col.width || "auto"}
                        onValueChange={(value) => updateColumnProp(col.key, "width", value as ColumnWidthOption)}
                      >
                        <SelectTrigger className="h-6 w-20 text-xs">
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          {COLUMN_WIDTH_OPTIONS.map((opt) => (
                            <SelectItem key={opt.value} value={opt.value}>
                              {opt.label}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                      <Checkbox
                        checked={col.editable ?? true}
                        onCheckedChange={(checked) => updateColumnProp(col.key, "editable", !!checked)}
                        title="편집 가능"
                      />
                      <Button
                        type="button"
                        variant="ghost"
                        size="sm"
                        onClick={() => toggleInputColumn({ columnName: col.key, displayName: col.title })}
                        className="text-destructive h-6 w-6 p-0"
                      >
                        <Trash2 className="h-3 w-3" />
                      </Button>
                    </div>
                  ))}
                </div>
              </div>
            </>
          )}

          {/* 계산 규칙 */}
          {(isModalMode || isInlineMode) && config.columns.length > 0 && (
            <>
              <Separator />
              <div className="space-y-2">
                <div className="flex items-center justify-between">
                  <Label className="text-xs font-medium">계산 규칙</Label>
                  <Button type="button" variant="outline" size="sm" onClick={addCalculationRule} className="h-6 text-xs">
                    <Calculator className="mr-1 h-3 w-3" />
                    추가
                  </Button>
                </div>
                <p className="text-[10px] text-muted-foreground">
                  예: 금액 = 수량 * 단가
                </p>
                
                <div className="max-h-32 space-y-2 overflow-y-auto">
                  {calculationRules.map((rule) => (
                    <div key={rule.id} className="flex items-center gap-2 rounded border p-2">
                      <Select
                        value={rule.targetColumn}
                        onValueChange={(value) => updateCalculationRule(rule.id, "targetColumn", value)}
                      >
                        <SelectTrigger className="h-7 w-24 text-xs">
                          <SelectValue placeholder="결과" />
                        </SelectTrigger>
                        <SelectContent>
                          {config.columns.map((col) => (
                            <SelectItem key={col.key} value={col.key}>
                              {col.title}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                      
                      <span className="text-xs">=</span>
                      
                      <Input
                        value={rule.formula}
                        onChange={(e) => updateCalculationRule(rule.id, "formula", e.target.value)}
                        placeholder="quantity * unit_price"
                        className="h-7 flex-1 text-xs"
                      />
                      
                      <Button
                        type="button"
                        variant="ghost"
                        size="sm"
                        onClick={() => removeCalculationRule(rule.id)}
                        className="h-7 w-7 p-0 text-destructive"
                      >
                        <Trash2 className="h-3 w-3" />
                      </Button>
                    </div>
                  ))}
                  
                  {calculationRules.length === 0 && (
                    <p className="text-muted-foreground py-2 text-center text-xs">
                      계산 규칙이 없습니다
                    </p>
                  )}
                </div>
              </div>
            </>
          )}
        </TabsContent>

        {/* 모달 설정 탭 */}
        <TabsContent value="modal" className="mt-4 space-y-4">
          {isModalMode ? (
            <>
              {/* 모달 크기 */}
              <div className="space-y-2">
                <Label className="text-xs font-medium">모달 크기</Label>
                <Select
                  value={config.modal?.size || "lg"}
                  onValueChange={(value) => updateModal("size", value)}
                >
                  <SelectTrigger className="h-8 text-xs">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {MODAL_SIZE_OPTIONS.map((opt) => (
                      <SelectItem key={opt.value} value={opt.value}>
                        {opt.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              {/* 모달 제목 */}
              <div className="space-y-2">
                <Label className="text-xs font-medium">모달 제목</Label>
                <Input
                  value={config.modal?.title || ""}
                  onChange={(e) => updateModal("title", e.target.value)}
                  placeholder="예: 품목 검색"
                  className="h-8 text-xs"
                />
              </div>

              {/* 버튼 텍스트 */}
              <div className="space-y-2">
                <Label className="text-xs font-medium">추가 버튼 텍스트</Label>
                <Input
                  value={config.modal?.buttonText || ""}
                  onChange={(e) => updateModal("buttonText", e.target.value)}
                  placeholder="예: 품목 검색"
                  className="h-8 text-xs"
                />
              </div>

              <Separator />

              {/* 검색 필드 */}
              <div className="space-y-2">
                <Label className="text-xs font-medium">검색 필드</Label>
                <p className="text-[10px] text-muted-foreground">
                  검색어 입력 시 검색할 필드
                </p>
                
                <div className="max-h-24 space-y-1 overflow-y-auto rounded-md border p-2">
                  {sourceTableColumns.map((column) => {
                    const searchFields = config.modal?.searchFields || [];
                    const isChecked = searchFields.includes(column.columnName);
                    
                    return (
                      <div
                        key={column.columnName}
                        className={cn(
                          "hover:bg-muted/50 flex cursor-pointer items-center gap-2 rounded px-2 py-1",
                          isChecked && "bg-blue-50",
                        )}
                        onClick={() => {
                          if (isChecked) {
                            updateModal("searchFields", searchFields.filter(f => f !== column.columnName));
                          } else {
                            updateModal("searchFields", [...searchFields, column.columnName]);
                          }
                        }}
                      >
                        <Checkbox checked={isChecked} className="pointer-events-none h-3.5 w-3.5" />
                        <span className="truncate text-xs">{column.displayName}</span>
                      </div>
                    );
                  })}
                </div>
              </div>
            </>
          ) : (
            <p className="text-muted-foreground py-4 text-center text-xs">
              모달 또는 혼합 모드에서만 설정할 수 있습니다
            </p>
          )}
        </TabsContent>
      </Tabs>
    </div>
  );
};

UnifiedRepeaterConfigPanel.displayName = "UnifiedRepeaterConfigPanel";

export default UnifiedRepeaterConfigPanel;
