import { useState } from 'react';
import { cn } from '../../lib/utils';
import { ChevronRight, ChevronDown } from 'lucide-react';

interface NodeProps {
  node: any;
  onSelect: (node: any) => void;
  selectedId: string | number | null;
  level: number;
}

function HorizontalTreeNode({ node, onSelect, selectedId, level }: NodeProps) {
  const [expanded, setExpanded] = useState(true); // Default to fully expanded
  const hasChildren = node.children && node.children.length > 0;

  // Determine colors based on level (mimicking horizontal flowchart reference image)
  let bgColor = "bg-white";
  let borderColor = "border-slate-200";
  let textColor = "text-slate-700";
  
  if (level === 2) {
    bgColor = "bg-emerald-100"; borderColor = "border-emerald-300"; textColor = "text-emerald-800";
  } else if (level >= 3) {
    bgColor = "bg-blue-100"; borderColor = "border-blue-300"; textColor = "text-blue-800";
  }

  return (
    <div className="flex flex-row items-start">
      {/* Node Card */}
      <div 
        className={cn(
          "flex items-center px-3 py-1.5 rounded-md border shadow-[0_1px_2px_rgba(0,0,0,0.05)] cursor-pointer whitespace-nowrap transition-colors z-10 h-[34px]",
          bgColor, borderColor,
          selectedId === node.id ? "ring-2 ring-indigo-500 ring-offset-1 border-indigo-400" : "hover:brightness-95"
        )}
        onClick={() => onSelect(node)}
      >
        <span className={cn("text-xs font-bold mr-3", textColor)}>{node.name || "Root"}</span>
        {node.id && <span className="text-[10px] opacity-60 mr-2 font-mono">{node.id}</span>}
        
        {/* Count Pill */}
        <div className="flex text-[9px] bg-white/70 rounded px-1 group shadow-sm items-center">
          <span className="px-1 text-slate-500 font-medium">{node.total_element_count || 0}</span>
          <span className="px-1 font-bold text-slate-800 border-l border-white/50 pl-1">{node.total_posts_count || 0} ▶</span>
        </div>

        {hasChildren && (
          <button 
            className="ml-2 px-1 text-slate-400 hover:text-slate-700 focus:outline-none transition-transform" 
            onClick={(e) => { e.stopPropagation(); setExpanded(!expanded); }}
          >
            {expanded ? <ChevronDown size={14} className="opacity-70"/> : <ChevronRight size={14} className="opacity-70"/>}
          </button>
        )}
      </div>

      {/* Children Container (Horizontal Layout Connections) */}
      {expanded && hasChildren && (
        <div className="flex flex-col relative ml-8">
           {/* Horizontal line from parent node to intersection (17px is half of 34px height) */}
           <div className="absolute -left-8 top-[17px] w-8 h-px bg-slate-300"></div>
           
           {node.children.map((child: any, i: number) => (
             <div 
               key={child.id || child.path || i}
               className={cn(
                 "relative pl-8 pb-3 flex items-start",
                 // Horizontal line to this child box from vertical intersection
                 "before:absolute before:left-0 before:top-[17px] before:w-8 before:h-px before:bg-slate-300",
                 // Vertical connection line
                 "after:absolute after:left-0 after:w-px after:bg-slate-300",
                 // Adjust vertical line start/end based on position to avoid overhanging lines
                 "first:after:top-[17px] first:after:bottom-0",
                 "last:after:top-0 last:after:bottom-[calc(100%-17px)]",
                 "[&:not(:first-child):not(:last-child)]:after:top-0 [&:not(:first-child):not(:last-child)]:after:bottom-0",
                 // If it's the ONLY child, hide vertical line completely
                 "first:last:after:hidden"
               )}
             >
                <HorizontalTreeNode node={child} onSelect={onSelect} selectedId={selectedId} level={level + 1} />
             </div>
           ))}
        </div>
      )}
    </div>
  );
}

export function CategoryTree({ data, onSelect, selectedId }: { data: any, onSelect: (node: any) => void, selectedId: any }) {
  if (!data || !data.children) return (
    <div className="bg-white rounded-3xl border border-slate-100 shadow-sm p-6 flex flex-col items-center justify-center min-h-[400px] text-slate-400">
      <div className="w-8 h-8 border-4 border-indigo-200 border-t-indigo-600 rounded-full animate-spin mb-4"></div>
      加载树形结构中... (请确保已重跑 python server.py)
    </div>
  );


  
  return (
    <div className="bg-white rounded-3xl border border-slate-100 shadow-sm p-0 overflow-hidden flex flex-col min-h-[400px]">
       <div className="overflow-x-auto overflow-y-auto max-h-[800px] w-full p-4 custom-scrollbar">
         <div className="flex flex-col gap-8 select-none min-w-max pb-8">
            {(() => {
               // The exact order the user requested:
               const orderKeyWords = ["形式", "实质", "意图"];
               
               // Group the children nodes by their source_type
               const groups: Record<string, any[]> = {
                 "形式": [],
                 "实质": [],
                 "意图": []
               };

               data.children.forEach((node: any) => {
                 const type = node.source_type;
                 if (type && groups[type]) {
                   groups[type].push(node);
                 } else if (type === "形式" || type === "实质" || type === "意图") {
                   groups[type] = [node];
                 }
               });

               return orderKeyWords.map((dimensionName: string) => {
                 const nodesInDimension = groups[dimensionName] || [];
                 if (nodesInDimension.length === 0) return null;

                 // Assign fixed colors complementing their semantic dimension
                 let color = { bg: 'bg-slate-50', border: 'border-slate-500', text: 'text-slate-800' };
                 if (dimensionName === "形式") {
                   color = { bg: 'bg-[#E3F2FD]', border: 'border-[#2196F3]', text: 'text-slate-800' };
                 } else if (dimensionName === "实质") {
                   color = { bg: 'bg-[#FFF3E0]', border: 'border-[#FF9800]', text: 'text-slate-800' };
                 } else if (dimensionName === "意图") {
                   color = { bg: 'bg-[#F1F8E9]', border: 'border-[#8BC34A]', text: 'text-slate-800' };
                 }

                 return (
                   <div key={dimensionName} className="flex flex-col">
                     {/* Category Header */}
                     <div className={cn("px-4 py-3 border-l-[6px] text-sm font-bold w-full mb-4", color.bg, color.border, color.text)}>
                       {dimensionName} 维度
                     </div>
                     
                     {/* Children Nodes Stacked Vertically, without parent link */}
                     <div className="flex flex-col gap-6 pl-4">
                       {nodesInDimension.map((subNode: any, subIdx: number) => (
                         <HorizontalTreeNode 
                           key={subNode.id || subIdx} 
                           node={subNode} 
                           onSelect={onSelect} 
                           selectedId={selectedId} 
                           level={1} 
                         />
                       ))}
                     </div>
                   </div>
                 )
               });
            })()}
         </div>
       </div>
    </div>
  );
}
