"use client";

import React, { useState } from "react";
import { CategoryColumnList } from "@/components/table-category/CategoryColumnList";
import { CategoryValueManager } from "@/components/table-category/CategoryValueManager";
import { ResponsiveSplitPanel } from "@/components/common/ResponsiveSplitPanel";

interface CategoryWidgetProps {
  widgetId?: string;
  tableName?: string; // 현재 화면의 테이블 (옵션 - 형제 메뉴 전체 표시)
  menuObjid?: number; // 현재 메뉴 OBJID (메뉴 스코프) - 필수
  component?: any; // DynamicComponentRenderer에서 전달되는 컴포넌트 정보
  [key: string]: any; // 추가 props 허용
}

/**
 * 카테고리 관리 위젯 (좌우 분할)
 * - 좌측: 형제 메뉴들의 모든 카테고리 타입 컬럼 목록 (메뉴 스코프)
 * - 우측: 선택된 컬럼의 카테고리 값 관리 (메뉴 스코프)
 */
export function CategoryWidget({ widgetId, tableName, menuObjid, component, ...props }: CategoryWidgetProps) {
  // menuObjid가 없으면 경고 로그
  React.useEffect(() => {
    console.log("🔍 CategoryWidget 받은 props:", {
      widgetId,
      tableName,
      menuObjid,
      hasComponent: !!component,
      propsKeys: Object.keys(props),
      propsMenuObjid: props.menuObjid,
      allProps: { widgetId, tableName, menuObjid, ...props },
    });
    
    if (!menuObjid && !props.menuObjid) {
      console.warn("⚠️ CategoryWidget: menuObjid가 전달되지 않았습니다", { 
        component, 
        props,
        allAvailableProps: { widgetId, tableName, menuObjid, ...props }
      });
    } else {
      console.log("✅ CategoryWidget 렌더링", { 
        widgetId, 
        tableName, 
        menuObjid: menuObjid || props.menuObjid 
      });
    }
  }, [menuObjid, widgetId, tableName, component, props]);
  // menuObjid 우선순위: 직접 전달된 값 > props에서 추출한 값
  const effectiveMenuObjid = menuObjid || props.menuObjid;
  
  const [selectedColumn, setSelectedColumn] = useState<{
    uniqueKey: string; // 테이블명.컬럼명 형식
    columnName: string;
    columnLabel: string;
    tableName: string;
  } | null>(null);

  return (
    <ResponsiveSplitPanel
      left={
        <CategoryColumnList
          tableName={tableName ?? ""}
          selectedColumn={selectedColumn?.uniqueKey || null}
          onColumnSelect={(uniqueKey, columnLabel, tblName) => {
            const columnName = uniqueKey.split('.')[1];
            setSelectedColumn({ uniqueKey, columnName, columnLabel, tableName: tblName });
          }}
          menuObjid={effectiveMenuObjid}
        />
      }
      right={
        selectedColumn ? (
          <CategoryValueManager
            key={selectedColumn.uniqueKey}
            tableName={selectedColumn.tableName}
            columnName={selectedColumn.columnName}
            columnLabel={selectedColumn.columnLabel}
            menuObjid={effectiveMenuObjid}
          />
        ) : (
          <div className="flex h-64 flex-col items-center justify-center rounded-lg border bg-card shadow-sm">
            <div className="flex flex-col items-center gap-2 text-center">
              <p className="text-sm text-muted-foreground">
                좌측에서 관리할 카테고리 컬럼을 선택하세요
              </p>
            </div>
          </div>
        )
      }
      leftTitle="카테고리 컬럼"
      leftWidth={15}
      minLeftWidth={10}
      maxLeftWidth={40}
    />
  );
}
