import { useEffect, useRef, useState } 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, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { ScrollArea } from "@/components/ui/scroll-area"
import { Separator } from "@/components/ui/separator"
import { WorkflowVisualizer } from '@/components/workflow/WorkflowVisualizer';
import { useWorkflowStore } from '@/stores/useWorkflowStore';
import { WorkflowDag, TaskStatus } from '@/types/workflow';
import { Terminal, Play, Loader2, Sparkles, Table, CheckCircle2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import { FinancialTable } from '@/components/report/FinancialTable';
import { useAnalysisTemplates } from "@/hooks/useConfig"

export function ReportPage() {
  const { id } = useParams();
  const [searchParams] = useSearchParams();
  const symbol = searchParams.get('symbol');
  const market = searchParams.get('market');
  const templateId = searchParams.get('templateId');
  
  const { 
    initialize, 
    setDag, 
    updateTaskStatus, 
    updateTaskContent,
    appendTaskLog, 
    setActiveTab,
    status, 
    tasks,
    dag,
    activeTab
  } = useWorkflowStore();

  const { data: templates } = useAnalysisTemplates();
  const templateName = templates && templateId ? templates[templateId]?.name : templateId;
  
  // SSE Connection Logic (Mocked for now)
  useEffect(() => {
      if (!id) return;
      initialize(id);
      
      // Set default active tab to overview or first task
      setActiveTab('overview');

      // --- MOCK SIMULATION START ---
      // In real app, this would be:
      // const eventSource = new EventSource(`/api/v1/workflow/events/${id}`);
      
      let timeouts: NodeJS.Timeout[] = [];

      const mockDag: WorkflowDag = {
          nodes: [
              { id: 'fetch:tushare', type: 'DataFetch', label: 'Fetch Tushare', dependencies: [], initial_status: 'Pending' },
              { id: 'fetch:finnhub', type: 'DataFetch', label: 'Fetch Finnhub', dependencies: [], initial_status: 'Pending' },
              { id: 'process:financials', type: 'DataProcessing', label: 'Clean Financials', dependencies: ['fetch:tushare', 'fetch:finnhub'], initial_status: 'Pending' },
              { id: 'analysis:basic', type: 'Analysis', label: 'Basic Analysis', dependencies: ['process:financials'], initial_status: 'Pending' },
              { id: 'analysis:risk', type: 'Analysis', label: 'Risk Assess', dependencies: ['process:financials'], initial_status: 'Pending' },
              { id: 'analysis:summary', type: 'Analysis', label: 'Final Summary', dependencies: ['analysis:basic', 'analysis:risk'], initial_status: 'Pending' },
          ]
      };

      // 1. Start
      timeouts.push(setTimeout(() => {
          setDag(mockDag);
      }, 1000));

      // 2. Run Fetch
      timeouts.push(setTimeout(() => {
          updateTaskStatus('fetch:tushare', 'Running', 'Connecting to Tushare API...');
          updateTaskStatus('fetch:finnhub', 'Running', 'Connecting to Finnhub...');
      }, 2000));

      timeouts.push(setTimeout(() => {
          updateTaskStatus('fetch:tushare', 'Completed', 'Fetched 3 years of income statements.');
          updateTaskStatus('fetch:finnhub', 'Completed', 'Fetched price history.');
      }, 4000));

      // 3. Process
      timeouts.push(setTimeout(() => {
          updateTaskStatus('process:financials', 'Running', 'Normalizing currency...');
      }, 4500));

      timeouts.push(setTimeout(() => {
          updateTaskStatus('process:financials', 'Completed', 'Data aligned to fiscal years.');
      }, 5500));

      // 4. Parallel Analysis
      timeouts.push(setTimeout(() => {
          updateTaskStatus('analysis:basic', 'Running', 'Generating basic metrics...');
          updateTaskStatus('analysis:risk', 'Running', 'Evaluating volatility...');
      }, 6000));

      // Stream logs
      timeouts.push(setTimeout(() => appendTaskLog('analysis:basic', 'Calculated ROE: 15%'), 7000));
      timeouts.push(setTimeout(() => appendTaskLog('analysis:basic', 'Calculated Net Margin: 22%'), 7500));
      timeouts.push(setTimeout(() => appendTaskLog('analysis:risk', 'Beta: 0.85'), 7200));

      // Stream Content for Basic Analysis
      const basicReport = `### Basic Analysis
      
**Profitability**: 
- ROE: **15%**
- Net Margin: **22%**

The company shows strong operational efficiency.`;
      
      streamMockContent(basicReport, 'analysis:basic', 6500, timeouts, updateTaskContent);

      // Stream Content for Risk
      const riskReport = `### Risk Assessment
      
**Volatility**: 
- Beta: **0.85** (Low Risk)
- Debt/Equity: **0.4** (Healthy)

No significant red flags detected in the balance sheet.`;
       streamMockContent(riskReport, 'analysis:risk', 6500, timeouts, updateTaskContent);

      timeouts.push(setTimeout(() => {
          updateTaskStatus('analysis:basic', 'Completed');
          updateTaskStatus('analysis:risk', 'Completed');
      }, 8500));

      // 5. Final (With Streaming Content)
      timeouts.push(setTimeout(() => {
          updateTaskStatus('analysis:summary', 'Running', 'Synthesizing report...');
          // Auto switch to summary tab when it starts
          setActiveTab('analysis:summary');
      }, 9000));

      // Simulate Typing Effect for Markdown
      const fullReport = `
# ${symbol} Financial Analysis Report

## 1. Executive Summary
Based on the financial data from **Tushare** and **Finnhub**, ${symbol} demonstrates strong fundamental performance.

*   **Profitability**: ROE is at **15%**, exceeding industry average.
*   **Risk**: Beta of **0.85** indicates lower volatility than the market.

## 2. Financial Health
The company has maintained a solid balance sheet.

| Metric | 2023 | 2024 |
| :--- | :--- | :--- |
| Revenue | $10B | $12B |
| Net Income | $1.5B | $2.0B |

> "The company's growth trajectory remains positive despite macroeconomic headwinds."

## 3. Conclusion
**Buy** rating is recommended for long-term investors.
      `;
      
      streamMockContent(fullReport, 'analysis:summary', 9100, timeouts, updateTaskContent);

      timeouts.push(setTimeout(() => {
           updateTaskStatus('analysis:summary', 'Completed', 'Report generated.');
      }, 13000));

      return () => timeouts.forEach(clearTimeout);
      // --- MOCK SIMULATION END ---

  }, [id]);

  // Helper to stream mock content char by char
  const streamMockContent = (text: string, taskId: string, startDelay: number, timeouts: NodeJS.Timeout[], updateFn: (id: string, delta: string) => void) => {
      const chunks = text.split("");
      let delay = startDelay;
      chunks.forEach((char) => {
          delay += 20; // Typing speed
          timeouts.push(setTimeout(() => {
              updateFn(taskId, char);
          }, delay));
      });
  };

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

  // Filter nodes that should have their own tabs (e.g. Analysis & Processing)
  // We keep DataFetch nodes out of tabs to reduce clutter, or maybe group them in "Overview"?
  // For now, let's show tabs for all Analysis nodes + Overview + Data
  const tabNodes = dag?.nodes.filter(n => n.type === 'Analysis') || [];

  return (
    <div className="container py-6 space-y-6 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="grid grid-cols-12 gap-6 flex-1 min-h-0">
            {/* Left Col: Visualizer & Logs (4 cols) */}
            <div className="col-span-4 flex flex-col gap-4 min-h-0 h-full">
                <Card className="shrink-0">
                    <CardHeader className="py-3 px-4">
                        <CardTitle className="text-sm font-medium">Workflow Status</CardTitle>
                    </CardHeader>
                    <CardContent className="p-0">
                         <WorkflowVisualizer />
                    </CardContent>
                </Card>

                <Card className="flex-1 flex flex-col min-h-0">
                    <CardHeader className="py-3 px-4 border-b">
                        <CardTitle className="text-sm font-medium flex items-center gap-2">
                            <Terminal className="h-4 w-4" />
                            Real-time Logs
                        </CardTitle>
                    </CardHeader>
                    <CardContent className="flex-1 p-0 min-h-0">
                        <ScrollArea className="h-full p-4">
                            <div className="space-y-1.5 font-mono text-xs">
                                {allLogs.length === 0 && <span className="text-muted-foreground italic">Waiting for logs...</span>}
                                {allLogs.map((entry, i) => (
                                    <div key={i} className="break-all">
                                        <span className="text-blue-500 font-semibold">[{entry.taskId}]</span>{" "}
                                        <span className="text-foreground">{entry.log}</span>
                                    </div>
                                ))}
                            </div>
                        </ScrollArea>
                    </CardContent>
                </Card>
            </div>

            {/* Right Col: Detail Tabs (8 cols) */}
            <div className="col-span-8 h-full min-h-0">
                <Tabs value={activeTab} onValueChange={setActiveTab} className="h-full flex flex-col">
                    <div className="w-full overflow-x-auto bg-background border-b shrink-0">
                        <TabsList className="h-auto p-0 bg-transparent gap-0">
                            <TabsTrigger value="overview" className="rounded-none border-b-2 border-transparent data-[state=active]:border-primary data-[state=active]:bg-transparent px-4 py-3">
                                Overview
                            </TabsTrigger>
                            <TabsTrigger value="data" className="rounded-none border-b-2 border-transparent data-[state=active]:border-primary data-[state=active]:bg-transparent px-4 py-3">
                                Fundamental Data
                            </TabsTrigger>
                            {tabNodes.map(node => (
                                <TabsTrigger 
                                    key={node.id} 
                                    value={node.id}
                                    className="rounded-none border-b-2 border-transparent data-[state=active]:border-primary data-[state=active]:bg-transparent px-4 py-3 gap-2"
                                >
                                    {node.label}
                                    <TaskStatusIndicator status={tasks[node.id]?.status || 'Pending'} />
                                </TabsTrigger>
                            ))}
                        </TabsList>
                    </div>
                    
                    {/* Content Area */}
                    <div className="flex-1 min-h-0 bg-muted/5 relative">
                        <TabsContent value="overview" className="absolute inset-0 m-0 p-6 overflow-y-auto">
                            <div className="max-w-2xl mx-auto text-center py-10 space-y-4">
                                <div className="bg-primary/10 w-16 h-16 rounded-full flex items-center justify-center mx-auto">
                                    <Sparkles className="h-8 w-8 text-primary" />
                                </div>
                                <h2 className="text-2xl font-bold">Analysis In Progress</h2>
                                <p className="text-muted-foreground">
                                    Select a task tab above or click a node in the graph to view details.
                                </p>
                            </div>
                        </TabsContent>

                        <TabsContent value="data" className="absolute inset-0 m-0 p-6 overflow-y-auto">
                            <FinancialTable />
                        </TabsContent>

                        {tabNodes.map(node => (
                            <TabsContent key={node.id} value={node.id} className="absolute inset-0 m-0 overflow-hidden flex flex-col">
                                <ScrollArea className="flex-1">
                                    <div className="p-8 max-w-4xl mx-auto">
                                        <div className="prose dark:prose-invert max-w-none">
                                            {tasks[node.id]?.content ? (
                                                <ReactMarkdown remarkPlugins={[remarkGfm]}>
                                                    {tasks[node.id].content || ''}
                                                </ReactMarkdown>
                                            ) : (
                                                 <div className="flex flex-col items-center justify-center h-[300px] text-muted-foreground space-y-4">
                                                    {tasks[node.id]?.status === 'Pending' && <p>Waiting to start...</p>}
                                                    {tasks[node.id]?.status === 'Running' && !tasks[node.id]?.content && <Loader2 className="h-8 w-8 animate-spin" />}
                                                 </div>
                                            )}
                                            {tasks[node.id]?.status === 'Running' && (
                                                <span className="inline-block w-2 h-4 ml-1 bg-primary animate-pulse"/>
                                            )}
                                        </div>
                                    </div>
                                </ScrollArea>
                            </TabsContent>
                        ))}
                    </div>
                </Tabs>
            </div>
        </div>
    </div>
  );
}

function WorkflowStatusBadge({ status }: { status: string }) {
    const variants: Record<string, "default" | "secondary" | "destructive" | "outline"> = {
        'IDLE': 'outline',
        'CONNECTING': 'secondary',
        'RUNNING': 'default',
        'COMPLETED': 'default',
        'ERROR': 'destructive'
    };
    
    let colorClass = "";
    if (status === 'RUNNING') colorClass = "bg-blue-500 hover:bg-blue-600 border-transparent";
    if (status === 'COMPLETED') colorClass = "bg-green-600 hover:bg-green-600 border-transparent";

    return <Badge variant={variants[status] || 'outline'} className={colorClass}>{status}</Badge>;
}

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