import React, { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Badge } from "@/components/ui/badge";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import { TaskStatus } from '@/types/workflow';
import { AnalysisModuleConfig } from '@/types/index';
import { BrainCircuit, Terminal, Info } from 'lucide-react';
import { TaskInfo } from '@/hooks/useWorkflow';

interface AnalysisModulesViewProps {
  taskStates: Record<string, TaskStatus>;
  taskInfos: Record<string, TaskInfo>;
  taskOutputs: Record<string, string>;
  modulesConfig: Record<string, AnalysisModuleConfig>;
}

export function AnalysisModulesView({ 
  taskStates, 
  taskInfos,
  taskOutputs,
  modulesConfig 
}: AnalysisModulesViewProps) {
  console.log('[AnalysisModulesView] Render. Config keys:', Object.keys(modulesConfig));
  console.log('[AnalysisModulesView] Task States:', taskStates);

  // Identify analysis tasks based on the template config
  // We assume task IDs in the DAG correspond to module IDs or follow a pattern
  // For now, let's try to match tasks that are NOT fetch tasks
  
  // If we have config, use it to drive tabs
  const moduleIds = Object.keys(modulesConfig);
  
  const [activeModuleId, setActiveModuleId] = useState<string>(moduleIds[0] || '');

  useEffect(() => {
      // If no active module and we have modules, select first
      if (!activeModuleId && moduleIds.length > 0) {
          setActiveModuleId(moduleIds[0]);
      }
  }, [moduleIds, activeModuleId]);

  if (moduleIds.length === 0) {
      return (
          <div className="flex flex-col items-center justify-center h-[300px] border-dashed border-2 rounded-lg text-muted-foreground">
              <BrainCircuit className="w-10 h-10 mb-2 opacity-50" />
              <p>No analysis modules defined in this template.</p>
          </div>
      );
  }

  return (
    <div className="space-y-4">
      <Tabs value={activeModuleId} onValueChange={setActiveModuleId} className="w-full">
        <div className="overflow-x-auto pb-2">
            <TabsList className="w-full justify-start h-auto p-1 bg-transparent gap-2">
              {moduleIds.map(moduleId => {
                const config = modulesConfig[moduleId];
                // Task ID might match module ID directly or be prefixed
                // We need to check multiple patterns because the backend DAG might be simplified (e.g., single "analysis:report" task)
                // or use "analysis:{moduleId}" format.
                let taskId = moduleId;
                let status = taskStates[taskId];

                if (!status) {
                  // Try prefix format
                  taskId = `analysis:${moduleId}`;
                  status = taskStates[taskId];
                }
                
                if (!status) {
                  // Try fallback to generic analysis task if specific one is missing
                  // This handles the case where backend collapses all analysis into one task
                  taskId = 'analysis:report';
                  status = taskStates[taskId];
                }

                // Default to pending if still not found
                status = status || 'Pending';
                
                return (
                  <TabsTrigger 
                    key={moduleId} 
                    value={moduleId}
                    className="data-[state=active]:bg-primary data-[state=active]:text-primary-foreground px-4 py-2 rounded-md border bg-card hover:bg-accent/50 transition-all"
                  >
                    <div className="flex items-center gap-2">
                        <span>{config.name}</span>
                        <StatusDot status={status} />
                    </div>
                  </TabsTrigger>
                );
              })}
            </TabsList>
        </div>

        {moduleIds.map(moduleId => {
            // Resolve task ID and Status using the same logic as tabs
            let taskId = moduleId;
            let status = taskStates[taskId];
            let output = taskOutputs[taskId];
            let info = taskInfos[taskId];

            if (!status) {
                taskId = `analysis:${moduleId}`;
                status = taskStates[taskId];
                output = taskOutputs[taskId];
                info = taskInfos[taskId];
            }
            
            if (!status) {
                // Fallback for status
                const genericId = 'analysis:report';
                status = taskStates[genericId];
                info = taskInfos[genericId];
                // Note: We might not want to show generic output for specific module tab, 
                // but if it's the only output we have, maybe? 
                // Usually 'analysis:report' output might be the full report or a summary.
                // Let's check if we have output for the specific module ID first in taskOutputs
                // regardless of status.
                if (!output) output = taskOutputs[genericId];
            }

            status = status || 'Pending';
            output = output || '';

            const config = modulesConfig[moduleId];

            return (
                <TabsContent key={moduleId} value={moduleId} className="mt-0">
                    <Card className="h-[600px] flex flex-col">
                        <CardHeader className="py-4 border-b bg-muted/5">
                            <div className="flex items-center justify-between">
                                <div className="flex items-center gap-3">
                                    <CardTitle className="text-lg">{config.name}</CardTitle>
                                    <Badge variant="outline" className="font-mono text-xs">
                                        {config.model_id}
                                    </Badge>
                                </div>
                                <StatusBadge status={status} message={info?.message} />
                            </div>
                        </CardHeader>
                        <CardContent className="flex-1 p-0 min-h-0 relative">
                            <ScrollArea className="h-full p-6">
                                {output ? (
                                    <div className="prose dark:prose-invert max-w-none pb-10">
                                        <ReactMarkdown remarkPlugins={[remarkGfm]}>
                                            {output}
                                        </ReactMarkdown>
                                    </div>
                                ) : (
                                    <div className="flex flex-col items-center justify-center h-full text-muted-foreground gap-2 opacity-50">
                                        <Terminal className="w-8 h-8" />
                                        <p>
                                          {status === 'Running' ? 'Generating analysis...' : 
                                           status === 'Skipped' ? 'Module skipped.' :
                                           status === 'Failed' ? 'Module failed.' :
                                           'Waiting for input...'}
                                        </p>
                                        {info?.message && (status === 'Skipped' || status === 'Failed') && (
                                          <p className="text-sm text-red-500 max-w-md text-center mt-2">
                                            Reason: {info.message}
                                          </p>
                                        )}
                                    </div>
                                )}
                            </ScrollArea>
                        </CardContent>
                    </Card>
                </TabsContent>
            );
        })}
      </Tabs>
    </div>
  );
}

function StatusDot({ status }: { status: TaskStatus }) {
    let colorClass = "bg-muted";
    if (status === 'Completed') colorClass = "bg-green-500";
    if (status === 'Failed') colorClass = "bg-red-500";
    if (status === 'Running') colorClass = "bg-blue-500 animate-pulse";
    if (status === 'Scheduled') colorClass = "bg-yellow-500";
    if (status === 'Skipped') colorClass = "bg-gray-400";
    
    return <div className={`w-2 h-2 rounded-full ${colorClass}`} />;
}

function StatusBadge({ status, message }: { status: TaskStatus, message?: string }) {
    let badge = <Badge variant="outline">Pending</Badge>;

    switch (status) {
      case 'Completed':
        badge = <Badge variant="outline" className="text-green-600 border-green-200 bg-green-50">Completed</Badge>;
        break;
      case 'Failed':
        badge = <Badge variant="destructive">Failed</Badge>;
        break;
      case 'Running':
        badge = <Badge variant="secondary" className="text-blue-600 bg-blue-50 animate-pulse">Generating...</Badge>;
        break;
      case 'Scheduled':
        badge = <Badge variant="outline" className="text-yellow-600 border-yellow-200 bg-yellow-50">Scheduled</Badge>;
        break;
      case 'Skipped':
        badge = <Badge variant="outline" className="text-gray-500">Skipped</Badge>;
        break;
      default:
        badge = <Badge variant="outline">Pending</Badge>;
    }

    if (message) {
      return (
        <TooltipProvider>
          <Tooltip>
            <TooltipTrigger asChild>
              <div className="flex items-center gap-2 cursor-help">
                {badge}
                <Info className="w-4 h-4 text-muted-foreground" />
              </div>
            </TooltipTrigger>
            <TooltipContent className="max-w-xs">
              <p>{message}</p>
            </TooltipContent>
          </Tooltip>
        </TooltipProvider>
      );
    }

    return badge;
  }
