import React, { useState, useEffect } from 'react';
import { WorkflowDag, TaskNode, TaskStatus, TaskType } from '@/types/workflow';
import { TaskOutputViewer } from './TaskOutputViewer';
import { Card } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { ScrollArea } from '@/components/ui/scroll-area';
import { cn } from '@/lib/utils';
import { 
  CheckCircle2, 
  Circle, 
  Clock, 
  AlertCircle, 
  Loader2, 
  SkipForward,
  Database,
  FileText,
  BrainCircuit
} from 'lucide-react';

interface WorkflowVisualizerProps {
  dag: WorkflowDag;
  taskStates: Record<string, TaskStatus>;
  taskOutputs: Record<string, string>;
  className?: string;
}

const TYPE_ORDER: Record<TaskType, number> = {
  'DataFetch': 1,
  'DataProcessing': 2,
  'Analysis': 3
};

const TYPE_ICONS: Record<TaskType, React.ReactNode> = {
  'DataFetch': <Database className="w-4 h-4" />,
  'DataProcessing': <FileText className="w-4 h-4" />,
  'Analysis': <BrainCircuit className="w-4 h-4" />
};

export function WorkflowVisualizer({ 
  dag, 
  taskStates, 
  taskOutputs,
  className 
}: WorkflowVisualizerProps) {
  const [selectedTaskId, setSelectedTaskId] = useState<string | null>(null);

  // Sort nodes by type then name
  const sortedNodes = [...dag.nodes].sort((a, b) => {
    const typeScoreA = TYPE_ORDER[a.type] || 99;
    const typeScoreB = TYPE_ORDER[b.type] || 99;
    if (typeScoreA !== typeScoreB) return typeScoreA - typeScoreB;
    return a.name.localeCompare(b.name);
  });

  // Auto-select first node or running node if none selected
  useEffect(() => {
    if (!selectedTaskId && sortedNodes.length > 0) {
      // Try to find a running node, or the first one
      const runningNode = sortedNodes.find(n => taskStates[n.id] === 'Running');
      setSelectedTaskId(runningNode ? runningNode.id : sortedNodes[0].id);
    }
  }, [dag, taskStates, selectedTaskId, sortedNodes]);

  const selectedNode = dag.nodes.find(n => n.id === selectedTaskId);

  return (
    <div className={cn("flex h-[600px] border rounded-lg overflow-hidden bg-background", className)}>
      {/* Left Sidebar: Task List */}
      <div className="w-1/3 min-w-[250px] border-r bg-muted/10 flex flex-col">
        <div className="p-4 border-b bg-muted/20">
          <h3 className="font-semibold text-sm text-foreground">Workflow Tasks</h3>
          <p className="text-xs text-muted-foreground mt-1">
            {dag.nodes.length} steps in pipeline
          </p>
        </div>
        <ScrollArea className="flex-1">
          <div className="p-2 space-y-1">
            {sortedNodes.map(node => (
              <TaskListItem
                key={node.id}
                node={node}
                status={taskStates[node.id] || node.initial_status}
                isSelected={selectedTaskId === node.id}
                onClick={() => setSelectedTaskId(node.id)}
              />
            ))}
          </div>
        </ScrollArea>
      </div>

      {/* Right Content: Output Viewer */}
      <div className="flex-1 min-w-0 bg-card">
        {selectedNode ? (
          <TaskOutputViewer
            taskId={selectedNode.id}
            taskName={selectedNode.name}
            taskType={selectedNode.type}
            status={taskStates[selectedNode.id] || selectedNode.initial_status}
            content={taskOutputs[selectedNode.id] || ''}
          />
        ) : (
          <div className="h-full flex items-center justify-center text-muted-foreground">
            Select a task to view details
          </div>
        )}
      </div>
    </div>
  );
}

function TaskListItem({ 
  node, 
  status, 
  isSelected, 
  onClick 
}: { 
  node: TaskNode; 
  status: TaskStatus; 
  isSelected: boolean; 
  onClick: () => void;
}) {
  return (
    <button
      onClick={onClick}
      className={cn(
        "w-full flex items-center gap-3 p-3 text-sm text-left rounded-md transition-colors",
        "hover:bg-accent hover:text-accent-foreground",
        isSelected ? "bg-accent text-accent-foreground shadow-sm" : "text-muted-foreground"
      )}
    >
      <StatusIcon status={status} />
      <div className="flex-1 min-w-0">
        <div className="font-medium truncate">{node.name}</div>
        <div className="flex items-center gap-1 text-xs opacity-70 mt-0.5">
          {TYPE_ICONS[node.type]}
          <span>{node.type}</span>
        </div>
      </div>
    </button>
  );
}

function StatusIcon({ status }: { status: TaskStatus }) {
  switch (status) {
    case 'Completed':
      return <CheckCircle2 className="w-4 h-4 text-green-500" />;
    case 'Failed':
      return <AlertCircle className="w-4 h-4 text-red-500" />;
    case 'Running':
      return <Loader2 className="w-4 h-4 text-blue-500 animate-spin" />;
    case 'Scheduled':
      return <Clock className="w-4 h-4 text-yellow-500" />;
    case 'Skipped':
      return <SkipForward className="w-4 h-4 text-gray-400" />;
    default: // Pending
      return <Circle className="w-4 h-4 text-gray-300" />;
  }
}

