"use client";

/**
 * V2Select 설정 패널
 * 토스식 단계별 UX: 소스 카드 선택 -> 소스별 설정 -> 고급 설정(접힘)
 */

import React, { useState, useEffect, useCallback, useMemo } from "react";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Switch } from "@/components/ui/switch";
import { Button } from "@/components/ui/button";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
import { Separator } from "@/components/ui/separator";
import { List, Database, FolderTree, Settings, ChevronDown, Plus, Trash2, Loader2, Filter } from "lucide-react";
import { cn } from "@/lib/utils";
import { apiClient } from "@/lib/api/client";
import type { V2SelectFilter } from "@/types/v2-components";

interface ColumnOption {
  columnName: string;
  columnLabel: string;
}

interface CategoryValueOption {
  valueCode: string;
  valueLabel: string;
}

const OPERATOR_OPTIONS = [
  { value: "=", label: "같음 (=)" },
  { value: "!=", label: "다름 (!=)" },
  { value: ">", label: "초과 (>)" },
  { value: "<", label: "미만 (<)" },
  { value: ">=", label: "이상 (>=)" },
  { value: "<=", label: "이하 (<=)" },
  { value: "in", label: "포함 (IN)" },
  { value: "notIn", label: "미포함 (NOT IN)" },
  { value: "like", label: "유사 (LIKE)" },
  { value: "isNull", label: "NULL" },
  { value: "isNotNull", label: "NOT NULL" },
] as const;

const VALUE_TYPE_OPTIONS = [
  { value: "static", label: "고정값" },
  { value: "field", label: "폼 필드 참조" },
  { value: "user", label: "로그인 사용자" },
] as const;

const USER_FIELD_OPTIONS = [
  { value: "companyCode", label: "회사코드" },
  { value: "userId", label: "사용자ID" },
  { value: "deptCode", label: "부서코드" },
  { value: "userName", label: "사용자명" },
] as const;

// ─── 데이터 소스 카드 정의 ───
const SOURCE_CARDS = [
  {
    value: "static",
    icon: List,
    title: "직접 입력",
    description: "옵션을 직접 추가해요",
  },
  {
    value: "category",
    icon: FolderTree,
    title: "카테고리",
    description: "등록된 선택지를 사용해요",
  },
  {
    value: "entity",
    icon: Database,
    title: "테이블 참조",
    description: "다른 테이블에서 가져와요",
    entityOnly: true,
  },
] as const;

/**
 * 필터 조건 설정 서브 컴포넌트
 */
const FilterConditionsSection: React.FC<{
  filters: V2SelectFilter[];
  columns: ColumnOption[];
  loadingColumns: boolean;
  targetTable: string;
  onFiltersChange: (filters: V2SelectFilter[]) => void;
}> = ({ filters, columns, loadingColumns, targetTable, onFiltersChange }) => {

  const addFilter = () => {
    onFiltersChange([
      ...filters,
      { column: "", operator: "=", valueType: "static", value: "" },
    ]);
  };

  const updateFilter = (index: number, patch: Partial<V2SelectFilter>) => {
    const updated = [...filters];
    updated[index] = { ...updated[index], ...patch };

    if (patch.valueType) {
      if (patch.valueType === "static") {
        updated[index].fieldRef = undefined;
        updated[index].userField = undefined;
      } else if (patch.valueType === "field") {
        updated[index].value = undefined;
        updated[index].userField = undefined;
      } else if (patch.valueType === "user") {
        updated[index].value = undefined;
        updated[index].fieldRef = undefined;
      }
    }

    if (patch.operator === "isNull" || patch.operator === "isNotNull") {
      updated[index].value = undefined;
      updated[index].fieldRef = undefined;
      updated[index].userField = undefined;
      updated[index].valueType = "static";
    }

    onFiltersChange(updated);
  };

  const removeFilter = (index: number) => {
    onFiltersChange(filters.filter((_, i) => i !== index));
  };

  const needsValue = (op: string) => op !== "isNull" && op !== "isNotNull";

  return (
    <div className="space-y-2">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-1.5">
          <Filter className="h-3.5 w-3.5 text-muted-foreground" />
          <span className="text-xs font-medium">데이터 필터</span>
        </div>
        <Button
          type="button"
          variant="ghost"
          size="sm"
          onClick={addFilter}
          className="h-6 px-2 text-xs"
        >
          <Plus className="mr-1 h-3 w-3" />
          추가
        </Button>
      </div>

      <p className="text-muted-foreground text-[10px]">
        {targetTable} 테이블에서 옵션을 불러올 때 적용할 조건
      </p>

      {loadingColumns && (
        <div className="text-muted-foreground flex items-center gap-2 text-xs">
          <Loader2 className="h-3 w-3 animate-spin" />
          컬럼 목록 로딩 중...
        </div>
      )}

      {filters.length === 0 && (
        <p className="text-muted-foreground py-2 text-center text-xs">
          필터 조건이 없습니다
        </p>
      )}

      <div className="space-y-2">
        {filters.map((filter, index) => (
          <div key={index} className="space-y-1.5 rounded-md border p-2">
            <div className="flex items-center gap-1.5">
              <Select
                value={filter.column || ""}
                onValueChange={(v) => updateFilter(index, { column: v })}
              >
                <SelectTrigger className="h-7 flex-1 text-[11px]">
                  <SelectValue placeholder="컬럼" />
                </SelectTrigger>
                <SelectContent>
                  {columns.map((col) => (
                    <SelectItem key={col.columnName} value={col.columnName}>
                      {col.columnLabel}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>

              <Select
                value={filter.operator || "="}
                onValueChange={(v) => updateFilter(index, { operator: v as V2SelectFilter["operator"] })}
              >
                <SelectTrigger className="h-7 w-[90px] shrink-0 text-[11px]">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {OPERATOR_OPTIONS.map((op) => (
                    <SelectItem key={op.value} value={op.value}>
                      {op.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>

              <Button
                type="button"
                variant="ghost"
                size="sm"
                onClick={() => removeFilter(index)}
                className="text-destructive h-7 w-7 shrink-0 p-0"
              >
                <Trash2 className="h-3 w-3" />
              </Button>
            </div>

            {needsValue(filter.operator) && (
              <div className="flex items-center gap-1.5">
                <Select
                  value={filter.valueType || "static"}
                  onValueChange={(v) => updateFilter(index, { valueType: v as V2SelectFilter["valueType"] })}
                >
                  <SelectTrigger className="h-7 w-[100px] shrink-0 text-[11px]">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {VALUE_TYPE_OPTIONS.map((vt) => (
                      <SelectItem key={vt.value} value={vt.value}>
                        {vt.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>

                {(filter.valueType || "static") === "static" && (
                  <Input
                    value={String(filter.value ?? "")}
                    onChange={(e) => updateFilter(index, { value: e.target.value })}
                    placeholder={filter.operator === "in" || filter.operator === "notIn" ? "값1, 값2, ..." : "값 입력"}
                    className="h-7 flex-1 text-[11px]"
                  />
                )}

                {filter.valueType === "field" && (
                  <Input
                    value={filter.fieldRef || ""}
                    onChange={(e) => updateFilter(index, { fieldRef: e.target.value })}
                    placeholder="참조할 필드명 (columnName)"
                    className="h-7 flex-1 text-[11px]"
                  />
                )}

                {filter.valueType === "user" && (
                  <Select
                    value={filter.userField || ""}
                    onValueChange={(v) => updateFilter(index, { userField: v as V2SelectFilter["userField"] })}
                  >
                    <SelectTrigger className="h-7 flex-1 text-[11px]">
                      <SelectValue placeholder="사용자 필드" />
                    </SelectTrigger>
                    <SelectContent>
                      {USER_FIELD_OPTIONS.map((uf) => (
                        <SelectItem key={uf.value} value={uf.value}>
                          {uf.label}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                )}
              </div>
            )}
          </div>
        ))}
      </div>
    </div>
  );
};

interface V2SelectConfigPanelProps {
  config: Record<string, any>;
  onChange: (config: Record<string, any>) => void;
  inputType?: string;
  tableName?: string;
  columnName?: string;
}

export const V2SelectConfigPanel: React.FC<V2SelectConfigPanelProps> = ({
  config,
  onChange,
  inputType,
  tableName,
  columnName,
}) => {
  const isEntityType = inputType === "entity";
  const isCategoryType = inputType === "category";

  const [entityColumns, setEntityColumns] = useState<ColumnOption[]>([]);
  const [loadingColumns, setLoadingColumns] = useState(false);

  const [categoryValues, setCategoryValues] = useState<CategoryValueOption[]>([]);
  const [loadingCategoryValues, setLoadingCategoryValues] = useState(false);

  const [filterColumns, setFilterColumns] = useState<ColumnOption[]>([]);
  const [loadingFilterColumns, setLoadingFilterColumns] = useState(false);

  const [advancedOpen, setAdvancedOpen] = useState(false);

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

  const filterTargetTable = useMemo(() => {
    const src = config.source || "static";
    if (src === "entity") return config.entityTable;
    if (src === "db") return config.table;
    if (src === "distinct" || src === "select") return tableName;
    return null;
  }, [config.source, config.entityTable, config.table, tableName]);

  useEffect(() => {
    if (!filterTargetTable) {
      setFilterColumns([]);
      return;
    }

    const loadFilterColumns = async () => {
      setLoadingFilterColumns(true);
      try {
        const response = await apiClient.get(`/table-management/tables/${filterTargetTable}/columns?size=500`);
        const data = response.data.data || response.data;
        const columns = data.columns || data || [];
        setFilterColumns(
          columns.map((col: any) => ({
            columnName: col.columnName || col.column_name || col.name,
            columnLabel: col.displayName || col.display_name || col.columnLabel || col.column_label || col.columnName || col.column_name || col.name,
          }))
        );
      } catch {
        setFilterColumns([]);
      } finally {
        setLoadingFilterColumns(false);
      }
    };

    loadFilterColumns();
  }, [filterTargetTable]);

  useEffect(() => {
    if (isCategoryType && config.source !== "category") {
      onChange({ ...config, source: "category" });
    }
  }, [isCategoryType]);

  const loadCategoryValues = useCallback(async (catTable: string, catColumn: string) => {
    if (!catTable || !catColumn) {
      setCategoryValues([]);
      return;
    }

    setLoadingCategoryValues(true);
    try {
      const response = await apiClient.get(`/table-categories/${catTable}/${catColumn}/values`);
      const data = response.data;
      if (data.success && data.data) {
        const flattenTree = (items: any[], depth: number = 0): CategoryValueOption[] => {
          const result: CategoryValueOption[] = [];
          for (const item of items) {
            result.push({
              valueCode: item.valueCode,
              valueLabel: depth > 0 ? `${"  ".repeat(depth)}${item.valueLabel}` : item.valueLabel,
            });
            if (item.children && item.children.length > 0) {
              result.push(...flattenTree(item.children, depth + 1));
            }
          }
          return result;
        };
        setCategoryValues(flattenTree(data.data));
      }
    } catch (error) {
      console.error("카테고리 값 조회 실패:", error);
      setCategoryValues([]);
    } finally {
      setLoadingCategoryValues(false);
    }
  }, []);

  useEffect(() => {
    if (config.source === "category" || config.source === "code") {
      const catTable = config.categoryTable || tableName;
      const catColumn = config.categoryColumn || columnName;
      if (catTable && catColumn) {
        loadCategoryValues(catTable, catColumn);
      }
    }
  }, [config.source, config.categoryTable, config.categoryColumn, tableName, columnName, loadCategoryValues]);

  const loadEntityColumns = useCallback(async (tblName: string) => {
    if (!tblName) {
      setEntityColumns([]);
      return;
    }

    setLoadingColumns(true);
    try {
      const response = await apiClient.get(`/table-management/tables/${tblName}/columns?size=500`);
      const data = response.data.data || response.data;
      const columns = data.columns || data || [];

      const columnOptions: ColumnOption[] = columns.map((col: any) => {
        const name = col.columnName || col.column_name || col.name;
        const label = col.displayName || col.display_name || col.columnLabel || col.column_label || name;

        return {
          columnName: name,
          columnLabel: label,
        };
      });

      setEntityColumns(columnOptions);
    } catch (error) {
      console.error("컬럼 목록 조회 실패:", error);
      setEntityColumns([]);
    } finally {
      setLoadingColumns(false);
    }
  }, []);

  useEffect(() => {
    if (config.source === "entity" && config.entityTable) {
      loadEntityColumns(config.entityTable);
    }
  }, [config.source, config.entityTable, loadEntityColumns]);

  const options = config.options || [];

  const addOption = () => {
    const newOptions = [...options, { value: "", label: "" }];
    updateConfig("options", newOptions);
  };

  const updateOptionValue = (index: number, value: string) => {
    const newOptions = [...options];
    newOptions[index] = { ...newOptions[index], value, label: value };
    updateConfig("options", newOptions);
  };

  const removeOption = (index: number) => {
    const newOptions = options.filter((_: any, i: number) => i !== index);
    updateConfig("options", newOptions);
  };

  const effectiveSource = isCategoryType
    ? "category"
    : config.source === "code"
      ? "category"
      : config.source || "static";

  const visibleCards = useMemo(() => {
    if (isCategoryType) {
      return SOURCE_CARDS.filter((c) => c.value === "category");
    }
    return SOURCE_CARDS.filter((c) => {
      if (c.entityOnly && !isEntityType) return false;
      return true;
    });
  }, [isCategoryType, isEntityType]);

  const gridCols = isEntityType ? "grid-cols-3" : "grid-cols-2";

  return (
    <div className="space-y-4">
      {/* ─── 1단계: 데이터 소스 선택 ─── */}
      <div className="space-y-2">
        <p className="text-sm font-medium">이 필드는 어떤 데이터를 선택하나요?</p>
        <div className={cn("grid gap-2", gridCols)}>
          {visibleCards.map((card) => {
            const Icon = card.icon;
            const isSelected = effectiveSource === card.value;
            return (
              <button
                key={card.value}
                type="button"
                onClick={() => updateConfig("source", card.value)}
                className={cn(
                  "flex flex-col items-center justify-center rounded-lg border p-3 text-center transition-all min-h-[80px]",
                  isSelected
                    ? "border-primary bg-primary/5 ring-1 ring-primary/20"
                    : "border-border hover:border-primary/50 hover:bg-muted/50"
                )}
              >
                <Icon className="h-5 w-5 mb-1.5 text-primary" />
                <span className="text-xs font-medium leading-tight">{card.title}</span>
                <span className="text-[10px] text-muted-foreground leading-tight mt-0.5">{card.description}</span>
              </button>
            );
          })}
        </div>
      </div>

      {/* ─── 2단계: 소스별 설정 ─── */}

      {/* 직접 입력 (static) */}
      {effectiveSource === "static" && (
        <div className="rounded-lg border bg-muted/30 p-4 space-y-3">
          <div className="flex items-center justify-between">
            <span className="text-sm font-medium">옵션 목록</span>
            <Button type="button" variant="outline" size="sm" onClick={addOption} className="h-7 px-2 text-xs">
              <Plus className="mr-1 h-3 w-3" />
              추가
            </Button>
          </div>

          {options.length > 0 ? (
            <div className="max-h-40 space-y-1.5 overflow-y-auto">
              {options.map((option: any, index: number) => (
                <div key={index} className="flex items-center gap-2">
                  <Input
                    value={option.value || ""}
                    onChange={(e) => updateOptionValue(index, e.target.value)}
                    placeholder={`옵션 ${index + 1}`}
                    className="h-8 flex-1 text-sm"
                  />
                  <Button
                    type="button"
                    variant="ghost"
                    size="icon"
                    onClick={() => removeOption(index)}
                    className="text-destructive h-8 w-8 shrink-0"
                  >
                    <Trash2 className="h-4 w-4" />
                  </Button>
                </div>
              ))}
            </div>
          ) : (
            <div className="text-center py-6 text-muted-foreground">
              <List className="mx-auto mb-2 h-8 w-8 opacity-30" />
              <p className="text-sm">아직 옵션이 없어요</p>
              <p className="text-xs">위의 추가 버튼으로 옵션을 만들어보세요</p>
            </div>
          )}

          {options.length > 0 && (
            <div className="border-t pt-3 mt-3">
              <div className="flex items-center justify-between">
                <span className="text-xs text-muted-foreground">기본 선택값</span>
                <Select
                  value={config.defaultValue || "_none_"}
                  onValueChange={(value) => updateConfig("defaultValue", value === "_none_" ? "" : value)}
                >
                  <SelectTrigger className="h-8 w-[160px] text-sm">
                    <SelectValue placeholder="선택 안함" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="_none_">선택 안함</SelectItem>
                    {options.map((option: any, index: number) => (
                      <SelectItem key={`default-${index}`} value={option.value || `_idx_${index}`}>
                        {option.label || option.value || `옵션 ${index + 1}`}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </div>
          )}
        </div>
      )}

      {/* 테이블 참조 (entity) */}
      {effectiveSource === "entity" && (
        <div className="rounded-lg border bg-muted/30 p-4 space-y-3">
          <div className="flex items-center gap-2">
            <Database className="h-4 w-4 text-primary" />
            <span className="text-sm font-medium">테이블 참조</span>
          </div>

          <div className="rounded-md border bg-background p-3">
            <p className="text-xs text-muted-foreground">참조 테이블</p>
            <p className="mt-0.5 text-sm font-medium">{config.entityTable || "미설정"}</p>
          </div>

          {loadingColumns && (
            <div className="text-muted-foreground flex items-center gap-2 text-xs">
              <Loader2 className="h-3 w-3 animate-spin" />
              컬럼 목록 로딩 중...
            </div>
          )}

          {entityColumns.length > 0 && (
            <div className="space-y-3">
              <div>
                <p className="mb-1.5 text-xs text-muted-foreground">실제 저장되는 값</p>
                <Select
                  value={config.entityValueColumn || ""}
                  onValueChange={(v) => updateConfig("entityValueColumn", v)}
                >
                  <SelectTrigger className="h-8 text-sm">
                    <SelectValue placeholder="컬럼 선택" />
                  </SelectTrigger>
                  <SelectContent>
                    {entityColumns.map((col) => (
                      <SelectItem key={col.columnName} value={col.columnName}>
                        {col.columnLabel}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div>
                <p className="mb-1.5 text-xs text-muted-foreground">사용자에게 보여지는 텍스트</p>
                <Select
                  value={config.entityLabelColumn || ""}
                  onValueChange={(v) => updateConfig("entityLabelColumn", v)}
                >
                  <SelectTrigger className="h-8 text-sm">
                    <SelectValue placeholder="컬럼 선택" />
                  </SelectTrigger>
                  <SelectContent>
                    {entityColumns.map((col) => (
                      <SelectItem key={col.columnName} value={col.columnName}>
                        {col.columnLabel}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <p className="text-[11px] text-muted-foreground">
                엔티티 선택 시 같은 폼의 관련 필드가 자동으로 채워져요
              </p>
            </div>
          )}

          {!loadingColumns && entityColumns.length === 0 && !config.entityTable && (
            <div className="rounded-md border-2 border-dashed p-4 text-center">
              <p className="text-sm text-muted-foreground">참조 테이블이 설정되지 않았어요</p>
              <p className="mt-1 text-xs text-muted-foreground">테이블 타입 관리에서 참조 테이블을 설정해주세요</p>
            </div>
          )}

          {config.entityTable && !loadingColumns && entityColumns.length === 0 && (
            <p className="text-[10px] text-amber-600">
              테이블 컬럼을 조회할 수 없습니다. 테이블 타입 관리에서 참조 테이블을 설정해주세요.
            </p>
          )}
        </div>
      )}

      {/* 카테고리 (category) - source="code" 하위 호환 포함 */}
      {effectiveSource === "category" && (
        <div className="rounded-lg border bg-muted/30 p-4 space-y-3">
          <div className="flex items-center gap-2">
            <FolderTree className="h-4 w-4 text-primary" />
            <span className="text-sm font-medium">카테고리</span>
          </div>

          {config.source === "code" && config.codeGroup && (
            <div className="rounded-md border bg-background p-3">
              <p className="text-xs text-muted-foreground">코드 그룹</p>
              <p className="mt-0.5 text-sm font-medium">{config.codeGroup}</p>
              <p className="mt-1 text-[11px] text-muted-foreground">
                테이블 컬럼에 설정된 코드 그룹이 자동으로 적용돼요
              </p>
            </div>
          )}

          <div className="rounded-md border bg-background p-3">
            <div className="flex gap-6">
              <div>
                <p className="text-xs text-muted-foreground">테이블</p>
                <p className="text-sm font-medium">{config.categoryTable || tableName || "-"}</p>
              </div>
              <div>
                <p className="text-xs text-muted-foreground">컬럼</p>
                <p className="text-sm font-medium">{config.categoryColumn || columnName || "-"}</p>
              </div>
            </div>
          </div>

          {loadingCategoryValues && (
            <div className="text-muted-foreground flex items-center gap-2 text-xs">
              <Loader2 className="h-3 w-3 animate-spin" />
              카테고리 값 로딩 중...
            </div>
          )}

          {categoryValues.length > 0 && (
            <div>
              <p className="mb-1.5 text-xs text-muted-foreground">
                {categoryValues.length}개의 값이 있어요
              </p>
              <div className="max-h-28 overflow-y-auto rounded-md border bg-background p-2 space-y-0.5">
                {categoryValues.map((cv) => (
                  <div key={cv.valueCode} className="flex items-center gap-2 px-1.5 py-0.5 text-xs">
                    <span className="shrink-0 font-mono text-[10px] text-muted-foreground">{cv.valueCode}</span>
                    <span className="truncate">{cv.valueLabel}</span>
                  </div>
                ))}
              </div>

              <div className="mt-3 flex items-center justify-between">
                <span className="text-xs text-muted-foreground">기본 선택값</span>
                <Select
                  value={config.defaultValue || "_none_"}
                  onValueChange={(value) => updateConfig("defaultValue", value === "_none_" ? "" : value)}
                >
                  <SelectTrigger className="h-8 w-[160px] text-sm">
                    <SelectValue placeholder="선택 안함" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="_none_">선택 안함</SelectItem>
                    {categoryValues.map((cv) => (
                      <SelectItem key={cv.valueCode} value={cv.valueCode}>
                        {cv.valueLabel}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </div>
          )}

          {!loadingCategoryValues && categoryValues.length === 0 && (
            <p className="text-[10px] text-amber-600">
              카테고리 값이 없습니다. 테이블 카테고리 관리에서 값을 추가해주세요.
            </p>
          )}
        </div>
      )}

      {/* 데이터 필터 (static 제외, filterTargetTable 있을 때만) */}
      {effectiveSource !== "static" && filterTargetTable && (
        <div className="rounded-lg border bg-muted/30 p-4">
          <FilterConditionsSection
            filters={(config.filters as V2SelectFilter[]) || []}
            columns={filterColumns}
            loadingColumns={loadingFilterColumns}
            targetTable={filterTargetTable}
            onFiltersChange={(filters) => updateConfig("filters", filters)}
          />
        </div>
      )}

      {/* ─── 3단계: 고급 설정 (기본 접혀있음) ─── */}
      <Collapsible open={advancedOpen} onOpenChange={setAdvancedOpen}>
        <CollapsibleTrigger asChild>
          <button
            type="button"
            className="flex w-full items-center justify-between rounded-lg border bg-muted/30 px-4 py-2.5 text-left transition-colors hover:bg-muted/50"
          >
            <div className="flex items-center gap-2">
              <Settings className="h-4 w-4 text-muted-foreground" />
              <span className="text-sm font-medium">고급 설정</span>
            </div>
            <ChevronDown
              className={cn(
                "h-4 w-4 text-muted-foreground transition-transform duration-200",
                advancedOpen && "rotate-180"
              )}
            />
          </button>
        </CollapsibleTrigger>
        <CollapsibleContent>
          <div className="rounded-b-lg border border-t-0 p-4 space-y-3">
            {/* 선택 모드 */}
            <div>
              <p className="mb-1.5 text-xs text-muted-foreground">선택 방식</p>
              <Select value={config.mode || "dropdown"} onValueChange={(v) => updateConfig("mode", v)}>
                <SelectTrigger className="h-8 text-sm">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="dropdown">드롭다운</SelectItem>
                  <SelectItem value="combobox">검색 가능 드롭다운</SelectItem>
                  <SelectItem value="radio">라디오 버튼</SelectItem>
                  <SelectItem value="check">체크박스</SelectItem>
                  <Separator className="my-1" />
                  <SelectItem value="tag">태그 선택</SelectItem>
                  <SelectItem value="tagbox">태그박스</SelectItem>
                  <SelectItem value="toggle">토글</SelectItem>
                  <SelectItem value="swap">스왑</SelectItem>
                </SelectContent>
              </Select>
              <p className="mt-1 text-[11px] text-muted-foreground">대부분의 경우 드롭다운이 적합해요</p>
            </div>

            {/* 토글 옵션들 */}
            <div className="space-y-2">
              <div className="flex items-center justify-between py-1">
                <div>
                  <p className="text-sm">여러 개 선택</p>
                  <p className="text-[11px] text-muted-foreground">한 번에 여러 값을 선택할 수 있어요</p>
                </div>
                <Switch
                  checked={config.multiple || false}
                  onCheckedChange={(checked) => updateConfig("multiple", checked)}
                />
              </div>

              {config.multiple && (
                <div className="ml-4 border-l-2 border-primary/20 pl-3">
                  <div className="flex items-center justify-between py-1">
                    <span className="text-xs text-muted-foreground">최대 선택 개수</span>
                    <Input
                      type="number"
                      value={config.maxSelect ?? ""}
                      onChange={(e) => updateConfig("maxSelect", e.target.value ? Number(e.target.value) : undefined)}
                      placeholder="제한 없음"
                      min={1}
                      className="h-7 w-[100px] text-xs"
                    />
                  </div>
                </div>
              )}

              <div className="flex items-center justify-between py-1">
                <div>
                  <p className="text-sm">검색 기능</p>
                  <p className="text-[11px] text-muted-foreground">옵션이 많을 때 검색으로 찾을 수 있어요</p>
                </div>
                <Switch
                  checked={config.searchable || false}
                  onCheckedChange={(checked) => updateConfig("searchable", checked)}
                />
              </div>

              <div className="flex items-center justify-between py-1">
                <div>
                  <p className="text-sm">선택 초기화</p>
                  <p className="text-[11px] text-muted-foreground">선택한 값을 지울 수 있는 X 버튼이 표시돼요</p>
                </div>
                <Switch
                  checked={config.allowClear !== false}
                  onCheckedChange={(checked) => updateConfig("allowClear", checked)}
                />
              </div>
            </div>
          </div>
        </CollapsibleContent>
      </Collapsible>
    </div>
  );
};

V2SelectConfigPanel.displayName = "V2SelectConfigPanel";

export default V2SelectConfigPanel;
