"use client";

/**
 * V2 카테고리 관리 컴포넌트
 * - 트리 구조 기반 카테고리 값 관리
 * - 3단계 계층 구조 지원 (대분류/중분류/소분류)
 */

import React, { useState, useCallback, useEffect } from "react";
import { CategoryColumnList } from "@/components/table-category/CategoryColumnList";
import { CategoryValueManager } from "@/components/table-category/CategoryValueManager";
import { CategoryValueManagerTree } from "@/components/table-category/CategoryValueManagerTree";
import { LayoutList, TreeDeciduous } from "lucide-react";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { ResponsiveSplitPanel } from "@/components/common/ResponsiveSplitPanel";
import { V2CategoryManagerConfig, defaultV2CategoryManagerConfig, ViewMode } from "./types";

interface V2CategoryManagerComponentProps {
  tableName?: string;
  menuObjid?: number;
  selectedScreen?: { tableName?: string; menuObjid?: number; menuId?: number };
  config?: Partial<V2CategoryManagerConfig>;
  componentConfig?: Partial<V2CategoryManagerConfig>;
  [key: string]: unknown;
}

export function V2CategoryManagerComponent({
  tableName,
  menuObjid,
  selectedScreen,
  config: externalConfig,
  componentConfig,
  ...props
}: V2CategoryManagerComponentProps) {
  // 설정 병합 (componentConfig도 포함)
  const config: V2CategoryManagerConfig = {
    ...defaultV2CategoryManagerConfig,
    ...externalConfig,
    ...componentConfig,
  };

  // tableName 우선순위: props > selectedScreen > componentConfig
  const effectiveTableName = tableName || selectedScreen?.tableName || (componentConfig as any)?.tableName || "";
  
  // menuObjid 우선순위: props > selectedScreen
  const propsMenuObjid = typeof props.menuObjid === "number" ? props.menuObjid : undefined;
  const effectiveMenuObjid = menuObjid || propsMenuObjid || selectedScreen?.menuObjid;

  // 디버그 로그
  useEffect(() => {
    console.log("🔍 V2CategoryManagerComponent props:", {
      tableName,
      menuObjid,
      selectedScreen,
      effectiveTableName,
      effectiveMenuObjid,
      config,
    });
  }, [tableName, menuObjid, selectedScreen, effectiveTableName, effectiveMenuObjid, config]);

  // 선택된 컬럼 상태
  const [selectedColumn, setSelectedColumn] = useState<{
    uniqueKey: string;
    columnName: string;
    columnLabel: string;
    tableName: string;
  } | null>(null);

  // 뷰 모드 상태
  const [viewMode, setViewMode] = useState<ViewMode>(config.viewMode);

  // 컬럼 선택 핸들러
  const handleColumnSelect = useCallback((uniqueKey: string, columnLabel: string, tableName: string) => {
    const columnName = uniqueKey.split(".")[1];
    setSelectedColumn({ uniqueKey, columnName, columnLabel, tableName });
  }, []);

  // 우측 패널 콘텐츠
  const rightContent = (
    <>
      {/* 뷰 모드 토글 */}
      {config.showViewModeToggle && (
        <div className="mb-2 flex items-center justify-end gap-1">
          <span className="text-muted-foreground mr-2 text-xs">보기 방식:</span>
          <div className="flex rounded-md border p-0.5">
            <Button
              variant="ghost"
              size="sm"
              className={cn("h-7 gap-1.5 px-2.5 text-xs", viewMode === "tree" && "bg-accent")}
              onClick={() => setViewMode("tree")}
            >
              <TreeDeciduous className="h-3.5 w-3.5" />
              트리
            </Button>
            <Button
              variant="ghost"
              size="sm"
              className={cn("h-7 gap-1.5 px-2.5 text-xs", viewMode === "list" && "bg-accent")}
              onClick={() => setViewMode("list")}
            >
              <LayoutList className="h-3.5 w-3.5" />
              목록
            </Button>
          </div>
        </div>
      )}

      {/* 카테고리 값 관리 */}
      <div className="min-h-0 flex-1 overflow-y-auto">
        {selectedColumn ? (
          viewMode === "tree" ? (
            <CategoryValueManagerTree
              key={`tree-${selectedColumn.uniqueKey}`}
              tableName={selectedColumn.tableName}
              columnName={selectedColumn.columnName}
              columnLabel={selectedColumn.columnLabel}
            />
          ) : (
            <CategoryValueManager
              key={`list-${selectedColumn.uniqueKey}`}
              tableName={selectedColumn.tableName}
              columnName={selectedColumn.columnName}
              columnLabel={selectedColumn.columnLabel}
              menuObjid={effectiveMenuObjid}
            />
          )
        ) : (
          <div className="bg-card flex h-64 flex-col items-center justify-center rounded-lg border shadow-sm">
            <div className="flex flex-col items-center gap-2 text-center">
              <TreeDeciduous className="text-muted-foreground/30 h-10 w-10" />
              <p className="text-muted-foreground text-sm">
                {config.showColumnList ? "좌측에서 관리할 카테고리 컬럼을 선택하세요" : "카테고리 컬럼이 설정되지 않았습니다"}
              </p>
            </div>
          </div>
        )}
      </div>
    </>
  );

  if (!config.showColumnList) {
    return (
      <div className="flex h-full flex-col overflow-hidden" style={{ height: config.height }}>
        {rightContent}
      </div>
    );
  }

  return (
    <ResponsiveSplitPanel
      left={
        <CategoryColumnList
          tableName={effectiveTableName}
          selectedColumn={selectedColumn?.uniqueKey || null}
          onColumnSelect={handleColumnSelect}
          menuObjid={effectiveMenuObjid}
        />
      }
      right={rightContent}
      leftTitle="카테고리 컬럼"
      leftWidth={config.leftPanelWidth}
      minLeftWidth={10}
      maxLeftWidth={40}
      height={config.height}
    />
  );
}

export default V2CategoryManagerComponent;

