"use client";

/**
 * V2Hierarchy 설정 패널
 * 통합 계층 컴포넌트의 세부 설정을 관리합니다.
 */

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 { Separator } from "@/components/ui/separator";
import { Checkbox } from "@/components/ui/checkbox";
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;
}

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 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]);

  return (
    <div className="space-y-4">
      {/* 계층 타입 */}
      <div className="space-y-2">
        <Label className="text-xs font-medium">계층 타입</Label>
        <Select
          value={config.hierarchyType || config.type || "tree"}
          onValueChange={(value) => updateConfig("hierarchyType", value)}
        >
          <SelectTrigger className="h-8 text-xs">
            <SelectValue placeholder="타입 선택" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="tree">트리</SelectItem>
            <SelectItem value="org-chart">조직도</SelectItem>
            <SelectItem value="bom">BOM (Bill of Materials)</SelectItem>
            <SelectItem value="cascading">연쇄 선택박스</SelectItem>
          </SelectContent>
        </Select>
      </div>

      <Separator />

      {/* 뷰 모드 */}
      <div className="space-y-2">
        <Label className="text-xs font-medium">표시 방식</Label>
        <Select
          value={config.viewMode || "tree"}
          onValueChange={(value) => updateConfig("viewMode", value)}
        >
          <SelectTrigger className="h-8 text-xs">
            <SelectValue placeholder="방식 선택" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="tree">트리뷰</SelectItem>
            <SelectItem value="table">테이블</SelectItem>
            <SelectItem value="chart">차트</SelectItem>
            <SelectItem value="cascading">연쇄 드롭다운</SelectItem>
          </SelectContent>
        </Select>
      </div>

      <Separator />

      {/* 데이터 소스 */}
      <div className="space-y-2">
        <Label className="text-xs font-medium">데이터 소스</Label>
        <Select
          value={config.dataSource || "static"}
          onValueChange={(value) => updateConfig("dataSource", value)}
        >
          <SelectTrigger className="h-8 text-xs">
            <SelectValue placeholder="소스 선택" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="static">정적 데이터</SelectItem>
            <SelectItem value="db">데이터베이스</SelectItem>
            <SelectItem value="api">API</SelectItem>
          </SelectContent>
        </Select>
      </div>

      {/* DB 설정 */}
      {config.dataSource === "db" && (
        <div className="space-y-3">
          {/* 테이블 선택 */}
          <div className="space-y-2">
            <Label className="text-[10px] text-muted-foreground">테이블</Label>
            <Select
              value={config.tableName || ""}
              onValueChange={(value) => {
                updateConfig("tableName", value);
                // 테이블 변경 시 컬럼 초기화
                updateConfig("idColumn", "");
                updateConfig("parentIdColumn", "");
                updateConfig("labelColumn", "");
              }}
              disabled={loadingTables}
            >
              <SelectTrigger className="h-8 text-xs">
                <SelectValue placeholder={loadingTables ? "로딩 중..." : "테이블 선택"} />
              </SelectTrigger>
              <SelectContent>
                {tables.map((table) => (
                  <SelectItem key={table.tableName} value={table.tableName}>
                    {table.displayName}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          
          {/* 컬럼 선택 */}
          {config.tableName && (
            <>
              <div className="grid grid-cols-2 gap-2">
                <div className="space-y-2">
                  <Label className="text-[10px] text-muted-foreground">ID 컬럼</Label>
                  <Select
                    value={config.idColumn || ""}
                    onValueChange={(value) => updateConfig("idColumn", value)}
                    disabled={loadingColumns}
                  >
                    <SelectTrigger className="h-8 text-xs">
                      <SelectValue placeholder={loadingColumns ? "로딩 중..." : "선택"} />
                    </SelectTrigger>
                    <SelectContent>
                      {columns.map((col) => (
                        <SelectItem key={col.columnName} value={col.columnName}>
                          {col.displayName}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
                <div className="space-y-2">
                  <Label className="text-[10px] text-muted-foreground">부모 ID 컬럼</Label>
                  <Select
                    value={config.parentIdColumn || ""}
                    onValueChange={(value) => updateConfig("parentIdColumn", value)}
                    disabled={loadingColumns}
                  >
                    <SelectTrigger className="h-8 text-xs">
                      <SelectValue placeholder={loadingColumns ? "로딩 중..." : "선택"} />
                    </SelectTrigger>
                    <SelectContent>
                      {columns.map((col) => (
                        <SelectItem key={col.columnName} value={col.columnName}>
                          {col.displayName}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
              </div>
              <div className="space-y-2">
                <Label className="text-[10px] text-muted-foreground">표시 컬럼</Label>
                <Select
                  value={config.labelColumn || ""}
                  onValueChange={(value) => updateConfig("labelColumn", value)}
                  disabled={loadingColumns}
                >
                  <SelectTrigger className="h-8 text-xs">
                    <SelectValue placeholder={loadingColumns ? "로딩 중..." : "선택"} />
                  </SelectTrigger>
                  <SelectContent>
                    {columns.map((col) => (
                      <SelectItem key={col.columnName} value={col.columnName}>
                        {col.displayName}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </>
          )}
        </div>
      )}

      {/* API 설정 */}
      {config.dataSource === "api" && (
        <div className="space-y-2">
          <Label className="text-[10px] text-muted-foreground">API 엔드포인트</Label>
          <Input
            value={config.apiEndpoint || ""}
            onChange={(e) => updateConfig("apiEndpoint", e.target.value)}
            placeholder="/api/hierarchy"
            className="h-8 text-xs"
          />
        </div>
      )}

      <Separator />

      {/* 옵션 */}
      <div className="space-y-3">
        <Label className="text-xs font-medium">옵션</Label>
        
        <div className="space-y-2">
          <Label className="text-[10px] text-muted-foreground">최대 레벨</Label>
          <Input
            type="number"
            value={config.maxLevel || ""}
            onChange={(e) => updateConfig("maxLevel", e.target.value ? Number(e.target.value) : undefined)}
            placeholder="제한 없음"
            min="1"
            className="h-8 text-xs"
          />
        </div>

        <div className="flex items-center space-x-2">
          <Checkbox
            id="draggable"
            checked={config.draggable || false}
            onCheckedChange={(checked) => updateConfig("draggable", checked)}
          />
          <label htmlFor="draggable" className="text-xs">드래그 앤 드롭</label>
        </div>

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

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

        <div className="flex items-center space-x-2">
          <Checkbox
            id="showCheckbox"
            checked={config.showCheckbox || false}
            onCheckedChange={(checked) => updateConfig("showCheckbox", checked)}
          />
          <label htmlFor="showCheckbox" className="text-xs">체크박스 표시</label>
        </div>

        <div className="flex items-center space-x-2">
          <Checkbox
            id="expandAll"
            checked={config.expandAll || false}
            onCheckedChange={(checked) => updateConfig("expandAll", checked)}
          />
          <label htmlFor="expandAll" className="text-xs">기본 전체 펼침</label>
        </div>
      </div>

      {/* BOM 전용 설정 */}
      {config.hierarchyType === "bom" && (
        <>
          <Separator />
          <div className="space-y-3">
            <Label className="text-xs font-medium">BOM 설정</Label>
            
            <div className="flex items-center space-x-2">
              <Checkbox
                id="showQuantity"
                checked={config.showQuantity !== false}
                onCheckedChange={(checked) => updateConfig("showQuantity", checked)}
              />
              <label htmlFor="showQuantity" className="text-xs">수량 표시</label>
            </div>

            <div className="space-y-2">
              <Label className="text-[10px] text-muted-foreground">수량 컬럼</Label>
              <Select
                value={config.quantityColumn || ""}
                onValueChange={(value) => updateConfig("quantityColumn", value)}
                disabled={loadingColumns || !config.tableName}
              >
                <SelectTrigger className="h-8 text-xs">
                  <SelectValue placeholder="선택" />
                </SelectTrigger>
                <SelectContent>
                  {columns.map((col) => (
                    <SelectItem key={col.columnName} value={col.columnName}>
                      {col.displayName}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>
        </>
      )}

      {/* 연쇄 선택박스 전용 설정 */}
      {config.hierarchyType === "cascading" && (
        <>
          <Separator />
          <div className="space-y-3">
            <Label className="text-xs font-medium">연쇄 설정</Label>
            
            <div className="space-y-2">
              <Label className="text-[10px] text-muted-foreground">부모 필드</Label>
              <Select
                value={config.parentField || ""}
                onValueChange={(value) => updateConfig("parentField", value)}
                disabled={loadingColumns || !config.tableName}
              >
                <SelectTrigger className="h-8 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 space-x-2">
              <Checkbox
                id="clearOnParentChange"
                checked={config.clearOnParentChange !== false}
                onCheckedChange={(checked) => updateConfig("clearOnParentChange", checked)}
              />
              <label htmlFor="clearOnParentChange" className="text-xs">부모 변경 시 값 초기화</label>
            </div>
          </div>
        </>
      )}
    </div>
  );
};

V2HierarchyConfigPanel.displayName = "V2HierarchyConfigPanel";

export default V2HierarchyConfigPanel;
