"use client";

/**
 * V2Hierarchy 설정 패널
 * 토스식 단계별 UX: 계층 타입 카드 선택 -> 데이터 소스 설정 -> 고급 설정(접힘)
 */

import React, { useState, useEffect } from "react";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Switch } from "@/components/ui/switch";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
import {
  GitFork,
  Building2,
  Layers,
  ListTree,
  Database,
  FileJson,
  Globe,
  Settings,
  ChevronDown,
  Loader2,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { tableTypeApi } from "@/lib/api/screen";

interface V2HierarchyConfigPanelProps {
  config: Record<string, any>;
  onChange: (config: Record<string, any>) => void;
}

interface TableOption {
  tableName: string;
  displayName: string;
}

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

const HIERARCHY_TYPE_CARDS = [
  { value: "tree", icon: GitFork, title: "트리", description: "계층 구조를 표시해요" },
  { value: "org-chart", icon: Building2, title: "조직도", description: "조직 구조를 보여줘요" },
  { value: "bom", icon: Layers, title: "BOM", description: "부품 구성을 관리해요" },
  { value: "cascading", icon: ListTree, title: "연쇄 선택", description: "단계별로 선택해요" },
] as const;

const DATA_SOURCE_CARDS = [
  { value: "static", icon: FileJson, title: "정적 데이터", description: "직접 입력해요" },
  { value: "db", icon: Database, title: "데이터베이스", description: "테이블에서 가져와요" },
  { value: "api", icon: Globe, title: "API", description: "외부 API로 조회해요" },
] as const;

export const V2HierarchyConfigPanel: React.FC<V2HierarchyConfigPanelProps> = ({
  config,
  onChange,
}) => {
  const [tables, setTables] = useState<TableOption[]>([]);
  const [loadingTables, setLoadingTables] = useState(false);
  const [columns, setColumns] = useState<ColumnOption[]>([]);
  const [loadingColumns, setLoadingColumns] = useState(false);
  const [advancedOpen, setAdvancedOpen] = useState(false);

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

  useEffect(() => {
    const loadTables = async () => {
      setLoadingTables(true);
      try {
        const data = await tableTypeApi.getTables();
        setTables(data.map(t => ({
          tableName: t.tableName,
          displayName: t.displayName || t.tableName
        })));
      } catch (error) {
        console.error("테이블 목록 로드 실패:", error);
      } finally {
        setLoadingTables(false);
      }
    };
    loadTables();
  }, []);

  useEffect(() => {
    const loadColumns = async () => {
      if (!config.tableName) { setColumns([]); return; }
      setLoadingColumns(true);
      try {
        const data = await tableTypeApi.getColumns(config.tableName);
        setColumns(data.map((c: any) => ({
          columnName: c.columnName || c.column_name,
          displayName: c.displayName || c.columnName || c.column_name
        })));
      } catch (error) {
        console.error("컬럼 목록 로드 실패:", error);
      } finally {
        setLoadingColumns(false);
      }
    };
    loadColumns();
  }, [config.tableName]);

  const hierarchyType = config.hierarchyType || config.type || "tree";
  const dataSource = config.dataSource || "static";

  return (
    <div className="space-y-4">
      {/* ─── 1단계: 계층 타입 선택 (카드) ─── */}
      <div className="space-y-2">
        <p className="text-sm font-medium">어떤 계층 구조를 사용하나요?</p>
        <div className="grid grid-cols-2 gap-2">
          {HIERARCHY_TYPE_CARDS.map((card) => {
            const Icon = card.icon;
            const isSelected = hierarchyType === card.value;
            return (
              <button
                key={card.value}
                type="button"
                onClick={() => updateConfig("hierarchyType", 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단계: 표시 방식 ─── */}
      <div className="rounded-lg border bg-muted/30 p-4 space-y-3">
        <span className="text-sm font-medium">표시 방식</span>
        <Select
          value={config.viewMode || "tree"}
          onValueChange={(value) => updateConfig("viewMode", value)}
        >
          <SelectTrigger className="h-8 text-sm">
            <SelectValue placeholder="방식 선택" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="tree">트리뷰</SelectItem>
            <SelectItem value="table">테이블</SelectItem>
            <SelectItem value="chart">차트</SelectItem>
            <SelectItem value="cascading">연쇄 드롭다운</SelectItem>
          </SelectContent>
        </Select>
        <p className="text-[11px] text-muted-foreground">데이터를 어떤 형태로 보여줄지 선택해요</p>
      </div>

      {/* ─── 3단계: 데이터 소스 선택 (카드) ─── */}
      <div className="space-y-2">
        <p className="text-sm font-medium">데이터는 어디서 가져오나요?</p>
        <div className="grid grid-cols-3 gap-2">
          {DATA_SOURCE_CARDS.map((card) => {
            const Icon = card.icon;
            const isSelected = dataSource === card.value;
            return (
              <button
                key={card.value}
                type="button"
                onClick={() => updateConfig("dataSource", 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>

      {/* ─── DB 소스 설정 ─── */}
      {dataSource === "db" && (
        <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>
            <p className="mb-1.5 text-xs text-muted-foreground">데이터 테이블</p>
            {loadingTables ? (
              <div className="flex items-center gap-2 text-xs text-muted-foreground">
                <Loader2 className="h-3 w-3 animate-spin" />
                테이블 로딩 중...
              </div>
            ) : (
              <Select
                value={config.tableName || ""}
                onValueChange={(value) => {
                  updateConfig("tableName", value);
                  updateConfig("idColumn", "");
                  updateConfig("parentIdColumn", "");
                  updateConfig("labelColumn", "");
                }}
              >
                <SelectTrigger className="h-8 text-sm">
                  <SelectValue placeholder="테이블 선택" />
                </SelectTrigger>
                <SelectContent>
                  {tables.map((table) => (
                    <SelectItem key={table.tableName} value={table.tableName}>
                      {table.displayName}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            )}
          </div>

          {config.tableName && (
            <>
              {loadingColumns ? (
                <div className="flex items-center gap-2 text-xs text-muted-foreground">
                  <Loader2 className="h-3 w-3 animate-spin" />
                  컬럼 로딩 중...
                </div>
              ) : (
                <>
                  <div className="space-y-2">
                    <p className="text-xs text-muted-foreground">컬럼 매핑</p>
                    <div className="flex gap-2">
                      <div className="flex-1">
                        <Label className="text-[10px] text-muted-foreground">ID 컬럼</Label>
                        <Select
                          value={config.idColumn || ""}
                          onValueChange={(value) => updateConfig("idColumn", value)}
                        >
                          <SelectTrigger className="h-7 text-xs">
                            <SelectValue placeholder="선택" />
                          </SelectTrigger>
                          <SelectContent>
                            {columns.map((col) => (
                              <SelectItem key={col.columnName} value={col.columnName}>
                                {col.displayName}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      </div>
                      <div className="flex-1">
                        <Label className="text-[10px] text-muted-foreground">부모 ID 컬럼</Label>
                        <Select
                          value={config.parentIdColumn || ""}
                          onValueChange={(value) => updateConfig("parentIdColumn", value)}
                        >
                          <SelectTrigger className="h-7 text-xs">
                            <SelectValue placeholder="선택" />
                          </SelectTrigger>
                          <SelectContent>
                            {columns.map((col) => (
                              <SelectItem key={col.columnName} value={col.columnName}>
                                {col.displayName}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      </div>
                    </div>
                  </div>

                  <div>
                    <p className="mb-1.5 text-xs text-muted-foreground">표시 컬럼</p>
                    <Select
                      value={config.labelColumn || ""}
                      onValueChange={(value) => updateConfig("labelColumn", value)}
                    >
                      <SelectTrigger className="h-8 text-sm">
                        <SelectValue placeholder="표시할 컬럼 선택" />
                      </SelectTrigger>
                      <SelectContent>
                        {columns.map((col) => (
                          <SelectItem key={col.columnName} value={col.columnName}>
                            {col.displayName}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>
                </>
              )}
            </>
          )}
        </div>
      )}

      {/* ─── API 소스 설정 ─── */}
      {dataSource === "api" && (
        <div className="rounded-lg border bg-muted/30 p-4 space-y-3">
          <div className="flex items-center gap-2">
            <Globe className="h-4 w-4 text-primary" />
            <span className="text-sm font-medium">API 설정</span>
          </div>
          <div>
            <p className="mb-1.5 text-xs text-muted-foreground">엔드포인트 URL</p>
            <Input
              value={config.apiEndpoint || ""}
              onChange={(e) => updateConfig("apiEndpoint", e.target.value)}
              placeholder="/api/hierarchy"
              className="h-8 text-sm"
            />
          </div>
        </div>
      )}

      {/* ─── BOM 전용 설정 ─── */}
      {hierarchyType === "bom" && (
        <div className="rounded-lg border bg-muted/30 p-4 space-y-3">
          <div className="flex items-center gap-2">
            <Layers className="h-4 w-4 text-primary" />
            <span className="text-sm font-medium">BOM 설정</span>
          </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.showQuantity !== false}
              onCheckedChange={(checked) => updateConfig("showQuantity", checked)}
            />
          </div>

          <div className="flex items-center justify-between py-1">
            <span className="text-xs text-muted-foreground">수량 컬럼</span>
            <Select
              value={config.quantityColumn || ""}
              onValueChange={(value) => updateConfig("quantityColumn", value)}
              disabled={loadingColumns || !config.tableName}
            >
              <SelectTrigger className="h-7 w-[160px] text-xs">
                <SelectValue placeholder="선택" />
              </SelectTrigger>
              <SelectContent>
                {columns.map((col) => (
                  <SelectItem key={col.columnName} value={col.columnName}>
                    {col.displayName}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
        </div>
      )}

      {/* ─── Cascading 전용 설정 ─── */}
      {hierarchyType === "cascading" && (
        <div className="rounded-lg border bg-muted/30 p-4 space-y-3">
          <div className="flex items-center gap-2">
            <ListTree className="h-4 w-4 text-primary" />
            <span className="text-sm font-medium">연쇄 선택 설정</span>
          </div>

          <div className="flex items-center justify-between py-1">
            <span className="text-xs text-muted-foreground">부모 필드</span>
            <Select
              value={config.parentField || ""}
              onValueChange={(value) => updateConfig("parentField", value)}
              disabled={loadingColumns || !config.tableName}
            >
              <SelectTrigger className="h-7 w-[160px] text-xs">
                <SelectValue placeholder="선택" />
              </SelectTrigger>
              <SelectContent>
                {columns.map((col) => (
                  <SelectItem key={col.columnName} value={col.columnName}>
                    {col.displayName}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </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.clearOnParentChange !== false}
              onCheckedChange={(checked) => updateConfig("clearOnParentChange", checked)}
            />
          </div>
        </div>
      )}

      {/* ─── 고급 설정 (Collapsible) ─── */}
      <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 className="flex items-center justify-between py-1">
              <span className="text-xs text-muted-foreground">최대 레벨</span>
              <Input
                type="number"
                value={config.maxLevel || ""}
                onChange={(e) => updateConfig("maxLevel", e.target.value ? Number(e.target.value) : undefined)}
                placeholder="제한 없음"
                min="1"
                className="h-7 w-[120px] text-xs"
              />
            </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.draggable || false}
                onCheckedChange={(checked) => updateConfig("draggable", 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.selectable !== false}
                onCheckedChange={(checked) => updateConfig("selectable", 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.multiSelect || false}
                onCheckedChange={(checked) => updateConfig("multiSelect", 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.showCheckbox || false}
                onCheckedChange={(checked) => updateConfig("showCheckbox", 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.expandAll || false}
                onCheckedChange={(checked) => updateConfig("expandAll", checked)}
              />
            </div>
          </div>
        </CollapsibleContent>
      </Collapsible>
    </div>
  );
};

V2HierarchyConfigPanel.displayName = "V2HierarchyConfigPanel";

export default V2HierarchyConfigPanel;
