import React, { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation'; // Import router
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Badge } from "@/components/ui/badge";
import { Loader2, Play, RefreshCw, BrainCircuit, Activity, Database, LayoutDashboard, LineChart, FileText } from "lucide-react";
import { WorkflowVisualizer } from '@/components/workflow/WorkflowVisualizer';
import { StockChart } from './StockChart';
import { useWorkflow } from '@/hooks/useWorkflow';
import { AnalysisTemplateSets } from '@/types/index';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import { ScrollArea } from '@/components/ui/scroll-area';
import { FundamentalDataView } from './FundamentalDataView';
import { AnalysisModulesView } from './AnalysisModulesView';

interface WorkflowReportLayoutProps {
  symbol: string;
  initialMarket?: string;
  initialTemplateId?: string;
  initialRequestId?: string;
}

export function WorkflowReportLayout({ 
  symbol, 
  initialMarket,
  initialTemplateId,
  initialRequestId
}: WorkflowReportLayoutProps) {
  const router = useRouter();
  const workflow = useWorkflow();
  const [templates, setTemplates] = useState<AnalysisTemplateSets>({});
  const [selectedTemplateId, setSelectedTemplateId] = useState(initialTemplateId || '');
  const [activeTab, setActiveTab] = useState("chart"); // Default to chart for quick overview

  // Auto-connect if initialRequestId is provided
  useEffect(() => {
    if (initialRequestId && workflow.status === 'idle' && !workflow.requestId) {
        workflow.connectToWorkflow(initialRequestId);
    }
  }, [initialRequestId, workflow]);

  // Load templates
  useEffect(() => {
    fetch('/api/configs/analysis_template_sets')
      .then(res => res.json())
      .then(data => {
        setTemplates(data);
        if (!selectedTemplateId && Object.keys(data).length > 0) {
          // Default to 'standard_analysis' if exists, else first key
          setSelectedTemplateId(data['standard_analysis'] ? 'standard_analysis' : Object.keys(data)[0]);
        }
      })
      .catch(err => console.error('Failed to load templates:', err));
  }, [selectedTemplateId]);

  // Auto switch to analysis tab when workflow starts - DISABLED
  // User prefers to see Data Fetching first or stay on current tab
  /*
  useEffect(() => {
    if (workflow.status === 'connecting' || workflow.status === 'connected') {
      setActiveTab("analysis");
    }
  }, [workflow.status]);
  */

  const handleStart = async () => {
    console.log('[WorkflowReportLayout] Start clicked for symbol:', symbol, 'Template:', selectedTemplateId);
    if (!selectedTemplateId) {
        console.warn('[WorkflowReportLayout] No template selected');
        return;
    }
    
    console.log('[WorkflowReportLayout] Calling startWorkflow...');
    const response = await workflow.startWorkflow({
      symbol,
      market: initialMarket,
      template_id: selectedTemplateId
    });
    console.log('[WorkflowReportLayout] startWorkflow returned:', response);

    // Handle Symbol Normalization Redirection
    if (response && response.symbol && response.symbol !== symbol) {
        console.log(`Redirecting normalized symbol: ${symbol} -> ${response.symbol}`);
        const newUrl = `/report/${encodeURIComponent(response.symbol)}?template_id=${selectedTemplateId}&market=${response.market}`;
        router.replace(newUrl);
    }
  };

  const isRunning = workflow.status === 'connecting' || workflow.status === 'connected';
  
  // Get current template config for dynamic tabs
  const currentTemplate = templates[selectedTemplateId];
  const dynamicModules = currentTemplate?.modules || {};

  return (
    <div className="container mx-auto p-4 space-y-4">
      {/* Header Card */}
      <Card>
        <CardHeader className="flex flex-row items-center justify-between py-4">
          <div className="flex flex-col gap-1">
            <CardTitle className="text-2xl font-bold flex items-center gap-3">
              {symbol}
              <Badge variant="outline" className="font-normal text-sm">
                {initialMarket || 'Unknown Market'}
              </Badge>
            </CardTitle>
            <div className="text-sm text-muted-foreground flex items-center gap-2">
              <StatusBadge status={workflow.status} error={workflow.error} />
              {workflow.requestId && (
                <span className="text-xs font-mono text-muted-foreground/50">
                  ID: {workflow.requestId}
                </span>
              )}
            </div>
          </div>

          <div className="flex items-center gap-4">
            <div className="w-[200px]">
              <Select 
                value={selectedTemplateId} 
                onValueChange={setSelectedTemplateId}
                disabled={isRunning}
              >
                <SelectTrigger>
                  <SelectValue placeholder="Select Template" />
                </SelectTrigger>
                <SelectContent>
                  {Object.entries(templates).map(([id, tpl]) => (
                    <SelectItem key={id} value={id}>{tpl.name}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <Button 
              onClick={handleStart} 
              disabled={!selectedTemplateId || isRunning}
              className="min-w-[100px]"
            >
              {isRunning ? (
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
              ) : (
                <Play className="mr-2 h-4 w-4" />
              )}
              {isRunning ? 'Running...' : 'Start'}
            </Button>
          </div>
        </CardHeader>
      </Card>

      {/* Main Content Tabs */}
      <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
        <TabsList className="grid w-full grid-cols-4">
          <TabsTrigger value="chart" className="gap-2">
            <LineChart className="w-4 h-4" />
            Market Chart
          </TabsTrigger>
          <TabsTrigger value="data" className="gap-2">
            <Database className="w-4 h-4" />
            Fundamental Data
          </TabsTrigger>
          <TabsTrigger value="analysis" className="gap-2">
            <LayoutDashboard className="w-4 h-4" />
            Analysis Modules
          </TabsTrigger>
          <TabsTrigger value="monitor" className="gap-2">
            <Activity className="w-4 h-4" />
            Workflow Monitor
          </TabsTrigger>
        </TabsList>

        {/* Tab A: Market Chart */}
        <TabsContent value="chart" className="mt-4">
          <StockChart symbol={symbol} />
        </TabsContent>

        {/* Tab B: Fundamental Data */}
        <TabsContent value="data" className="mt-4">
          <FundamentalDataView 
            taskStates={workflow.taskStates}
            taskInfos={workflow.taskInfos}
            taskOutputs={workflow.taskOutputs}
          />
        </TabsContent>

        {/* Tab C: Analysis Modules */}
        <TabsContent value="analysis" className="mt-4">
           {workflow.requestId ? (
              <AnalysisModulesView 
                taskStates={workflow.taskStates}
                taskInfos={workflow.taskInfos}
                taskOutputs={workflow.taskOutputs}
                modulesConfig={dynamicModules}
              />
           ) : (
             <EmptyState onStart={handleStart} message="Start workflow to generate analysis" />
           )}
        </TabsContent>

        {/* Tab D: Workflow Monitor */}
        <TabsContent value="monitor" className="mt-4 space-y-4">
          {workflow.dag ? (
            <div className="grid grid-cols-3 gap-4">
               <div className="col-span-2">
                  <WorkflowVisualizer 
                    dag={workflow.dag}
                    taskStates={workflow.taskStates}
                    taskOutputs={workflow.taskOutputs}
                  />
               </div>
               <div className="col-span-1">
                 <Card className="h-full">
                   <CardHeader>
                     <CardTitle className="text-lg">Execution Stats</CardTitle>
                   </CardHeader>
                   <CardContent>
                     <div className="space-y-4 text-sm">
                        <div className="flex justify-between py-2 border-b">
                          <span className="text-muted-foreground">Status</span>
                          <span className="font-medium">{workflow.status}</span>
                        </div>
                        <div className="flex justify-between py-2 border-b">
                          <span className="text-muted-foreground">Tasks Total</span>
                          <span className="font-medium">{workflow.dag.nodes.length}</span>
                        </div>
                        <div className="flex justify-between py-2 border-b">
                          <span className="text-muted-foreground">Tasks Completed</span>
                          <span className="font-medium text-green-600">
                            {Object.values(workflow.taskStates).filter(s => s === 'completed').length}
                          </span>
                        </div>
                        {workflow.finalResult && (
                           <div className="pt-4">
                              <Button variant="outline" className="w-full gap-2" onClick={() => setActiveTab("analysis")}>
                                <FileText className="w-4 h-4" />
                                View Final Report
                              </Button>
                           </div>
                        )}
                     </div>
                   </CardContent>
                 </Card>
               </div>
            </div>
          ) : (
            <EmptyState onStart={handleStart} message="Ready to visualize workflow execution" />
          )}
        </TabsContent>
      </Tabs>
    </div>
  );
}

function StatusBadge({ status, error }: { status: string, error: string | null }) {
  if (error) {
    return <Badge variant="destructive">Error: {error}</Badge>;
  }
  switch (status) {
    case 'connecting':
    case 'connected':
      return <Badge variant="secondary" className="animate-pulse">Processing</Badge>;
    case 'disconnected': // Usually means finished
      return <Badge variant="outline">Finished</Badge>;
    case 'idle':
      return <Badge variant="outline">Ready</Badge>;
    default:
      return <Badge variant="outline">{status}</Badge>;
  }
}

function EmptyState({ onStart, message }: { onStart: () => void, message: string }) {
  return (
    <div className="flex flex-col items-center justify-center h-[400px] border rounded-lg border-dashed bg-muted/5 text-muted-foreground">
      <BrainCircuit className="w-12 h-12 mb-4 opacity-20" />
      <p className="mb-4">{message}</p>
      <Button variant="outline" onClick={onStart}>
        Run Analysis
      </Button>
    </div>
  );
}

// Removed FinalReportView as it is now superseded by AnalysisModulesView
