"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 { 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-1">
      {/* HIERARCHY TYPE 섹션 */}
      <div className="border-b border-border/50 pb-3 mb-3">
        <h4 className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground py-2">HIERARCHY TYPE</h4>
        <div className="flex items-center justify-between py-1.5">
          <span className="text-xs text-muted-foreground">계층 타입</span>
          <div className="w-[140px]">
            <Select
              value={config.hierarchyType || config.type || "tree"}
              onValueChange={(value) => updateConfig("hierarchyType", value)}
            >
              <SelectTrigger className="h-7 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>
        </div>
      </div>

      {/* VIEW MODE 섹션 */}
      <div className="border-b border-border/50 pb-3 mb-3">
        <h4 className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground py-2">VIEW MODE</h4>
        <div className="flex items-center justify-between py-1.5">
          <span className="text-xs text-muted-foreground">표시 방식</span>
          <div className="w-[140px]">
            <Select
              value={config.viewMode || "tree"}
              onValueChange={(value) => updateConfig("viewMode", value)}
            >
              <SelectTrigger className="h-7 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>
        </div>
      </div>

      {/* DATA SOURCE 섹션 */}
      <div className="border-b border-border/50 pb-3 mb-3">
        <h4 className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground py-2">DATA SOURCE</h4>
        <div className="flex items-center justify-between py-1.5">
          <span className="text-xs text-muted-foreground">데이터 소스</span>
          <div className="w-[140px]">
            <Select
              value={config.dataSource || "static"}
              onValueChange={(value) => updateConfig("dataSource", value)}
            >
              <SelectTrigger className="h-7 text-xs">
                <SelectValue placeholder="소스 선택" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="static">정적 데이터</SelectItem>
                <SelectItem value="db">데이터베이스</SelectItem>
                <SelectItem value="api">API</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </div>

        {/* DB 설정 */}
        {config.dataSource === "db" && (
          <>
            <div className="flex items-center justify-between py-1.5">
              <span className="text-xs text-muted-foreground">테이블</span>
              <div className="w-[140px]">
                <Select
                  value={config.tableName || ""}
                  onValueChange={(value) => {
                    updateConfig("tableName", value);
                    updateConfig("idColumn", "");
                    updateConfig("parentIdColumn", "");
                    updateConfig("labelColumn", "");
                  }}
                  disabled={loadingTables}
                >
                  <SelectTrigger className="h-7 text-xs">
                    <SelectValue placeholder={loadingTables ? "로딩 중..." : "테이블 선택"} />
                  </SelectTrigger>
                  <SelectContent>
                    {tables.map((table) => (
                      <SelectItem key={table.tableName} value={table.tableName}>
                        {table.displayName}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </div>

            {config.tableName && (
              <>
                <div className="flex gap-2 py-1.5">
                  <div className="flex-1">
                    <Label className="text-[10px] text-muted-foreground">ID 컬럼</Label>
                    <Select
                      value={config.idColumn || ""}
                      onValueChange={(value) => updateConfig("idColumn", value)}
                      disabled={loadingColumns}
                    >
                      <SelectTrigger className="h-7 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="flex-1">
                    <Label className="text-[10px] text-muted-foreground">부모 ID 컬럼</Label>
                    <Select
                      value={config.parentIdColumn || ""}
                      onValueChange={(value) => updateConfig("parentIdColumn", value)}
                      disabled={loadingColumns}
                    >
                      <SelectTrigger className="h-7 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="flex items-center justify-between py-1.5">
                  <span className="text-xs text-muted-foreground">표시 컬럼</span>
                  <div className="w-[140px]">
                    <Select
                      value={config.labelColumn || ""}
                      onValueChange={(value) => updateConfig("labelColumn", value)}
                      disabled={loadingColumns}
                    >
                      <SelectTrigger className="h-7 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="flex items-center justify-between py-1.5">
            <span className="text-xs text-muted-foreground">API 엔드포인트</span>
            <div className="w-[140px]">
              <Input
                value={config.apiEndpoint || ""}
                onChange={(e) => updateConfig("apiEndpoint", e.target.value)}
                placeholder="/api/hierarchy"
                className="h-7 text-xs"
              />
            </div>
          </div>
        )}
      </div>

      {/* OPTIONS 섹션 */}
      <div className="border-b border-border/50 pb-3 mb-3">
        <h4 className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground py-2">OPTIONS</h4>
        <div className="flex items-center justify-between py-1.5">
          <span className="text-xs text-muted-foreground">최대 레벨</span>
          <div className="w-[140px]">
            <Input
              type="number"
              value={config.maxLevel || ""}
              onChange={(e) => updateConfig("maxLevel", e.target.value ? Number(e.target.value) : undefined)}
              placeholder="제한 없음"
              min="1"
              className="h-7 text-xs"
            />
          </div>
        </div>
        <div className="flex items-center justify-between py-1.5">
          <span className="text-xs text-muted-foreground">드래그 앤 드롭</span>
          <Checkbox
            checked={config.draggable || false}
            onCheckedChange={(checked) => updateConfig("draggable", checked)}
          />
        </div>
        <div className="flex items-center justify-between py-1.5">
          <span className="text-xs text-muted-foreground">선택 가능</span>
          <Checkbox
            checked={config.selectable !== false}
            onCheckedChange={(checked) => updateConfig("selectable", checked)}
          />
        </div>
        <div className="flex items-center justify-between py-1.5">
          <span className="text-xs text-muted-foreground">다중 선택</span>
          <Checkbox
            checked={config.multiSelect || false}
            onCheckedChange={(checked) => updateConfig("multiSelect", checked)}
          />
        </div>
        <div className="flex items-center justify-between py-1.5">
          <span className="text-xs text-muted-foreground">체크박스 표시</span>
          <Checkbox
            checked={config.showCheckbox || false}
            onCheckedChange={(checked) => updateConfig("showCheckbox", checked)}
          />
        </div>
        <div className="flex items-center justify-between py-1.5">
          <span className="text-xs text-muted-foreground">기본 전체 펼침</span>
          <Checkbox
            checked={config.expandAll || false}
            onCheckedChange={(checked) => updateConfig("expandAll", checked)}
          />
        </div>
      </div>

      {/* BOM SETTINGS 섹션 - BOM 타입 전용 */}
      {config.hierarchyType === "bom" && (
        <div className="border-b border-border/50 pb-3 mb-3">
          <h4 className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground py-2">BOM SETTINGS</h4>
          <div className="flex items-center justify-between py-1.5">
            <span className="text-xs text-muted-foreground">수량 표시</span>
            <Checkbox
              checked={config.showQuantity !== false}
              onCheckedChange={(checked) => updateConfig("showQuantity", checked)}
            />
          </div>
          <div className="flex items-center justify-between py-1.5">
            <span className="text-xs text-muted-foreground">수량 컬럼</span>
            <div className="w-[140px]">
              <Select
                value={config.quantityColumn || ""}
                onValueChange={(value) => updateConfig("quantityColumn", value)}
                disabled={loadingColumns || !config.tableName}
              >
                <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>
      )}

      {/* CASCADING SETTINGS 섹션 - 연쇄 선택박스 전용 */}
      {config.hierarchyType === "cascading" && (
        <div className="border-b border-border/50 pb-3 mb-3">
          <h4 className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground py-2">CASCADING SETTINGS</h4>
          <div className="flex items-center justify-between py-1.5">
            <span className="text-xs text-muted-foreground">부모 필드</span>
            <div className="w-[140px]">
              <Select
                value={config.parentField || ""}
                onValueChange={(value) => updateConfig("parentField", value)}
                disabled={loadingColumns || !config.tableName}
              >
                <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 className="flex items-center justify-between py-1.5">
            <span className="text-xs text-muted-foreground">부모 변경 시 초기화</span>
            <Checkbox
              checked={config.clearOnParentChange !== false}
              onCheckedChange={(checked) => updateConfig("clearOnParentChange", checked)}
            />
          </div>
        </div>
      )}
    </div>
  );
};

V2HierarchyConfigPanel.displayName = "V2HierarchyConfigPanel";

export default V2HierarchyConfigPanel;
