"use client";

/**
 * V2 카테고리 관리 컴포넌트
 * - 대시보드 레이아웃: Stat Strip + 좌측 테이블 nav + 칩 바 + 트리/목록 편집기
 * - 3단계 계층 구조 지원 (대분류/중분류/소분류)
 */

import React, { useState, useCallback, useMemo } from "react";
import { CategoryColumnList } from "@/components/table-category/CategoryColumnList";
import type { CategoryColumn } 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 { Badge } from "@/components/ui/badge";
import { cn } from "@/lib/utils";
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) {
  const config: V2CategoryManagerConfig = {
    ...defaultV2CategoryManagerConfig,
    ...externalConfig,
    ...componentConfig,
  };

  const effectiveTableName =
    tableName || selectedScreen?.tableName || (componentConfig as any)?.tableName || "";
  const propsMenuObjid = typeof props.menuObjid === "number" ? props.menuObjid : undefined;
  const effectiveMenuObjid = menuObjid || propsMenuObjid || selectedScreen?.menuObjid;

  const [columns, setColumns] = useState<CategoryColumn[]>([]);
  const [selectedTable, setSelectedTable] = useState<string | null>(null);
  const [selectedColumn, setSelectedColumn] = useState<{
    uniqueKey: string;
    columnName: string;
    columnLabel: string;
    tableName: string;
  } | null>(null);
  const [viewMode, setViewMode] = useState<ViewMode>(config.viewMode);

  const handleColumnsLoaded = useCallback((loaded: CategoryColumn[]) => {
    setColumns(loaded);
    if (loaded.length > 0) {
      setSelectedTable((prev) => prev ?? loaded[0].tableName);
    }
  }, []);

  const handleTableSelect = useCallback((tableName: string) => {
    setSelectedTable(tableName);
    setSelectedColumn(null);
  }, []);

  const handleColumnSelect = useCallback(
    (uniqueKey: string, columnLabel: string, colTableName: string) => {
      const columnName = uniqueKey.includes(".") ? uniqueKey.split(".")[1] : uniqueKey;
      setSelectedColumn({ uniqueKey: uniqueKey.includes(".") ? uniqueKey : `${colTableName}.${uniqueKey}`, columnName, columnLabel, tableName: colTableName });
    },
    [],
  );

  const stats = useMemo(() => {
    const columnCount = columns.length;
    const totalValues = columns.reduce((sum, c) => sum + (c.valueCount ?? 0), 0);
    const tableCount = new Set(columns.map((c) => c.tableName)).size;
    const inactiveCount = 0;
    return { columnCount, totalValues, tableCount, inactiveCount };
  }, [columns]);

  const columnsForSelectedTable = useMemo(
    () => (selectedTable ? columns.filter((c) => c.tableName === selectedTable) : []),
    [columns, selectedTable],
  );

  /** 편집기 헤더에 표시할 트리/목록 세그먼트 (보기 방식 토글) */
  const viewModeSegment =
    config.showViewModeToggle ? (
      <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>
    ) : null;

  const rightContent = (
    <>
      <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}
              headerRight={viewModeSegment}
            />
          ) : (
            <CategoryValueManager
              key={`list-${selectedColumn.uniqueKey}`}
              tableName={selectedColumn.tableName}
              columnName={selectedColumn.columnName}
              columnLabel={selectedColumn.columnLabel}
              menuObjid={effectiveMenuObjid}
              headerRight={viewModeSegment}
            />
          )
        ) : (
          <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 (
    <div
      className="flex h-full flex-col overflow-hidden rounded-lg border bg-card text-card-foreground shadow-sm"
      style={{ height: config.height }}
    >
      {/* Stat Strip: 카테고리 컬럼(primary) | 전체 값(success) | 테이블(primary) | 비활성(warning) */}
      <div className="grid grid-cols-4 border-b bg-background">
        <div className="border-r py-3.5 text-center last:border-r-0">
          <div className="text-[22px] font-extrabold leading-none tracking-tight text-primary">
            {stats.columnCount}
          </div>
          <div className="mt-1 text-[9px] font-semibold uppercase tracking-widest text-muted-foreground">
            카테고리 컬럼
          </div>
        </div>
        <div className="border-r py-3.5 text-center last:border-r-0">
          <div className="text-[22px] font-extrabold leading-none tracking-tight text-success">
            {stats.totalValues}
          </div>
          <div className="mt-1 text-[9px] font-semibold uppercase tracking-widest text-muted-foreground">
            전체 값
          </div>
        </div>
        <div className="border-r py-3.5 text-center last:border-r-0">
          <div className="text-[22px] font-extrabold leading-none tracking-tight text-primary">
            {stats.tableCount}
          </div>
          <div className="mt-1 text-[9px] font-semibold uppercase tracking-widest text-muted-foreground">
            테이블
          </div>
        </div>
        <div className="py-3.5 text-center">
          <div className="text-[22px] font-extrabold leading-none tracking-tight text-warning">
            {stats.inactiveCount}
          </div>
          <div className="mt-1 text-[9px] font-semibold uppercase tracking-widest text-muted-foreground">
            비활성
          </div>
        </div>
      </div>

      <div className="flex min-h-0 flex-1">
        {/* 좌측 테이블 nav: 240px */}
        <div className="flex w-[240px] shrink-0 flex-col border-r">
          <CategoryColumnList
            tableName={effectiveTableName}
            selectedColumn={selectedColumn?.uniqueKey ?? null}
            onColumnSelect={handleColumnSelect}
            menuObjid={effectiveMenuObjid}
            selectedTable={selectedTable}
            onTableSelect={setSelectedTable}
            onColumnsLoaded={handleColumnsLoaded}
          />
        </div>

        {/* 우측: 칩 바 + 편집기 */}
        <div className="flex min-w-0 flex-1 flex-col">
          {/* 칩 바 */}
          <div className="flex flex-wrap gap-1.5 border-b bg-background px-4 py-3">
            {columnsForSelectedTable.map((col) => {
              const uniqueKey = `${col.tableName}.${col.columnName}`;
              const isActive = selectedColumn?.uniqueKey === uniqueKey;
              return (
                <button
                  key={uniqueKey}
                  type="button"
                  onClick={() =>
                    handleColumnSelect(uniqueKey, col.columnLabel || col.columnName, col.tableName)
                  }
                  className={cn(
                    "inline-flex items-center gap-1.5 rounded-full border px-[10px] py-[5px] text-[11px] font-semibold transition-colors",
                    isActive
                      ? "border-primary bg-primary/5 text-primary"
                      : "border-border bg-muted/50 hover:border-primary hover:bg-primary/5 hover:text-primary",
                  )}
                >
                  <span>{col.columnLabel || col.columnName}</span>
                  <Badge
                    variant="secondary"
                    className={cn(
                      "h-4 rounded-full px-1.5 text-[9px] font-bold",
                      isActive ? "bg-primary/15 text-primary" : "bg-muted text-muted-foreground",
                    )}
                  >
                    {col.valueCount ?? 0}
                  </Badge>
                </button>
              );
            })}
            {selectedTable && columnsForSelectedTable.length === 0 && (
              <span className="text-muted-foreground text-xs">이 테이블에 카테고리 컬럼이 없습니다</span>
            )}
          </div>

          {/* 편집기 영역 */}
          <div className="flex min-h-0 flex-1 flex-col overflow-hidden p-3">
            {rightContent}
          </div>
        </div>
      </div>
    </div>
  );
}

export default V2CategoryManagerComponent;
