'use client';

/**
 * BOM Tree 시각화 컴포넌트
 *
 * API: GET /api/proxy/items/{id}/bom/tree
 * 3단계 트리: FG(루트) → CAT(카테고리 그룹) → PT(부품)
 * CAT 노드: 카테고리 헤더로 렌더링 (접힘/펼침, count 표시)
 * PT 노드: 품목 행으로 렌더링 (코드, 품목명, 수량, 단위)
 */

import { useState, useEffect, useCallback } from 'react';
import { ChevronDown, ChevronRight, ChevronsUpDown, Loader2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Package } from 'lucide-react';

// BOM 트리 노드 타입
interface BomTreeNode {
  id: number;
  code: string;
  name: string;
  item_type: string;
  specification?: string;
  unit?: string;
  quantity?: number;
  count?: number;       // CAT 노드 — 하위 품목 건수
  depth: number;
  children: BomTreeNode[];
}

// 유형별 뱃지 스타일
const ITEM_TYPE_COLORS: Record<string, string> = {
  FG: 'bg-blue-100 text-blue-800',
  PT: 'bg-green-100 text-green-800',
  RM: 'bg-orange-100 text-orange-800',
  SM: 'bg-purple-100 text-purple-800',
  CS: 'bg-gray-100 text-gray-800',
  BN: 'bg-pink-100 text-pink-800',
  SF: 'bg-cyan-100 text-cyan-800',
};

// 노드별 고유 키 생성 (CAT 노드는 id=0이므로 이름 기반)
function getNodeKey(node: BomTreeNode, index: number): string {
  if (node.item_type === 'CAT') return `cat-${index}-${node.name}`;
  return `item-${node.id}`;
}

// 모든 노드의 키를 재귀적으로 수집
function collectAllKeys(nodes: BomTreeNode[]): Set<string> {
  const keys = new Set<string>();
  function walk(node: BomTreeNode, index: number) {
    keys.add(getNodeKey(node, index));
    node.children?.forEach((child, i) => walk(child, i));
  }
  nodes.forEach((node, i) => walk(node, i));
  return keys;
}

// 카테고리 노드 컴포넌트
function CategoryNode({
  node,
  nodeKey,
  isOpen,
  onToggle,
}: {
  node: BomTreeNode;
  nodeKey: string;
  isOpen: boolean;
  onToggle: (key: string) => void;
}) {
  const hasChildren = node.children && node.children.length > 0;

  return (
    <div>
      {/* 카테고리 헤더 */}
      <div
        className="flex items-center gap-2 py-2 px-3 bg-gray-50 hover:bg-gray-100 cursor-pointer rounded-sm"
        onClick={() => hasChildren && onToggle(nodeKey)}
      >
        {hasChildren && (
          isOpen
            ? <ChevronDown className="h-4 w-4 text-gray-500 shrink-0" />
            : <ChevronRight className="h-4 w-4 text-gray-500 shrink-0" />
        )}
        <span className="text-sm font-semibold text-gray-700">{node.name}</span>
        <Badge variant="outline" className="text-xs">{node.count ?? node.children?.length ?? 0}건</Badge>
      </div>

      {/* 하위 품목 (접힘/펼침) */}
      {isOpen && hasChildren && (
        <div className="border-l-2 border-gray-200 ml-3">
          {node.children.map((child, i) => (
            <ItemNode key={child.id || `child-${i}`} node={child} />
          ))}
        </div>
      )}
    </div>
  );
}

// 품목(PT) 노드 컴포넌트
function ItemNode({ node }: { node: BomTreeNode }) {
  return (
    <div className="py-1.5 px-3 ml-3 hover:bg-gray-50 rounded-sm">
      <div className="flex items-center gap-2">
        {/* 유형 뱃지 */}
        <Badge
          variant="outline"
          className={`text-[10px] px-1.5 py-0 font-medium shrink-0 ${ITEM_TYPE_COLORS[node.item_type] || 'bg-gray-100 text-gray-800'}`}
        >
          {node.item_type}
        </Badge>

        {/* 코드 — PC만 인라인 표시 */}
        <code className="text-xs text-gray-400 shrink-0 max-w-[180px] truncate hidden md:inline">
          {node.code}
        </code>

        {/* 품목명 */}
        <span className="text-sm text-gray-700 flex-1 min-w-0 truncate">{node.name}</span>

        {/* 수량 + 단위 */}
        <span className="text-xs shrink-0 whitespace-nowrap">
          {node.quantity != null && (
            <span className="font-medium text-blue-600">x{node.quantity}</span>
          )}
          {node.unit && (
            <span className="text-muted-foreground ml-0.5">{node.unit}</span>
          )}
        </span>
      </div>
      {/* 코드 2줄 — 모바일만 */}
      <code className="text-[11px] text-gray-400 pl-6 truncate md:hidden block">
        {node.code}
      </code>
    </div>
  );
}

// 범용 노드 렌더러 (CAT 분기)
function BomNodeRenderer({
  node,
  index,
  expandedNodes,
  onToggle,
}: {
  node: BomTreeNode;
  index: number;
  expandedNodes: Set<string>;
  onToggle: (key: string) => void;
}) {
  const nodeKey = getNodeKey(node, index);
  const isCategory = node.item_type === 'CAT';

  if (isCategory) {
    return (
      <CategoryNode
        node={node}
        nodeKey={nodeKey}
        isOpen={expandedNodes.has(nodeKey)}
        onToggle={onToggle}
      />
    );
  }

  return <ItemNode node={node} />;
}

interface BomTreeViewerProps {
  itemId: string;
  itemType: string;
}

export function BomTreeViewer({ itemId, itemType }: BomTreeViewerProps) {
  const [treeData, setTreeData] = useState<BomTreeNode | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [expandedNodes, setExpandedNodes] = useState<Set<string>>(new Set());
  const [allExpanded, setAllExpanded] = useState(true);

  // 트리 데이터 로드
  const loadTree = useCallback(async () => {
    setIsLoading(true);
    setError(null);
    try {
      const response = await fetch(`/api/proxy/items/${itemId}/bom/tree`);
      const result = await response.json();

      if (result.success && result.data) {
        const root = result.data as BomTreeNode;
        setTreeData(root);
        // 기본: 모든 카테고리 펼침
        if (root.children) {
          setExpandedNodes(collectAllKeys(root.children));
        }
      } else {
        setTreeData(null);
      }
    } catch {
      setError('BOM 트리를 불러오는 중 오류가 발생했습니다.');
    } finally {
      setIsLoading(false);
    }
  }, [itemId]);

  useEffect(() => {
    const isBomTarget = ['FG', 'PT', '제품', '부품'].includes(itemType);
    if (isBomTarget) {
      loadTree();
    } else {
      setIsLoading(false);
    }
  }, [loadTree, itemType]);

  // BOM 대상이 아니면 렌더링하지 않음
  if (!['FG', 'PT', '제품', '부품'].includes(itemType)) return null;

  // 로딩
  if (isLoading) {
    return (
      <Card>
        <CardContent className="py-8 flex items-center justify-center text-muted-foreground">
          <Loader2 className="w-4 h-4 mr-2 animate-spin" />
          BOM 트리를 불러오는 중...
        </CardContent>
      </Card>
    );
  }

  // 에러
  if (error) {
    return (
      <Card>
        <CardContent className="py-8 text-center text-muted-foreground">
          {error}
          <Button variant="link" size="sm" onClick={loadTree} className="ml-2">
            다시 시도
          </Button>
        </CardContent>
      </Card>
    );
  }

  // 데이터 없음
  if (!treeData || !treeData.children || treeData.children.length === 0) {
    return (
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Package className="h-5 w-5" />
            부품 구성 (BOM)
          </CardTitle>
        </CardHeader>
        <CardContent>
          <p className="text-sm text-muted-foreground text-center py-4">
            등록된 BOM 정보가 없습니다.
          </p>
        </CardContent>
      </Card>
    );
  }

  const toggleNode = (key: string) => {
    setExpandedNodes((prev) => {
      const next = new Set(prev);
      if (next.has(key)) next.delete(key);
      else next.add(key);
      return next;
    });
  };

  const expandAll = () => { setExpandedNodes(collectAllKeys(treeData.children)); setAllExpanded(true); };
  const collapseAll = () => { setExpandedNodes(new Set()); setAllExpanded(false); };
  const toggleAll = () => { if (allExpanded) collapseAll(); else expandAll(); };

  // 카테고리 그룹 수 & 총 품목 수
  const categories = treeData.children.filter(n => n.item_type === 'CAT');
  const totalItems = categories.reduce((sum, cat) => sum + (cat.count ?? cat.children?.length ?? 0), 0);
  const groupCount = categories.length;

  return (
    <Card>
      <CardHeader>
        {/* PC: 한 줄 레이아웃 */}
        <div className="hidden md:flex md:items-center md:justify-between">
          <CardTitle className="flex items-center gap-2">
            <Package className="h-5 w-5" />
            부품 구성 (BOM)
          </CardTitle>
          <div className="flex items-center gap-2">
            <Badge variant="outline" className="bg-blue-50 text-blue-700">
              총 {totalItems}개 품목 · {groupCount}개 그룹
            </Badge>
            <Button variant="outline" size="sm" onClick={toggleAll} className="h-7 text-xs">
              <ChevronsUpDown className="w-3 h-3 mr-1" />
              {allExpanded ? '전체 접기' : '전체 펼치기'}
            </Button>
          </div>
        </div>
        {/* 모바일: 줄바꿈 레이아웃 */}
        <div className="md:hidden space-y-2">
          <CardTitle className="flex items-center gap-2">
            <Package className="h-5 w-5" />
            부품 구성 (BOM)
          </CardTitle>
          <Badge variant="outline" className="bg-blue-50 text-blue-700 w-fit">
            총 {totalItems}개 품목 · {groupCount}개 그룹
          </Badge>
          <Button variant="outline" size="sm" onClick={toggleAll} className="h-7 text-xs w-fit">
            <ChevronsUpDown className="w-3 h-3 mr-1" />
            {allExpanded ? '전체 접기' : '전체 펼치기'}
          </Button>
        </div>
      </CardHeader>
      <CardContent>
        <div className="space-y-1">
          {treeData.children.map((node, i) => (
            <BomNodeRenderer
              key={getNodeKey(node, i)}
              node={node}
              index={i}
              expandedNodes={expandedNodes}
              onToggle={toggleNode}
            />
          ))}
        </div>
      </CardContent>
    </Card>
  );
}
