import React, { useEffect, useState } from 'react';
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";
import { Card, CardHeader, CardTitle } 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 } from "lucide-react";
import { AnalysisTemplateSets } from '@/types';
import { ReportState } from '@/types/report';
import { RawDataViewer } from './RawDataViewer';
import { FinancialTable } from './FinancialTable';
import { AnalysisViewer } from './AnalysisViewer';
import { StockChart } from './StockChart';

interface ReportLayoutProps {
  state: ReportState;
  onTemplateChange: (id: string) => void;
  onTrigger: () => void;
}

export function ReportLayout({ state, onTemplateChange, onTrigger }: ReportLayoutProps) {
  const [templates, setTemplates] = useState<AnalysisTemplateSets>({});
  const [activeTab, setActiveTab] = useState("chart");

  // Load templates for dropdown
  useEffect(() => {
    fetch('/api/configs/analysis_template_sets')
      .then(res => res.json())
      .then(data => setTemplates(data))
      .catch(err => console.error(err));
  }, []);

  // Auto-switch tabs based on state
  useEffect(() => {
      if (state.fetchStatus === 'fetching') {
          setActiveTab("fundamental");
      } else if (state.analysisStatus === 'running' && activeTab === 'fundamental') {
          // Try to switch to the first analysis tab if available
          const firstModule = state.templateConfig ? Object.keys(state.templateConfig.modules)[0] : null;
          if (firstModule) {
              setActiveTab(firstModule);
          }
      }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [state.fetchStatus, state.analysisStatus, state.templateConfig]);

  return (
    <div className="container mx-auto p-4 space-y-4">
      {/* Header Area */}
      <Card>
        <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
          <div className="flex flex-col space-y-1">
            <CardTitle className="text-2xl font-bold">{state.symbol}</CardTitle>
            <div className="text-sm text-muted-foreground flex items-center gap-2">
              <span>Market: {state.market || 'Unknown'}</span>
              <span>•</span>
              <Badge variant={state.analysisStatus === 'running' ? "default" : state.analysisStatus === 'error' ? "destructive" : "secondary"}>
                {state.analysisStatus === 'running' ? 'Analyzing...' : 
                 state.analysisStatus === 'error' ? 'Failed' :
                 state.fetchStatus === 'fetching' ? 'Fetching Data...' : 'Ready'}
              </Badge>
            </div>
          </div>
          <div className="flex items-center gap-4">
            <div className="w-[200px]">
              <Select value={state.templateId} onValueChange={onTemplateChange}>
                <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={onTrigger} 
                disabled={!state.templateId || state.fetchStatus === 'fetching' || state.analysisStatus === 'running'}
            >
              {state.fetchStatus === 'fetching' || state.analysisStatus === 'running' ? (
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
              ) : null}
              Start Analysis
            </Button>
          </div>
        </CardHeader>
      </Card>

      {/* Main Content Area */}
      {/* Error Banner */}
      {(state.analysisStatus === 'error' || state.fetchStatus === 'error') && state.error && (
        <div className="bg-destructive/15 text-destructive text-sm p-3 rounded-md border border-destructive/20">
            <strong>Error:</strong> {state.error}
        </div>
      )}

      <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
        <TabsList className="w-full justify-start overflow-x-auto">
          <TabsTrigger value="chart">Stock Chart</TabsTrigger>
          <TabsTrigger value="fundamental">Fundamental Data</TabsTrigger>
          
          {/* Dynamic Tabs from Template */}
          {state.templateConfig && Object.entries(state.templateConfig.modules).map(([moduleId, moduleConfig]) => (
            <TabsTrigger key={moduleId} value={moduleId} disabled={state.fetchStatus !== 'complete'}>
              {moduleConfig.name}
              {state.analysisStatus === 'running' && !state.analysisResults[moduleId] && (
                  <Loader2 className="ml-2 h-3 w-3 animate-spin" />
              )}
            </TabsTrigger>
          ))}
        </TabsList>

        <div className="mt-4">
            {/* SCENARIO 1: Stock Chart */}
            <TabsContent value="chart" className="m-0">
                <StockChart symbol={state.symbol} />
            </TabsContent>

            {/* SCENARIO 2: Fundamental Data */}
            <TabsContent value="fundamental" className="m-0 space-y-8">
                {/* Always show the Provider/Task Grid (RawDataViewer) as it contains the per-provider status */}
                    <RawDataViewer 
                        data={state.fundamentalData} 
                        tasks={state.tasks}
                        status={state.fetchStatus} 
                    />
                
                {/* Show Aggregated Table only when complete */}
                {/* User request: Hide consolidated table temporarily to focus on raw provider data */}
                {/* {state.fetchStatus === 'complete' && (
                    <div className="space-y-4">
                        <div className="flex items-center justify-between">
                             <h3 className="text-lg font-semibold tracking-tight">Aggregated Financial Statements</h3>
                        </div>
                    <FinancialTable 
                        data={state.fundamentalData} 
                        status={state.fetchStatus} 
                    />
                    </div>
                )} */}
            </TabsContent>

            {/* SCENARIO 3: Analysis Modules */}
            {state.templateConfig && Object.entries(state.templateConfig.modules).map(([moduleId, moduleConfig]) => (
                <TabsContent key={moduleId} value={moduleId} className="m-0">
                    <AnalysisViewer 
                        result={state.analysisResults[moduleId]} 
                        config={moduleConfig}
                        isActive={activeTab === moduleId}
                    />
                </TabsContent>
            ))}
        </div>
      </Tabs>

      {/* Execution Details Footer */}
      <div className="text-xs text-muted-foreground border-t pt-2 flex justify-between">
          <span>Request ID: {state.requestId || '-'}</span>
          <span>
              Time: {(state.executionMeta.elapsed / 1000).toFixed(1)}s 
              | Tokens: {state.executionMeta.tokens}
          </span>
      </div>
    </div>
  );
}

