import { useState, useEffect, useMemo } from 'react';
import { useParams, useSearchParams } from 'react-router-dom';
import { Badge } from '@/components/ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { WorkflowVisualizer } from '@/components/workflow/WorkflowVisualizer';
import { ContextExplorer } from '@/components/workflow/ContextExplorer';
import { useWorkflowStore } from '@/stores/useWorkflowStore';
import { TaskStatus, schemas } from '@/api/schema.gen';
import { Loader2, CheckCircle2, AlertCircle, Clock, PanelLeftClose, PanelLeftOpen, FileText, GitBranch, ArrowRight } from 'lucide-react';
import { Button } from '@/components/ui/button';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import { useAnalysisTemplates } from "@/hooks/useConfig"
import { RealtimeLogs } from '@/components/RealtimeLogs';
import { WorkflowStatus, ConnectionStatus, TaskState } from '@/types/workflow';
import { Progress } from "@/components/ui/progress"
import { cn, formatNodeName } from '@/lib/utils';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";

export function ReportPage() {
  const { id } = useParams();
  // ... (rest of the imports)
  const [searchParams] = useSearchParams();
  const symbol = searchParams.get('symbol');
  const market = searchParams.get('market');
  const templateId = searchParams.get('templateId');
  const [isSidebarCollapsed, setIsSidebarCollapsed] = useState(false);
  const [isWorkflowSticky, setIsWorkflowSticky] = useState(false);

  useEffect(() => {
      const handleScroll = () => {
          // Detect if user has scrolled down enough to trigger visual sticky change
          // Header (64) + Padding (16) = 80px. 
          // We add a small threshold to avoid flickering
          setIsWorkflowSticky(window.scrollY > 10);
      };
      window.addEventListener('scroll', handleScroll);
      return () => window.removeEventListener('scroll', handleScroll);
  }, []);
  
  const { 
    initialize, 
    handleEvent,
    status, 
    tasks,
    dag,
    activeTab,
    setActiveTab
  } = useWorkflowStore();

  const { data: templates } = useAnalysisTemplates();
  const templateName = templates && templateId ? templates[templateId]?.name : templateId;
  
  // SSE Connection Logic
  useEffect(() => {
      if (!id) return;
      initialize(id);
      
      // Connect to real backend SSE
      const eventSource = new EventSource(`/api/v1/workflow/events/${id}`);
      
      eventSource.onmessage = (event) => {
          try {
              const parsedEvent = JSON.parse(event.data);
              handleEvent(parsedEvent);
          } catch (e) {
              console.error("Failed to parse SSE event:", e);
          }
      };

      eventSource.onerror = (err) => {
          console.error("SSE Connection Error:", err);
          // Optional: Retry logic or error state update
          // eventSource.close();
      };

      return () => {
          eventSource.close();
      };
  }, [id, initialize, handleEvent]);

    // Combine logs from all tasks for the "Global Log" view
    const allLogs = useMemo(() => Object.entries(tasks).flatMap(([taskId, state]) => 
        state.logs.map(log => ({ taskId, log }))
    ), [tasks]);

    // Include ALL nodes in tabs to allow debugging context for DataFetch tasks
    const tabNodes = dag?.nodes || [];

  return (
    <div className="container py-4 space-y-4 min-h-[calc(100vh-4rem)] flex flex-col">
        {/* Header Area */}
        <div className="flex items-center justify-between shrink-0">
            <div className="space-y-1">
                <h1 className="text-2xl font-bold tracking-tight flex items-center gap-2">
                    {symbol}
                    <Badge variant="outline" className="text-base font-normal">{market}</Badge>
                    <WorkflowStatusBadge status={status} />
                </h1>
                <div className="flex items-center gap-4 text-sm text-muted-foreground">
                    <span>Request ID: <span className="font-mono">{id}</span></span>
                    {templateName && <span>Template: <span className="font-medium">{templateName}</span></span>}
                </div>
            </div>
            <div className="flex gap-2">
                 <Button size="sm" variant="outline">Export PDF</Button>
            </div>
        </div>

        {/* Main Content Grid */}
        <div className="flex gap-4 flex-1 items-start">
            {/* Left Col: Visualizer */}
            <div className={cn(
                "flex flex-col gap-4 transition-all duration-300 ease-in-out sticky top-20 h-[calc(100vh-6rem)]",
                isSidebarCollapsed ? "w-[60px]" : "w-[33%] min-w-[350px]"
            )}>
                <Card className={cn(
                    "flex-1 flex flex-col min-h-0 py-0 gap-0 overflow-hidden transition-all duration-300",
                    isWorkflowSticky ? "shadow-lg border-primary/20" : "shadow-sm"
                )}>
                    <CardHeader 
                        className={cn(
                            "py-3 px-4 shrink-0 flex flex-row items-center space-y-0 transition-all duration-300 cursor-pointer hover:bg-muted/50", 
                            isSidebarCollapsed ? "h-full flex-col justify-start py-3 gap-4" : "h-[60px] justify-between"
                        )}
                        onClick={() => setIsSidebarCollapsed(!isSidebarCollapsed)}
                    >
                        {!isSidebarCollapsed ? (
                            <CardTitle className="text-sm font-medium truncate">Workflow Status</CardTitle>
                        ) : (
                            <div className="writing-vertical-lr transform rotate-180 text-sm font-medium whitespace-nowrap tracking-wide text-muted-foreground mt-2">
                                Workflow Status
                            </div>
                        )}
                        <Button 
                            variant="ghost" 
                            size="icon" 
                            className={cn("h-8 w-8 shrink-0", isSidebarCollapsed && "order-first")} 
                            onClick={(e) => {
                                e.stopPropagation(); // Prevent double toggle if button is clicked
                                setIsSidebarCollapsed(!isSidebarCollapsed);
                            }}
                        >
                            {isSidebarCollapsed ? <PanelLeftOpen className="h-4 w-4" /> : <PanelLeftClose className="h-4 w-4" />}
                        </Button>
                    </CardHeader>
                    <CardContent className={cn("p-0 flex-1 min-h-0 relative transition-opacity duration-200", isSidebarCollapsed ? "opacity-0 pointer-events-none" : "opacity-100")}>
                         <div className="absolute inset-0">
                            <WorkflowVisualizer />
                         </div>
                    </CardContent>
                </Card>
            </div>

            {/* Right Col: Detail Tabs */}
            <div className="flex-1 min-w-0">
                <Tabs value={activeTab} onValueChange={setActiveTab} className="flex flex-col">
                    <div className="w-full shrink-0">
                        <TabsList className="h-auto p-0 bg-transparent gap-1 flex-wrap justify-start w-full border-b">
                            <TabsTrigger 
                                value="overview" 
                                className="
                                    rounded-t-md rounded-b-none 
                                    border border-b-0 border-border/50 
                                    bg-muted/60 
                                    data-[state=active]:bg-background 
                                    data-[state=active]:border-border 
                                    data-[state=active]:border-b-background 
                                    data-[state=active]:mb-[-1px] 
                                    data-[state=active]:shadow-sm 
                                    data-[state=active]:z-10
                                    px-4 py-2.5
                                    text-muted-foreground
                                    data-[state=active]:text-foreground
                                    relative
                                "
                            >
                                Overview
                            </TabsTrigger>
                            {tabNodes.map(node => (
                                <TabsTrigger 
                                    key={node.id} 
                                    value={node.id}
                                    className="
                                        rounded-t-md rounded-b-none 
                                        border border-b-0 border-border/50 
                                        bg-muted/60 
                                        data-[state=active]:bg-background 
                                        data-[state=active]:border-border 
                                        data-[state=active]:border-b-background 
                                        data-[state=active]:mb-[-1px] 
                                        data-[state=active]:shadow-sm 
                                        data-[state=active]:z-10
                                        px-4 py-2.5 gap-2
                                        text-muted-foreground
                                        data-[state=active]:text-foreground
                                        relative
                                    "
                                >
                                    {node.display_name || formatNodeName(node.name)}
                                    <TaskStatusIndicator status={tasks[node.id]?.status || schemas.TaskStatus.enum.Pending} />
                                </TabsTrigger>
                            ))}
                        </TabsList>
                    </div>
                    
                    {/* Content Area */}
                    <div className="mt-4 bg-background border rounded-md relative shadow-sm">
                        <TabsContent value="overview" className="m-0 p-6">
                            <OverviewTabContent 
                                status={status}
                                tasks={tasks}
                                totalTasks={dag?.nodes.length || 0}
                                completedTasks={Object.values(tasks).filter(t => t.status === schemas.TaskStatus.enum.Completed).length}
                            />
                        </TabsContent>

                        {tabNodes.map(node => (
                            <TabsContent key={node.id} value={node.id} className="m-0 p-0">
                                <TaskDetailView task={tasks[node.id]} requestId={id} />
                            </TabsContent>
                        ))}
                    </div>
                </Tabs>
            </div>
        </div>
        
        <RealtimeLogs logs={allLogs} className="shrink-0 sticky bottom-0 z-10 bg-background border-t" />
    </div>
  );
}


function OverviewTabContent({ status, tasks, totalTasks, completedTasks }: { 
    status: WorkflowStatus, 
    tasks: Record<string, TaskState>,
    totalTasks: number,
    completedTasks: number
}) {
    // ... (implementation remains same)
    const progress = totalTasks > 0 ? (completedTasks / totalTasks) * 100 : 0;
    
    // Find errors
    const failedTasks = Object.entries(tasks).filter(([_, t]) => t.status === schemas.TaskStatus.enum.Failed);

    return (
        <div className="max-w-3xl mx-auto space-y-8 py-6">
            {/* Hero Status */}
            <Card className="border-primary/10 shadow-md">
                <CardHeader className="text-center pb-2">
                    <div className="mx-auto mb-4 bg-muted rounded-full p-3 w-fit">
                        {status === schemas.TaskStatus.enum.Completed ? (
                            <CheckCircle2 className="h-8 w-8 text-green-600" />
                        ) : status === schemas.TaskStatus.enum.Failed ? (
                            <AlertCircle className="h-8 w-8 text-destructive" />
                        ) : (
                            <Loader2 className="h-8 w-8 text-blue-500 animate-spin" />
                        )}
                    </div>
                    <CardTitle className="text-2xl">
                        {status === schemas.TaskStatus.enum.Completed ? "Analysis Completed" : 
                         status === schemas.TaskStatus.enum.Failed ? "Analysis Failed" : 
                         "Analysis In Progress"}
                    </CardTitle>
                </CardHeader>
                <CardContent className="space-y-6">
                    <div className="space-y-2">
                        <div className="flex justify-between text-sm text-muted-foreground">
                            <span>Overall Progress</span>
                            <span>{Math.round(progress)}% ({completedTasks}/{totalTasks} tasks)</span>
                        </div>
                        <Progress value={progress} className="h-2" />
                    </div>

                    {/* Failed Tasks Warning */}
                    {failedTasks.length > 0 && (
                        <div className="bg-destructive/10 text-destructive rounded-md p-4 text-sm flex items-start gap-2">
                            <AlertCircle className="h-5 w-5 shrink-0 mt-0.5" />
                            <div className="space-y-1">
                                <p className="font-semibold">Some tasks failed:</p>
                                <ul className="list-disc list-inside">
                                    {failedTasks.map(([id, t]) => (
                                        <li key={id}>
                                            <span className="font-medium">{id}</span>: {t.message || "Unknown error"}
                                        </li>
                                    ))}
                                </ul>
                            </div>
                        </div>
                    )}
                </CardContent>
            </Card>

            {/* Stats Grid */}
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                <Card>
                    <CardHeader className="pb-2">
                        <CardTitle className="text-sm font-medium text-muted-foreground">Total Tasks</CardTitle>
                    </CardHeader>
                    <CardContent>
                        <div className="text-2xl font-bold">{totalTasks}</div>
                    </CardContent>
                </Card>
                <Card>
                    <CardHeader className="pb-2">
                        <CardTitle className="text-sm font-medium text-muted-foreground">Completed</CardTitle>
                    </CardHeader>
                    <CardContent>
                        <div className="text-2xl font-bold text-green-600">{completedTasks}</div>
                    </CardContent>
                </Card>
                <Card>
                    <CardHeader className="pb-2">
                        <CardTitle className="text-sm font-medium text-muted-foreground">Duration</CardTitle>
                    </CardHeader>
                    <CardContent>
                        <div className="text-2xl font-bold flex items-center gap-2">
                            <Clock className="h-5 w-5 text-muted-foreground" />
                            <span>--:--</span>
                        </div>
                    </CardContent>
                </Card>
            </div>
        </div>
    )
}

function TaskDetailView({ task, requestId }: { task?: TaskState, requestId?: string }) {
    // Only show context tab if we have commits
    const hasContext = task?.inputCommit || task?.outputCommit;

    if (task?.status === schemas.TaskStatus.enum.Failed && !task.content) {
        return (
            <div className="flex flex-col h-full">
                <Tabs defaultValue="report" className="flex-1 flex flex-col">
                    {hasContext && (
                         <div className="border-b px-4 bg-muted/40">
                            <TabsList className="bg-transparent p-0 h-10 w-full justify-start gap-6">
                                <TabsTrigger value="report" className="data-[state=active]:bg-transparent data-[state=active]:shadow-none data-[state=active]:border-b-2 data-[state=active]:border-primary rounded-none px-0 py-2 h-full">
                                    <span className="flex items-center gap-2"><FileText className="w-4 h-4" /> Report Content</span>
                                </TabsTrigger>
                                <TabsTrigger value="context" className="data-[state=active]:bg-transparent data-[state=active]:shadow-none data-[state=active]:border-b-2 data-[state=active]:border-primary rounded-none px-0 py-2 h-full">
                                     <span className="flex items-center gap-2"><GitBranch className="w-4 h-4" /> Context Inspector</span>
                                </TabsTrigger>
                            </TabsList>
                        </div>
                    )}
                    <TabsContent value="report" className="flex-1 m-0">
                        <div className="flex flex-col items-center justify-center h-full min-h-[400px] p-8 text-muted-foreground space-y-4">
                            <AlertCircle className="h-12 w-12 text-destructive/80 mb-2" />
                            <h3 className="text-lg font-medium text-foreground">Analysis Failed</h3>
                            <div className="max-w-xl text-center space-y-2">
                                <p className="text-sm text-muted-foreground">The task encountered an error and could not complete.</p>
                                <p className="text-destructive bg-destructive/10 p-4 rounded-md border border-destructive/20 font-mono text-sm whitespace-pre-wrap">
                                    {task.message || "Unknown error occurred."}
                                </p>
                            </div>
                        </div>
                    </TabsContent>
                     <TabsContent value="context" className="flex-1 m-0 h-[600px]">
                        {requestId && (task.inputCommit || task.outputCommit) && (
                            <ContextExplorer 
                                reqId={requestId} 
                                commitHash={task.outputCommit || task.inputCommit!}
                                diffTargetHash={task.outputCommit ? task.inputCommit : undefined}
                                className="h-full p-4"
                            />
                        )}
                    </TabsContent>
                </Tabs>
            </div>
        );
    }

    return (
        <div className="flex flex-col h-full">
             <Tabs defaultValue="report" className="flex-1 flex flex-col">
                {hasContext && (
                        <div className="border-b px-4 bg-muted/40">
                        <TabsList className="bg-transparent p-0 h-10 w-full justify-start gap-6">
                            <TabsTrigger value="report" className="data-[state=active]:bg-transparent data-[state=active]:shadow-none data-[state=active]:border-b-2 data-[state=active]:border-primary rounded-none px-0 py-2 h-full">
                                <span className="flex items-center gap-2"><FileText className="w-4 h-4" /> Report Content</span>
                            </TabsTrigger>
                            <TabsTrigger value="context" className="data-[state=active]:bg-transparent data-[state=active]:shadow-none data-[state=active]:border-b-2 data-[state=active]:border-primary rounded-none px-0 py-2 h-full">
                                    <span className="flex items-center gap-2"><GitBranch className="w-4 h-4" /> Context Inspector</span>
                            </TabsTrigger>
                        </TabsList>
                    </div>
                )}
                
                <TabsContent value="report" className="flex-1 m-0 min-h-0 overflow-auto">
                    <div className="p-8 max-w-4xl mx-auto">
                        <div className="prose dark:prose-invert max-w-none prose-p:text-foreground prose-headings:text-foreground prose-li:text-foreground prose-strong:text-foreground prose-span:text-foreground">
                            {task?.content ? (
                                <ReactMarkdown remarkPlugins={[remarkGfm]}>
                                    {task.content || ''}
                                </ReactMarkdown>
                            ) : (
                                <div className="flex flex-col items-center justify-center h-[300px] text-muted-foreground space-y-4">
                                {task?.status === schemas.TaskStatus.enum.Pending && <p>Waiting to start...</p>}
                                {task?.status === schemas.TaskStatus.enum.Running && !task?.content && <Loader2 className="h-8 w-8 animate-spin" />}
                                </div>
                            )}
                            {task?.status === schemas.TaskStatus.enum.Running && (
                                <span className="inline-block w-2 h-4 ml-1 bg-primary animate-pulse"/>
                            )}
                        </div>
                    </div>
                </TabsContent>
                
                <TabsContent value="context" className="flex-1 m-0 h-[600px]">
                    {requestId && (task?.inputCommit || task?.outputCommit) && (
                        <ContextExplorer 
                            reqId={requestId} 
                            commitHash={task.outputCommit || task.inputCommit!}
                            diffTargetHash={task.outputCommit ? task.inputCommit : undefined}
                            className="h-full p-4"
                        />
                    )}
                </TabsContent>
            </Tabs>
        </div>
    );
}

function WorkflowStatusBadge({ status }: { status: WorkflowStatus }) {
    // Map local store status to TaskStatus enum for consistency where possible
    // These comparisons are now type-safe against the WorkflowStatus literal union type
    if (status === schemas.TaskStatus.enum.Running) {
        return (
            <Badge variant="default" className="bg-blue-500 hover:bg-blue-600 border-transparent flex items-center gap-1">
                <Loader2 className="h-3 w-3 animate-spin" />
                {schemas.TaskStatus.enum.Running}
            </Badge>
        );
    }

    if (status === schemas.TaskStatus.enum.Completed) {
        return (
            <Badge variant="default" className="bg-green-600 hover:bg-green-600 border-transparent">
                 {schemas.TaskStatus.enum.Completed}
            </Badge>
        );
    }

    if (status === schemas.TaskStatus.enum.Failed) {
        return (
            <Badge variant="destructive">
                {schemas.TaskStatus.enum.Failed}
            </Badge>
        );
    }

    if (status === ConnectionStatus.Connecting) {
         return <Badge variant="secondary">CONNECTING</Badge>;
    }

    return <Badge variant="outline">{status}</Badge>;
}

function TaskStatusIndicator({ status }: { status: TaskStatus }) {
    switch (status) {
        case schemas.TaskStatus.enum.Running: return <Loader2 className="h-3 w-3 animate-spin text-blue-500" />;
        case schemas.TaskStatus.enum.Completed: return <CheckCircle2 className="h-3 w-3 text-green-500" />;
        case schemas.TaskStatus.enum.Failed: return <div className="h-2 w-2 rounded-full bg-red-500" />;
        default: return null;
    }
}
