'use client';

import { memo, useState } from 'react';
import { ChevronRight, ChevronDown } from 'lucide-react';
import type { ComponentEntry } from './actions';

const TIER_CONFIG: Record<string, { label: string; color: string; bg: string; border: string }> = {
  ui: { label: 'UI', color: 'text-blue-700', bg: 'bg-blue-50', border: 'border-blue-200' },
  atoms: { label: 'Atoms', color: 'text-green-700', bg: 'bg-green-50', border: 'border-green-200' },
  molecules: { label: 'Molecules', color: 'text-purple-700', bg: 'bg-purple-50', border: 'border-purple-200' },
  organisms: { label: 'Organisms', color: 'text-orange-700', bg: 'bg-orange-50', border: 'border-orange-200' },
  common: { label: 'Common', color: 'text-teal-700', bg: 'bg-teal-50', border: 'border-teal-200' },
  layout: { label: 'Layout', color: 'text-indigo-700', bg: 'bg-indigo-50', border: 'border-indigo-200' },
  dev: { label: 'Dev', color: 'text-yellow-700', bg: 'bg-yellow-50', border: 'border-yellow-200' },
  domain: { label: 'Domain', color: 'text-gray-700', bg: 'bg-gray-50', border: 'border-gray-200' },
};

interface RelationshipTreeNodeProps {
  component: ComponentEntry;
  allComponents: Map<string, ComponentEntry>;
  direction: 'up' | 'down'; // up=usedBy, down=imports
  depth: number;
  maxDepth: number;
  visitedPaths: Set<string>;
  onSelectComponent: (filePath: string) => void;
}

export const RelationshipTreeNode = memo(function RelationshipTreeNode({
  component,
  allComponents,
  direction,
  depth,
  maxDepth,
  visitedPaths,
  onSelectComponent,
}: RelationshipTreeNodeProps) {
  const childPaths = direction === 'up' ? component.usedBy : component.imports;
  const children = childPaths
    .map((fp) => allComponents.get(fp))
    .filter((c): c is ComponentEntry => c !== undefined);
  const hasChildren = children.length > 0;

  const [expanded, setExpanded] = useState(depth < 2);

  const isCircular = visitedPaths.has(component.filePath);
  const isMaxDepth = depth >= maxDepth;

  const tierConfig = TIER_CONFIG[component.tier] || TIER_CONFIG.domain;
  const paddingLeft = depth * 24;

  return (
    <>
      <div
        className="group flex items-center py-1.5 hover:bg-gray-50 dark:hover:bg-gray-800 rounded transition-colors cursor-pointer"
        style={{ paddingLeft: `${paddingLeft + 8}px` }}
        onClick={() => onSelectComponent(component.filePath)}
      >
        {/* 펼침/접힘 */}
        <button
          className={`h-5 w-5 flex items-center justify-center shrink-0 ${
            !hasChildren || isCircular || isMaxDepth ? 'invisible' : ''
          }`}
          onClick={(e) => {
            e.stopPropagation();
            setExpanded(!expanded);
          }}
        >
          {expanded ? (
            <ChevronDown className="h-3.5 w-3.5 text-gray-400" />
          ) : (
            <ChevronRight className="h-3.5 w-3.5 text-gray-400" />
          )}
        </button>

        {/* 컴포넌트 정보 */}
        <span className="text-sm font-medium text-gray-800 dark:text-gray-200 ml-1">
          {component.name}
        </span>
        <span className={`text-[10px] px-1 py-0.5 rounded ml-1.5 ${tierConfig.bg} ${tierConfig.color} ${tierConfig.border} border`}>
          {tierConfig.label}
        </span>

        {isCircular && (
          <span className="text-[10px] text-amber-600 ml-1.5">(순환)</span>
        )}
      </div>

      {/* 자식 노드 (재귀) */}
      {hasChildren && expanded && !isCircular && !isMaxDepth && (
        <>
          {children.map((child) => {
            const nextVisited = new Set(visitedPaths);
            nextVisited.add(component.filePath);
            return (
              <RelationshipTreeNode
                key={child.filePath}
                component={child}
                allComponents={allComponents}
                direction={direction}
                depth={depth + 1}
                maxDepth={maxDepth}
                visitedPaths={nextVisited}
                onSelectComponent={onSelectComponent}
              />
            );
          })}
        </>
      )}
    </>
  );
});
