"use client";

/**
 * BOM 트리 뷰 설정 패널
 *
 * 토스식 단계별 UX:
 * - 기본 탭: 디테일 테이블 → 트리 구조 → 엔티티 → 표시 옵션 → 고급(이력/버전)
 * - 컬럼 탭: 소스 표시 컬럼 + 디테일 컬럼 + 선택된 컬럼 상세
 */

import React, { useState, useEffect, useMemo, useCallback } from "react";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Switch } from "@/components/ui/switch";
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 { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
import { Badge } from "@/components/ui/badge";
import {
  Database,
  Link2,
  Trash2,
  GripVertical,
  ArrowRight,
  ChevronDown,
  ChevronRight,
  Eye,
  EyeOff,
  Check,
  ChevronsUpDown,
  GitBranch,
  Settings,
} from "lucide-react";
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
} from "@/components/ui/command";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import { tableTypeApi } from "@/lib/api/screen";
import { tableManagementApi } from "@/lib/api/tableManagement";
import { cn } from "@/lib/utils";

interface TableRelation {
  tableName: string;
  tableLabel: string;
  foreignKeyColumn: string;
  referenceColumn: string;
}

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 TreeColumnConfig {
  key: string;
  title: string;
  width?: string;
  visible?: boolean;
  hidden?: boolean;
  isSourceDisplay?: boolean;
}

interface BomTreeConfig {
  detailTable?: string;
  foreignKey?: string;
  parentKey?: string;

  historyTable?: string;
  versionTable?: string;

  dataSource?: {
    sourceTable?: string;
    foreignKey?: string;
    referenceKey?: string;
    displayColumn?: string;
  };

  columns: TreeColumnConfig[];

  features?: {
    showExpandAll?: boolean;
    showHeader?: boolean;
    showQuantity?: boolean;
    showLossRate?: boolean;
    showHistory?: boolean;
    showVersion?: boolean;
  };
}

interface V2BomTreeConfigPanelProps {
  config: BomTreeConfig;
  onChange: (config: BomTreeConfig) => void;
  currentTableName?: string;
  screenTableName?: string;
}

export function V2BomTreeConfigPanel({
  config: propConfig,
  onChange,
  currentTableName: propCurrentTableName,
  screenTableName,
}: V2BomTreeConfigPanelProps) {
  const currentTableName = screenTableName || propCurrentTableName;

  const config: BomTreeConfig = useMemo(
    () => {
      const { columns: propColumns, ...rest } = propConfig || {} as BomTreeConfig;
      return {
        ...rest,
        columns: propColumns || [],
        dataSource: { ...propConfig?.dataSource },
        features: {
          showExpandAll: true,
          showHeader: true,
          showQuantity: true,
          showLossRate: true,
          ...propConfig?.features,
        },
      };
    },
    [propConfig],
  );

  const [detailTableColumns, setDetailTableColumns] = useState<ColumnOption[]>([]);
  const [entityColumns, setEntityColumns] = useState<EntityColumnOption[]>([]);
  const [sourceTableColumns, setSourceTableColumns] = useState<ColumnOption[]>([]);
  const [allTables, setAllTables] = useState<{ tableName: string; displayName: string }[]>([]);
  const [relatedTables, setRelatedTables] = useState<TableRelation[]>([]);
  const [loadingColumns, setLoadingColumns] = useState(false);
  const [loadingSourceColumns, setLoadingSourceColumns] = useState(false);
  const [loadingTables, setLoadingTables] = useState(false);
  const [loadingRelations, setLoadingRelations] = useState(false);
  const [tableComboboxOpen, setTableComboboxOpen] = useState(false);
  const [expandedColumn, setExpandedColumn] = useState<string | null>(null);
  const [displayOptionsOpen, setDisplayOptionsOpen] = useState(false);
  const [columnSelectOpen, setColumnSelectOpen] = useState(false);
  const [selectedColumnsOpen, setSelectedColumnsOpen] = useState(false);
  const [advancedOpen, setAdvancedOpen] = useState(false);

  const updateConfig = useCallback(
    (updates: Partial<BomTreeConfig>) => {
      onChange({ ...config, ...updates });
    },
    [config, onChange],
  );

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

  // 전체 테이블 목록 로드
  useEffect(() => {
    const loadTables = async () => {
      setLoadingTables(true);
      try {
        const response = await tableManagementApi.getTableList();
        if (response.success && response.data) {
          setAllTables(
            response.data.map((t: any) => ({
              tableName: t.tableName || t.table_name,
              displayName: t.displayName || t.table_label || t.tableName || t.table_name,
            })),
          );
        }
      } catch (error) {
        console.error("테이블 목록 로드 실패:", error);
      } finally {
        setLoadingTables(false);
      }
    };
    loadTables();
  }, []);

  // 연관 테이블 로드
  useEffect(() => {
    const loadRelatedTables = async () => {
      const baseTable = currentTableName;
      if (!baseTable) {
        setRelatedTables([]);
        return;
      }
      setLoadingRelations(true);
      try {
        const { apiClient } = await import("@/lib/api/client");
        const response = await apiClient.get(
          `/table-management/columns/${baseTable}/referenced-by`,
        );
        if (response.data.success && response.data.data) {
          setRelatedTables(
            response.data.data.map((rel: any) => ({
              tableName: rel.tableName || rel.table_name,
              tableLabel: rel.tableLabel || rel.table_label || rel.tableName || rel.table_name,
              foreignKeyColumn: rel.columnName || rel.column_name,
              referenceColumn: rel.referenceColumn || rel.reference_column || "id",
            })),
          );
        }
      } catch (error) {
        console.error("연관 테이블 로드 실패:", error);
        setRelatedTables([]);
      } finally {
        setLoadingRelations(false);
      }
    };
    loadRelatedTables();
  }, [currentTableName]);

  // 디테일 테이블 선택
  const handleDetailTableSelect = useCallback(
    (tableName: string) => {
      const relation = relatedTables.find((r) => r.tableName === tableName);
      updateConfig({
        detailTable: tableName,
        foreignKey: relation?.foreignKeyColumn || config.foreignKey,
      });
    },
    [relatedTables, config.foreignKey, updateConfig],
  );

  // 디테일 테이블 컬럼 로드
  useEffect(() => {
    const loadColumns = async () => {
      if (!config.detailTable) {
        setDetailTableColumns([]);
        setEntityColumns([]);
        return;
      }
      setLoadingColumns(true);
      try {
        const columnData = await tableTypeApi.getColumns(config.detailTable);
        const cols: ColumnOption[] = [];
        const entityCols: EntityColumnOption[] = [];

        for (const c of columnData) {
          let detailSettings: any = null;
          if (c.detailSettings) {
            try {
              detailSettings =
                typeof c.detailSettings === "string" ? JSON.parse(c.detailSettings) : c.detailSettings;
            } catch {
              // ignore
            }
          }

          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 refTable = detailSettings?.referenceTable || c.referenceTable;
            if (refTable) {
              entityCols.push({
                columnName: col.columnName,
                displayName: col.displayName,
                referenceTable: refTable,
                referenceColumn: detailSettings?.referenceColumn || c.referenceColumn || "id",
                displayColumn: detailSettings?.displayColumn || c.displayColumn,
              });
            }
          }
        }

        setDetailTableColumns(cols);
        setEntityColumns(entityCols);
      } catch (error) {
        console.error("컬럼 로드 실패:", error);
        setDetailTableColumns([]);
        setEntityColumns([]);
      } finally {
        setLoadingColumns(false);
      }
    };
    loadColumns();
  }, [config.detailTable]);

  // 소스(엔티티) 테이블 컬럼 로드
  useEffect(() => {
    const loadSourceColumns = async () => {
      const sourceTable = config.dataSource?.sourceTable;
      if (!sourceTable) {
        setSourceTableColumns([]);
        return;
      }
      setLoadingSourceColumns(true);
      try {
        const columnData = await tableTypeApi.getColumns(sourceTable);
        setSourceTableColumns(
          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,
          })),
        );
      } catch (error) {
        console.error("소스 테이블 컬럼 로드 실패:", error);
        setSourceTableColumns([]);
      } finally {
        setLoadingSourceColumns(false);
      }
    };
    loadSourceColumns();
  }, [config.dataSource?.sourceTable]);

  // 엔티티 컬럼 선택 시 소스 테이블 자동 설정
  const handleEntityColumnSelect = (columnName: string) => {
    const selectedEntity = entityColumns.find((c) => c.columnName === columnName);
    if (selectedEntity) {
      updateConfig({
        dataSource: {
          ...config.dataSource,
          sourceTable: selectedEntity.referenceTable || "",
          foreignKey: selectedEntity.columnName,
          referenceKey: selectedEntity.referenceColumn || "id",
          displayColumn: selectedEntity.displayColumn,
        },
      });
    }
  };

  // 컬럼 토글
  const toggleDetailColumn = (column: ColumnOption) => {
    const exists = config.columns.findIndex((c) => c.key === column.columnName && !c.isSourceDisplay);
    if (exists >= 0) {
      updateConfig({ columns: config.columns.filter((c) => c.key !== column.columnName || c.isSourceDisplay) });
    } else {
      const newCol: TreeColumnConfig = {
        key: column.columnName,
        title: column.displayName,
        width: "auto",
        visible: true,
      };
      updateConfig({ columns: [...config.columns, newCol] });
    }
  };

  const toggleSourceDisplayColumn = (column: ColumnOption) => {
    const exists = config.columns.some((c) => c.key === column.columnName && c.isSourceDisplay);
    if (exists) {
      updateConfig({ columns: config.columns.filter((c) => c.key !== column.columnName) });
    } else {
      const newCol: TreeColumnConfig = {
        key: column.columnName,
        title: column.displayName,
        width: "auto",
        visible: true,
        isSourceDisplay: true,
      };
      updateConfig({ columns: [...config.columns, newCol] });
    }
  };

  const isColumnAdded = (columnName: string) =>
    config.columns.some((c) => c.key === columnName && !c.isSourceDisplay);

  const isSourceColumnSelected = (columnName: string) =>
    config.columns.some((c) => c.key === columnName && c.isSourceDisplay);

  const updateColumnProp = (key: string, field: keyof TreeColumnConfig, value: any) => {
    updateConfig({
      columns: config.columns.map((col) => (col.key === key ? { ...col, [field]: value } : col)),
    });
  };

  const displayableColumns = useMemo(() => {
    const fkColumn = config.dataSource?.foreignKey;
    const systemCols = ["id", "created_at", "updated_at", "created_by", "updated_by", "company_code", "created_date"];
    return detailTableColumns.filter(
      (col) => col.columnName !== fkColumn && col.inputType !== "entity" && !systemCols.includes(col.columnName),
    );
  }, [detailTableColumns, config.dataSource?.foreignKey]);

  const fkCandidateColumns = useMemo(() => {
    const systemCols = ["created_at", "updated_at", "created_by", "updated_by", "company_code", "created_date"];
    return detailTableColumns.filter((c) => !systemCols.includes(c.columnName));
  }, [detailTableColumns]);

  return (
    <div className="space-y-4">
      <Tabs defaultValue="basic" className="w-full">
        <TabsList className="grid w-full grid-cols-2">
          <TabsTrigger value="basic" className="text-xs">
            기본
          </TabsTrigger>
          <TabsTrigger value="columns" className="text-xs">
            컬럼
          </TabsTrigger>
        </TabsList>

        {/* ─── 기본 설정 탭 ─── */}
        <TabsContent value="basic" className="mt-4 space-y-4">
          {/* 디테일 테이블 */}
          <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">BOM 디테일을 어디에서 가져오나요?</span>
            </div>

            <div
              className={cn(
                "rounded-lg border p-3",
                config.detailTable ? "border-orange-300 bg-amber-50" : "border-input bg-muted",
              )}
            >
              <div className="flex items-center gap-2">
                <Database
                  className={cn("h-4 w-4", config.detailTable ? "text-amber-600" : "text-muted-foreground/70")}
                />
                <div className="flex-1">
                  <p className={cn("text-sm font-medium", config.detailTable ? "text-orange-700" : "text-muted-foreground")}>
                    {config.detailTable
                      ? allTables.find((t) => t.tableName === config.detailTable)?.displayName || config.detailTable
                      : "미설정"}
                  </p>
                  {config.detailTable && config.foreignKey && (
                    <p className="mt-0.5 text-[10px] text-amber-600">
                      FK: {config.foreignKey} &rarr; {currentTableName || "메인 테이블"}.id
                    </p>
                  )}
                </div>
              </div>
            </div>

            <Popover open={tableComboboxOpen} onOpenChange={setTableComboboxOpen}>
              <PopoverTrigger asChild>
                <Button
                  variant="outline"
                  role="combobox"
                  aria-expanded={tableComboboxOpen}
                  disabled={loadingTables || loadingRelations}
                  className="h-8 w-full justify-between text-xs"
                >
                  {loadingTables ? "로딩 중..." : "디테일 테이블 선택..."}
                  <ChevronsUpDown className="ml-2 h-3 w-3 shrink-0 opacity-50" />
                </Button>
              </PopoverTrigger>
              <PopoverContent
                className="p-0"
                style={{ width: "var(--radix-popover-trigger-width)" }}
                align="start"
              >
                <Command>
                  <CommandInput placeholder="테이블 검색..." className="text-xs" />
                  <CommandList className="max-h-60">
                    <CommandEmpty className="py-3 text-center text-xs">
                      테이블을 찾을 수 없어요.
                    </CommandEmpty>

                    {relatedTables.length > 0 && (
                      <CommandGroup heading="연관 테이블 (FK 자동 설정)">
                        {relatedTables.map((rel) => (
                          <CommandItem
                            key={rel.tableName}
                            value={`${rel.tableName} ${rel.tableLabel}`}
                            onSelect={() => {
                              handleDetailTableSelect(rel.tableName);
                              setTableComboboxOpen(false);
                            }}
                            className="text-xs"
                          >
                            <Check
                              className={cn(
                                "mr-2 h-3 w-3",
                                config.detailTable === rel.tableName ? "opacity-100" : "opacity-0",
                              )}
                            />
                            <Link2 className="mr-2 h-3 w-3 text-amber-500" />
                            <span>{rel.tableLabel}</span>
                            <span className="text-muted-foreground ml-1 text-[10px]">
                              ({rel.foreignKeyColumn})
                            </span>
                          </CommandItem>
                        ))}
                      </CommandGroup>
                    )}

                    <CommandGroup heading="전체 테이블">
                      {allTables
                        .filter((t) => !relatedTables.some((r) => r.tableName === t.tableName))
                        .map((table) => (
                          <CommandItem
                            key={table.tableName}
                            value={`${table.tableName} ${table.displayName}`}
                            onSelect={() => {
                              handleDetailTableSelect(table.tableName);
                              setTableComboboxOpen(false);
                            }}
                            className="text-xs"
                          >
                            <Check
                              className={cn(
                                "mr-2 h-3 w-3",
                                config.detailTable === table.tableName ? "opacity-100" : "opacity-0",
                              )}
                            />
                            <Database className="mr-2 h-3 w-3 text-muted-foreground/70" />
                            <span>{table.displayName}</span>
                          </CommandItem>
                        ))}
                    </CommandGroup>
                  </CommandList>
                </Command>
              </PopoverContent>
            </Popover>

            {/* 화면 메인 테이블 참고 */}
            {currentTableName && (
              <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">{currentTableName}</p>
                <p className="text-[10px] text-muted-foreground mt-0.5">
                  컬럼 {detailTableColumns.length}개 / 엔티티 {entityColumns.length}개
                </p>
              </div>
            )}
          </div>

          {/* 트리 구조 설정 */}
          <div className="rounded-lg border bg-muted/30 p-4 space-y-3">
            <div className="flex items-center gap-2">
              <GitBranch className="h-4 w-4 text-primary" />
              <span className="text-sm font-medium">트리 구조는 어떻게 만드나요?</span>
            </div>
            <p className="text-[11px] text-muted-foreground">
              메인 FK와 부모-자식 계층 FK를 선택하면 트리 구조가 만들어져요
            </p>

            {fkCandidateColumns.length > 0 ? (
              <div className="space-y-3">
                <div>
                  <p className="mb-1.5 text-xs text-muted-foreground">FK 컬럼 (메인 테이블 참조)</p>
                  <Select
                    value={config.foreignKey || ""}
                    onValueChange={(value) => updateConfig({ foreignKey: value })}
                  >
                    <SelectTrigger className="h-8 text-sm">
                      <SelectValue placeholder="FK 컬럼 선택" />
                    </SelectTrigger>
                    <SelectContent>
                      {fkCandidateColumns.map((col) => (
                        <SelectItem key={col.columnName} value={col.columnName}>
                          <div className="flex items-center gap-2">
                            <span>{col.displayName}</span>
                            {col.displayName !== col.columnName && (
                              <span className="text-muted-foreground text-[10px]">({col.columnName})</span>
                            )}
                          </div>
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
                <div>
                  <p className="mb-1.5 text-xs text-muted-foreground">부모 키 컬럼 (자기 참조 FK)</p>
                  <Select
                    value={config.parentKey || ""}
                    onValueChange={(value) => updateConfig({ parentKey: value })}
                  >
                    <SelectTrigger className="h-8 text-sm">
                      <SelectValue placeholder="부모 키 컬럼 선택" />
                    </SelectTrigger>
                    <SelectContent>
                      {fkCandidateColumns.map((col) => (
                        <SelectItem key={col.columnName} value={col.columnName}>
                          <div className="flex items-center gap-2">
                            <span>{col.displayName}</span>
                            {col.displayName !== col.columnName && (
                              <span className="text-muted-foreground text-[10px]">({col.columnName})</span>
                            )}
                          </div>
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
              </div>
            ) : (
              <div className="rounded-md border-2 border-dashed p-4 text-center">
                <GitBranch className="mx-auto mb-2 h-8 w-8 opacity-30 text-muted-foreground" />
                <p className="text-sm text-muted-foreground">
                  {loadingColumns ? "컬럼 정보를 불러오고 있어요..." : "디테일 테이블을 먼저 선택해주세요"}
                </p>
              </div>
            )}
          </div>

          {/* 엔티티 선택 (품목 참조) */}
          <div className="rounded-lg border bg-muted/30 p-4 space-y-3">
            <div className="flex items-center gap-2">
              <Link2 className="h-4 w-4 text-primary" />
              <span className="text-sm font-medium">어떤 품목 정보를 표시하나요?</span>
            </div>
            <p className="text-[11px] text-muted-foreground">
              트리 노드에 표시할 품목 정보의 소스 엔티티를 선택해주세요
            </p>

            {entityColumns.length > 0 ? (
              <Select
                value={config.dataSource?.foreignKey || ""}
                onValueChange={handleEntityColumnSelect}
                disabled={!config.detailTable}
              >
                <SelectTrigger className="h-8 text-sm">
                  <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-primary" />
                        <span>{col.displayName}</span>
                        <ArrowRight className="h-3 w-3 text-muted-foreground/70" />
                        <span className="text-muted-foreground">{col.referenceTable}</span>
                      </div>
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            ) : (
              <div className="rounded-md border-2 border-dashed p-4 text-center">
                <p className="text-sm text-muted-foreground">
                  {loadingColumns
                    ? "컬럼 정보를 불러오고 있어요..."
                    : !config.detailTable
                      ? "디테일 테이블을 먼저 선택해주세요"
                      : "엔티티 타입 컬럼이 없어요"}
                </p>
              </div>
            )}

            {config.dataSource?.sourceTable && (
              <div className="rounded-md border bg-background p-3 space-y-1">
                <p className="text-xs text-muted-foreground">선택된 엔티티</p>
                <p className="text-sm font-medium">{config.dataSource.sourceTable}</p>
                <p className="text-[11px] text-muted-foreground">
                  {config.dataSource.foreignKey} 컬럼에서 참조해요
                </p>
              </div>
            )}
          </div>

          {/* 표시 옵션 - Collapsible + Badge */}
          <Collapsible open={displayOptionsOpen} onOpenChange={setDisplayOptionsOpen}>
            <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">
                  <Eye className="h-4 w-4 text-muted-foreground" />
                  <span className="text-sm font-medium">표시 옵션</span>
                  <Badge
                    variant="secondary"
                    className="text-[10px] h-5"
                  >
                    {[
                      config.features?.showExpandAll ?? true,
                      config.features?.showHeader ?? true,
                      config.features?.showQuantity ?? true,
                      config.features?.showLossRate ?? true,
                    ].filter(Boolean).length}
                    /4
                  </Badge>
                </div>
                <ChevronDown
                  className={cn(
                    "h-4 w-4 text-muted-foreground transition-transform duration-200",
                    displayOptionsOpen && "rotate-180",
                  )}
                />
              </button>
            </CollapsibleTrigger>
            <CollapsibleContent>
              <div className="rounded-b-lg border border-t-0 p-3 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.features?.showExpandAll ?? true}
                    onCheckedChange={(checked) => updateFeatures("showExpandAll", checked)}
                  />
                </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.features?.showHeader ?? true}
                    onCheckedChange={(checked) => updateFeatures("showHeader", checked)}
                  />
                </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.features?.showQuantity ?? true}
                    onCheckedChange={(checked) => updateFeatures("showQuantity", checked)}
                  />
                </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.features?.showLossRate ?? true}
                    onCheckedChange={(checked) => updateFeatures("showLossRate", checked)}
                  />
                </div>
              </div>
            </CollapsibleContent>
          </Collapsible>

          {/* 고급 설정 (이력/버전 관리) - Collapsible + Badge */}
          <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>
                  <Badge variant="secondary" className="text-[10px] h-5">
                    2개
                  </Badge>
                </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-4">
                {/* 이력 관리 */}
                <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">BOM 변경 이력을 추적해요</p>
                    </div>
                    <Switch
                      checked={config.features?.showHistory ?? true}
                      onCheckedChange={(checked) => updateFeatures("showHistory", checked)}
                    />
                  </div>
                  {(config.features?.showHistory ?? true) && (
                    <div className="ml-4 border-l-2 border-primary/20 pl-3">
                      <p className="mb-1.5 text-xs text-muted-foreground">이력 테이블</p>
                      <Popover>
                        <PopoverTrigger asChild>
                          <Button
                            variant="outline"
                            role="combobox"
                            disabled={loadingTables}
                            className="h-8 w-full justify-between text-xs"
                          >
                            {config.historyTable
                              ? allTables.find((t) => t.tableName === config.historyTable)?.displayName || config.historyTable
                              : "이력 테이블 선택..."}
                            <ChevronsUpDown className="ml-2 h-3 w-3 shrink-0 opacity-50" />
                          </Button>
                        </PopoverTrigger>
                        <PopoverContent
                          className="p-0"
                          style={{ width: "var(--radix-popover-trigger-width)" }}
                          align="start"
                        >
                          <Command>
                            <CommandInput placeholder="테이블 검색..." className="text-xs" />
                            <CommandList className="max-h-48">
                              <CommandEmpty className="py-3 text-center text-xs">
                                테이블을 찾을 수 없어요.
                              </CommandEmpty>
                              <CommandGroup>
                                {allTables.map((table) => (
                                  <CommandItem
                                    key={table.tableName}
                                    value={`${table.tableName} ${table.displayName}`}
                                    onSelect={() => updateConfig({ historyTable: table.tableName })}
                                    className="text-xs"
                                  >
                                    <Check
                                      className={cn(
                                        "mr-2 h-3 w-3",
                                        config.historyTable === table.tableName ? "opacity-100" : "opacity-0",
                                      )}
                                    />
                                    <Database className="mr-2 h-3 w-3 text-muted-foreground/70" />
                                    <span>{table.displayName}</span>
                                  </CommandItem>
                                ))}
                              </CommandGroup>
                            </CommandList>
                          </Command>
                        </PopoverContent>
                      </Popover>
                    </div>
                  )}
                </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">BOM 버전별로 관리해요</p>
                    </div>
                    <Switch
                      checked={config.features?.showVersion ?? true}
                      onCheckedChange={(checked) => updateFeatures("showVersion", checked)}
                    />
                  </div>
                  {(config.features?.showVersion ?? true) && (
                    <div className="ml-4 border-l-2 border-primary/20 pl-3">
                      <p className="mb-1.5 text-xs text-muted-foreground">버전 테이블</p>
                      <Popover>
                        <PopoverTrigger asChild>
                          <Button
                            variant="outline"
                            role="combobox"
                            disabled={loadingTables}
                            className="h-8 w-full justify-between text-xs"
                          >
                            {config.versionTable
                              ? allTables.find((t) => t.tableName === config.versionTable)?.displayName || config.versionTable
                              : "버전 테이블 선택..."}
                            <ChevronsUpDown className="ml-2 h-3 w-3 shrink-0 opacity-50" />
                          </Button>
                        </PopoverTrigger>
                        <PopoverContent
                          className="p-0"
                          style={{ width: "var(--radix-popover-trigger-width)" }}
                          align="start"
                        >
                          <Command>
                            <CommandInput placeholder="테이블 검색..." className="text-xs" />
                            <CommandList className="max-h-48">
                              <CommandEmpty className="py-3 text-center text-xs">
                                테이블을 찾을 수 없어요.
                              </CommandEmpty>
                              <CommandGroup>
                                {allTables.map((table) => (
                                  <CommandItem
                                    key={table.tableName}
                                    value={`${table.tableName} ${table.displayName}`}
                                    onSelect={() => updateConfig({ versionTable: table.tableName })}
                                    className="text-xs"
                                  >
                                    <Check
                                      className={cn(
                                        "mr-2 h-3 w-3",
                                        config.versionTable === table.tableName ? "opacity-100" : "opacity-0",
                                      )}
                                    />
                                    <Database className="mr-2 h-3 w-3 text-muted-foreground/70" />
                                    <span>{table.displayName}</span>
                                  </CommandItem>
                                ))}
                              </CommandGroup>
                            </CommandList>
                          </Command>
                        </PopoverContent>
                      </Popover>
                    </div>
                  )}
                </div>
              </div>
            </CollapsibleContent>
          </Collapsible>
        </TabsContent>

        {/* ─── 컬럼 설정 탭 ─── */}
        <TabsContent value="columns" className="mt-4 space-y-4">
          {/* 컬럼 선택 - Collapsible + Badge */}
          <Collapsible open={columnSelectOpen} onOpenChange={setColumnSelectOpen}>
            <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">
                  <Database className="h-4 w-4 text-muted-foreground" />
                  <span className="text-sm font-medium">컬럼 선택</span>
                  <Badge variant="secondary" className="text-[10px] h-5">
                    {config.columns.length}개 선택됨
                  </Badge>
                </div>
                <ChevronDown
                  className={cn(
                    "h-4 w-4 text-muted-foreground transition-transform duration-200",
                    columnSelectOpen && "rotate-180",
                  )}
                />
              </button>
            </CollapsibleTrigger>
            <CollapsibleContent>
              <div className="rounded-b-lg border border-t-0 p-3 space-y-2">
                <p className="text-[11px] text-muted-foreground">
                  소스 테이블 컬럼은 표시용, 디테일 테이블 컬럼은 직접 컬럼이에요
                </p>

                {/* 소스 테이블 컬럼 (표시용) */}
                {config.dataSource?.sourceTable && (
                  <>
                    <div className="mb-1 mt-2 flex items-center gap-1 text-[10px] font-medium text-primary">
                      <Link2 className="h-3 w-3" />
                      소스 테이블 ({config.dataSource.sourceTable}) - 표시용
                    </div>
                    {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-28 space-y-0.5 overflow-y-auto rounded-md border border-primary/20 bg-primary/10/30 p-2">
                        {sourceTableColumns.map((column) => (
                          <div
                            key={`source-${column.columnName}`}
                            className={cn(
                              "flex cursor-pointer items-center gap-2 rounded px-2 py-1 hover:bg-primary/10/50",
                              isSourceColumnSelected(column.columnName) && "bg-primary/10",
                            )}
                            onClick={() => toggleSourceDisplayColumn(column)}
                          >
                            <Checkbox
                              checked={isSourceColumnSelected(column.columnName)}
                              onCheckedChange={() => toggleSourceDisplayColumn(column)}
                              className="pointer-events-none h-3.5 w-3.5"
                            />
                            <Link2 className="h-3 w-3 flex-shrink-0 text-primary" />
                            <span className="truncate text-xs">{column.displayName}</span>
                            <span className="ml-auto text-[10px] text-primary/80">표시</span>
                          </div>
                        ))}
                      </div>
                    )}
                  </>
                )}

                {/* 디테일 테이블 컬럼 */}
                <div className="mb-1 mt-3 flex items-center gap-1 text-[10px] font-medium text-muted-foreground">
                  <Database className="h-3 w-3" />
                  디테일 테이블 ({config.detailTable || "미선택"}) - 직접 컬럼
                </div>
                {loadingColumns ? (
                  <p className="text-muted-foreground py-2 text-xs">로딩 중...</p>
                ) : displayableColumns.length === 0 ? (
                  <p className="text-muted-foreground py-2 text-xs">컬럼 정보가 없어요</p>
                ) : (
                  <div className="max-h-36 space-y-0.5 overflow-y-auto rounded-md border p-2">
                    {displayableColumns.map((column) => (
                      <div
                        key={`detail-${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={() => toggleDetailColumn(column)}
                      >
                        <Checkbox
                          checked={isColumnAdded(column.columnName)}
                          onCheckedChange={() => toggleDetailColumn(column)}
                          className="pointer-events-none h-3.5 w-3.5"
                        />
                        <Database className="text-muted-foreground h-3 w-3 flex-shrink-0" />
                        <span className="truncate text-xs">{column.displayName}</span>
                        <span className="ml-auto text-[10px] text-muted-foreground/70">{column.inputType}</span>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            </CollapsibleContent>
          </Collapsible>

          {/* 선택된 컬럼 상세 - Collapsible + Badge */}
          {config.columns.length > 0 && (
            <Collapsible open={selectedColumnsOpen} onOpenChange={setSelectedColumnsOpen}>
              <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">
                    <GripVertical className="h-4 w-4 text-muted-foreground" />
                    <span className="text-sm font-medium">선택된 컬럼</span>
                    <Badge variant="secondary" className="text-[10px] h-5">
                      {config.columns.length}개
                    </Badge>
                  </div>
                  <ChevronDown
                    className={cn(
                      "h-4 w-4 text-muted-foreground transition-transform duration-200",
                      selectedColumnsOpen && "rotate-180",
                    )}
                  />
                </button>
              </CollapsibleTrigger>
              <CollapsibleContent>
                <div className="rounded-b-lg border border-t-0 p-3 space-y-2">
                  <span className="text-[11px] text-muted-foreground">드래그로 순서 변경</span>
                  <div className="max-h-48 space-y-1 overflow-y-auto">
                {config.columns.map((col, index) => (
                  <div key={col.key} className="space-y-1">
                    <div
                      className={cn(
                        "flex items-center gap-2 rounded-md border p-2",
                        col.isSourceDisplay
                          ? "border-primary/20 bg-primary/10/50"
                          : "border-border bg-muted/30",
                        col.hidden && "opacity-50",
                      )}
                      draggable
                      onDragStart={(e) => e.dataTransfer.setData("columnIndex", String(index))}
                      onDragOver={(e) => e.preventDefault()}
                      onDrop={(e) => {
                        e.preventDefault();
                        const fromIndex = parseInt(e.dataTransfer.getData("columnIndex"), 10);
                        if (fromIndex !== index) {
                          const newColumns = [...config.columns];
                          const [movedCol] = newColumns.splice(fromIndex, 1);
                          newColumns.splice(index, 0, movedCol);
                          updateConfig({ columns: newColumns });
                        }
                      }}
                    >
                      <GripVertical className="text-muted-foreground h-3 w-3 cursor-grab flex-shrink-0" />

                      {!col.isSourceDisplay && (
                        <button
                          type="button"
                          onClick={() =>
                            setExpandedColumn(expandedColumn === col.key ? null : col.key)
                          }
                          className="rounded p-0.5 hover:bg-muted/80"
                        >
                          {expandedColumn === col.key ? (
                            <ChevronDown className="h-3 w-3 text-muted-foreground" />
                          ) : (
                            <ChevronRight className="h-3 w-3 text-muted-foreground" />
                          )}
                        </button>
                      )}

                      {col.isSourceDisplay ? (
                        <Link2 className="h-3 w-3 flex-shrink-0 text-primary" />
                      ) : (
                        <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"
                      />

                      {!col.isSourceDisplay && (
                        <button
                          type="button"
                          onClick={() => updateColumnProp(col.key, "hidden", !col.hidden)}
                          className={cn(
                            "rounded p-1 hover:bg-muted/80",
                            col.hidden ? "text-muted-foreground/70" : "text-muted-foreground",
                          )}
                          title={col.hidden ? "히든" : "표시됨"}
                        >
                          {col.hidden ? (
                            <EyeOff className="h-3 w-3" />
                          ) : (
                            <Eye className="h-3 w-3" />
                          )}
                        </button>
                      )}

                      <Button
                        type="button"
                        variant="ghost"
                        size="sm"
                        onClick={() => {
                          if (col.isSourceDisplay) {
                            toggleSourceDisplayColumn({ columnName: col.key, displayName: col.title });
                          } else {
                            toggleDetailColumn({ columnName: col.key, displayName: col.title });
                          }
                        }}
                        className="text-destructive h-6 w-6 p-0"
                      >
                        <Trash2 className="h-3 w-3" />
                      </Button>
                    </div>

                    {/* 확장 상세 */}
                    {!col.isSourceDisplay && expandedColumn === col.key && (
                      <div className="ml-6 space-y-2 rounded-md border border-dashed border-input bg-muted p-2">
                        <div className="space-y-1">
                          <p className="text-[10px] text-muted-foreground">컬럼 너비</p>
                          <Input
                            value={col.width || "auto"}
                            onChange={(e) => updateColumnProp(col.key, "width", e.target.value)}
                            placeholder="auto, 100px, 20%"
                            className="h-6 text-xs"
                          />
                        </div>
                      </div>
                    )}
                  </div>
                ))}
                  </div>
                </div>
              </CollapsibleContent>
            </Collapsible>
          )}
        </TabsContent>
      </Tabs>
    </div>
  );
}

V2BomTreeConfigPanel.displayName = "V2BomTreeConfigPanel";

export default V2BomTreeConfigPanel;
