// ResultsSection.jsx
import React, { useState, useEffect, useRef } from 'react';
import {
  Box,
  Paper,
  Typography,
  Tabs,
  Tab,
  Fade,
  Chip,
  Stack,
  Divider,
  useTheme,
  Alert,
} from '@mui/material';
import ShowChartIcon from '@mui/icons-material/ShowChart';
import CompareIcon from '@mui/icons-material/Compare';
import BarChartIcon from '@mui/icons-material/BarChart';
import TimelineIcon from '@mui/icons-material/Timeline';
import TrendingDownIcon from '@mui/icons-material/TrendingDown';
import SecurityIcon from '@mui/icons-material/Security';
import AssessmentIcon from '@mui/icons-material/Assessment';
import AIInsightsLoader from './results/AIInsightsLoader';
import { formatDate } from '../utils/formatters';

// Import your components
import PortfolioOverview from './results/PortfolioOverview';
import CorrelationAnalysis from './results/CorrelationAnalysis';
import VolumeAnalysisTab from './results/VolumeAnalysisTab';
import RebalancingAnalysis from './results/RebalancingAnalysis';
import DrawdownAnalysis from './results/DrawdownAnalysis';
import RiskAnalysis from './results/RiskAnalysis';
import AttributionAnalysis from './results/AttributionAnalysis';

function ResultsSection({ results, comparisonPortfolios, onRemoveComparison }) {
  const [activeTab, setActiveTab] = useState(0);
  const [isAnalyzing, setIsAnalyzing] = useState(false);
  const [analysisResults, setAnalysisResults] = useState({});
  const [analysisError, setAnalysisError] = useState(null);
  const [tabAnalysisStatus, setTabAnalysisStatus] = useState({});  // Track each tab's analysis status
  const [aiInsightsError, setAiInsightsError] = useState(null); // New state for AI insights specific errors
  const theme = useTheme();

  const isFirstRender = useRef(true);

  // Define 'showCorrelation' here as it is used in 'tabs' definition
  const { comparison, dates, correlations, data_quality } = results || {};
  const mode = data_quality?.mode || 'portfolio_comparison';
  const isBenchmarkMode = mode === 'benchmark';

  const portfolioNames = comparison ? Object.keys(comparison) : [];
  const mainPortfolio = portfolioNames[0];
  const mainPortfolioName =
    comparisonPortfolios.find(
      (p) => JSON.stringify(p.portfolio) === JSON.stringify(comparison?.[mainPortfolio]?.portfolio)
    )?.name || mainPortfolio;
  const comparisonPortfolio = portfolioNames[1];

  const showCorrelation =
    correlations && correlations.pearson && Object.keys(correlations.pearson.matrix || {}).length > 1;

  const tabs = [
    {
      label: 'Overview',
      component: PortfolioOverview,
      icon: ShowChartIcon,
      description: 'Key metrics and portfolio performance',
      color: theme.palette.primary.main,
      getAnalysisData: (results) => ({
        metrics: results.comparison[mainPortfolio]?.metrics || {},
        comparisonMetrics: comparisonPortfolio ? results.comparison[comparisonPortfolio]?.metrics : null,
        mode: mode,
        portfolioName: mainPortfolioName,
        comparisonName: comparisonPortfolio
      }),
    },
    ...(showCorrelation
      ? [
          {
            label: 'Correlation Analysis',
            component: CorrelationAnalysis,
            icon: CompareIcon,
            description: 'Asset relationships and diversification',
            color: theme.palette.info.main,
            getAnalysisData: (results) => ({
              correlations: results.correlations || {},
              portfolioCorrelations: results.comparison[mainPortfolio]?.correlations || {},
              comparisonCorrelations: comparisonPortfolio ? results.comparison[comparisonPortfolio]?.correlations : null,
              mode: mode,
              portfolioName: mainPortfolioName,
              comparisonName: comparisonPortfolio
            }),
          },
        ]
      : []),
    {
      label: 'Volume Analysis',
      component: VolumeAnalysisTab,
      icon: BarChartIcon,
      description: 'Trading volume patterns and trends',
      color: theme.palette.info.dark,
      getAnalysisData: (results) => ({
        volumeAnalysis: results.comparison[mainPortfolio]?.metrics?.volume_analysis || {},
        comparisonVolumeAnalysis: comparisonPortfolio ? results.comparison[comparisonPortfolio]?.metrics?.volume_analysis : null,
        mode: mode,
        portfolioName: mainPortfolioName,
        comparisonName: comparisonPortfolio
      }),
    },
    {
      label: 'Rebalancing Analysis',
      component: RebalancingAnalysis,
      icon: TimelineIcon,
      description: 'Portfolio rebalancing strategies',
      color: theme.palette.success.main,
      getAnalysisData: (results) => ({
        rebalancing: results.comparison[mainPortfolio]?.rebalancing || {},
        comparisonRebalancing: comparisonPortfolio ? results.comparison[comparisonPortfolio]?.rebalancing : null,
        mode: mode,
        portfolioName: mainPortfolioName,
        comparisonName: comparisonPortfolio
      }),
    },
    {
      label: 'Drawdown Analysis',
      component: DrawdownAnalysis,
      icon: TrendingDownIcon,
      description: 'Historical portfolio declines',
      color: theme.palette.warning.main,
      getAnalysisData: (results) => ({
        drawdowns: results.comparison[mainPortfolio]?.metrics?.drawdowns || {},
        comparisonDrawdowns: comparisonPortfolio ? results.comparison[comparisonPortfolio]?.metrics?.drawdowns : null,
        mode: mode,
        portfolioName: mainPortfolioName,
        comparisonName: comparisonPortfolio
      }),
    },
    {
      label: 'Risk Analysis',
      component: RiskAnalysis,
      icon: SecurityIcon,
      description: 'Value at Risk and risk metrics',
      color: theme.palette.error.main,
      getAnalysisData: (results) => ({
        riskMetrics: results.comparison[mainPortfolio]?.metrics?.risk_metrics || {},
        comparisonRiskMetrics: comparisonPortfolio ? results.comparison[comparisonPortfolio]?.metrics?.risk_metrics : null,
        mode: mode,
        portfolioName: mainPortfolioName,
        comparisonName: comparisonPortfolio
      }),
    },
    {
      label: 'Attribution Analysis',
      component: AttributionAnalysis,
      icon: AssessmentIcon,
      description: 'Performance drivers and factors',
      color: theme.palette.secondary.main,
      getAnalysisData: (results) => ({
        attribution: results.comparison[mainPortfolio]?.attribution || {},
        comparisonAttribution: comparisonPortfolio ? results.comparison[comparisonPortfolio]?.attribution : null,
        mode: mode,
        portfolioName: mainPortfolioName,
        comparisonName: comparisonPortfolio
      }),
    },
  ];

  useEffect(() => {
    const startAnalysis = async () => {
      if (results && isFirstRender.current) {
        isFirstRender.current = false;
        let eventSource = null;
        
        try {
          // Initialize all tabs as analyzing
          const initialStatus = {};
          tabs.forEach(tab => {
            initialStatus[tab.label] = 'analyzing';
          });
          setTabAnalysisStatus(initialStatus);
          
          // Collect analysis data for all tabs
          const analysisData = {};
          tabs.forEach(tab => {
            if (tab.getAnalysisData) {
              analysisData[tab.label] = tab.getAnalysisData(results);
            }
          });

          // Make the API call
          const response = await fetch('/api/analyze', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify({ analysisData }),
          });

          if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
          }

          // Calculate number of tabs that need analysis
          const tabsNeedingAnalysis = tabs.filter(tab => tab.getAnalysisData).map(tab => tab.label);

          // Create EventSource with query parameter
          eventSource = new EventSource(`/api/analyze/stream?expected_tabs=${tabsNeedingAnalysis.join(',')}`);
          
          eventSource.onmessage = (event) => {
            try {
              const data = JSON.parse(event.data);
              
              // Handle completion message
              if (data.status === 'completed') {
                console.log('Analysis completed:', data.completedTabs);
                eventSource.close();
                return;
              }
              
              // Handle error messages
              if (data.error) {
                console.error('Analysis error:', data.error);
                setAnalysisError(data.error);
                return;
              }

              const { tabName, analysis } = data;
              
              if (tabName && analysis) {
                setAnalysisResults(prev => ({
                  ...prev,
                  [tabName]: analysis
                }));
                setTabAnalysisStatus(prev => ({
                  ...prev,
                  [tabName]: 'completed'
                }));
              }
            } catch (error) {
              console.error('Error processing SSE message:', error);
            }
          };

          eventSource.onerror = (error) => {
            console.error('EventSource error:', error);
            eventSource.close();
            setAiInsightsError('Failed to receive analysis updates'); // Use new state instead
            // Mark all tabs as failed for AI insights
            setTabAnalysisStatus(prev => {
              const newStatus = {};
              Object.keys(prev).forEach(tab => {
                newStatus[tab] = 'failed';
              });
              return newStatus;
            });
          };

        } catch (error) {
          console.error('Error analyzing data:', error);
          setAiInsightsError(error.message || 'Failed to analyze data'); // Use new state instead
          if (eventSource) {
            eventSource.close();
          }
          // Mark all tabs as failed for AI insights
          setTabAnalysisStatus(prev => {
            const newStatus = {};
            Object.keys(prev).forEach(tab => {
              newStatus[tab] = 'failed';
            });
            return newStatus;
          });
        }
      }
    };

    startAnalysis();

    // Cleanup function
    return () => {
      isFirstRender.current = false;
    };
  }, [results]);

  const handleTabChange = (event, newValue) => {
    setActiveTab(newValue);
  };

  const renderContent = () => {
    if (!results) return null;

    return (
      <Box
        sx={{
          display: 'flex',
          flexDirection: 'column',
          height: '100%',
          width: '100%',
          overflow: 'hidden',
          px: { xs: 2, sm: 3, md: 4 },
        }}
      >
        <Fade in={true}>
          <Paper
            elevation={0}
            variant="outlined"
            sx={{
              p: { xs: 2, sm: 3 },
              mb: 3,
              background: `linear-gradient(45deg, 
                ${theme.palette.background.paper} 0%,
                ${theme.palette.background.default} 100%)`,
              flexShrink: 0,
              borderRadius: 2,
              boxShadow: 1,
            }}
          >
            <Stack
              direction={{ xs: 'column', sm: 'row' }}
              alignItems={{ xs: 'flex-start', sm: 'center' }}
              spacing={{ xs: 2, sm: 3 }}
              sx={{ mb: { xs: 2, sm: 0 } }}
            >
              <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                <BarChartIcon color="primary" sx={{ fontSize: { xs: 24, sm: 32 } }} />
                <Box>
                  <Typography variant="h5" sx={{ fontSize: { xs: '1.25rem', sm: '1.5rem' } }}>
                    {isBenchmarkMode ? 'Benchmark Comparison' : 'Portfolio Comparison'}
                  </Typography>
                  <Stack
                    direction="row"
                    spacing={1}
                    alignItems="center"
                    sx={{
                      flexWrap: 'wrap',
                      gap: 0.5,
                    }}
                  >
                    <Chip
                      label={mainPortfolioName}
                      color="primary"
                      variant="outlined"
                      size="small"
                      icon={<ShowChartIcon />}
                    />
                    {comparisonPortfolio && (
                      <>
                        <CompareIcon fontSize="small" color="action" />
                        <Chip
                          label={comparisonPortfolio}
                          color="secondary"
                          variant="outlined"
                          size="small"
                          icon={<ShowChartIcon />}
                        />
                      </>
                    )}
                  </Stack>
                </Box>
              </Box>
              <Divider orientation="vertical" flexItem sx={{ display: { xs: 'none', sm: 'block' } }} />
              <Box sx={{ display: 'flex', gap: 3, flexWrap: 'wrap' }}>
                <Box>
                  <Typography variant="caption" color="text.secondary" display="block">
                    Analysis Period
                  </Typography>
                  <Typography variant="body2" sx={{ fontWeight: 500 }}>
                    {formatDate(data_quality?.date_range?.start)} - {formatDate(data_quality?.date_range?.end)}
                  </Typography>
                </Box>
                <Box>
                  <Typography variant="caption" color="text.secondary" display="block">
                    Data Points
                  </Typography>
                  <Typography variant="body2" sx={{ fontWeight: 500 }}>
                    {data_quality?.num_data_points?.toLocaleString()}
                  </Typography>
                </Box>
              </Box>
            </Stack>
          </Paper>
        </Fade>

        <Paper
          elevation={0}
          variant="outlined"
          sx={{
            mb: 3,
            flexShrink: 0,
            overflow: 'auto',
            borderRadius: 2,
            mx: { xs: 0, sm: 0 },
            boxShadow: 1,
          }}
        >
          <Tabs
            value={activeTab}
            onChange={handleTabChange}
            variant="scrollable"
            scrollButtons={false}
            allowScrollButtonsMobile={false}
            sx={{
              borderBottom: 1,
              borderColor: 'divider',
              '& .MuiTabs-scroller': {
                overflow: 'auto !important',
                '&::-webkit-scrollbar': {
                  height: 6,
                },
                '&::-webkit-scrollbar-track': {
                  backgroundColor: 'transparent',
                },
                '&::-webkit-scrollbar-thumb': {
                  backgroundColor: theme.palette.divider,
                  borderRadius: 3,
                  '&:hover': {
                    backgroundColor: theme.palette.action.hover,
                  },
                },
              },
              '& .MuiTab-root': {
                minHeight: { xs: 60, sm: 72 },
                p: { xs: 1, sm: 2 },
                minWidth: { xs: 'auto', sm: 200 },
                whiteSpace: 'nowrap',
              },
            }}
          >
            {tabs.map((tab, index) => (
              <Tab
                key={tab.label}
                icon={
                  <Box
                    sx={{
                      p: 1,
                      borderRadius: 1,
                      bgcolor: `${tab.color}15`,
                      color: tab.color,
                    }}
                  >
                    <tab.icon />
                  </Box>
                }
                label={
                  <Box
                    sx={{
                      textAlign: 'left',
                      ml: 1,
                      width: '100%',
                    }}
                  >
                    <Typography
                      variant="body2"
                      component="div"
                      sx={{
                        fontWeight: 500,
                        fontSize: { xs: '0.875rem', sm: '1rem' },
                      }}
                    >
                      {tab.label}
                    </Typography>
                    <Typography
                      variant="caption"
                      color="text.secondary"
                      component="div"
                      sx={{
                        maxWidth: { xs: '100%', sm: 200 },
                        whiteSpace: 'normal',
                        lineHeight: 1.2,
                        display: { xs: 'none', sm: 'block' },
                      }}
                    >
                      {tab.description}
                    </Typography>
                  </Box>
                }
                sx={{
                  flexDirection: 'row',
                  alignItems: 'center',
                  width: 'auto',
                }}
              />
            ))}
          </Tabs>
        </Paper>

        <Box
          sx={{
            flexGrow: 1,
            overflow: 'auto',
            minHeight: 0,
            px: { xs: 0, sm: 0 },
          }}
        >
          <Fade in={true} key={activeTab}>
            <Box position="relative">
              {tabs.map((tab, index) =>
                activeTab === index ? (
                  <React.Fragment key={tab.label}>
                    {/* Show loader only if this specific tab is analyzing and has no results yet */}
                    {tabAnalysisStatus[tab.label] === 'analyzing' && !analysisResults[tab.label] && (
                      <Box sx={{ mb: 3 }}>
                        <AIInsightsLoader isAnalyzing={true} />
                      </Box>
                    )}
                    
                    <tab.component
                      comparison={comparison}
                      dates={data_quality}
                      mode={mode}
                      correlations={
                        tab.label === 'Correlation Analysis'
                          ? comparison[Object.keys(comparison)[0]]?.correlations
                          : correlations
                      }
                      comparisonPortfolios={Object.entries(comparison)
                        .filter(([name]) => name !== Object.keys(comparison)[0])
                        .map(([name, data]) => ({
                          name,
                          correlations: data.correlations,
                          portfolio: data.portfolio,
                        }))}
                      analysis={analysisResults[tab.label]}
                      isAnalyzing={
                        tabAnalysisStatus[tab.label] === 'analyzing' && 
                        !analysisResults[tab.label]
                      }
                    />
                  </React.Fragment>
                ) : null
              )}
            </Box>
          </Fade>
        </Box>
      </Box>
    );
  };

  return (
    <React.Fragment>
      {renderContent()}
      {aiInsightsError && (
        <Alert 
          severity="warning" 
          sx={{ 
            position: 'fixed', 
            bottom: 16, 
            right: 16, 
            maxWidth: '400px',
            boxShadow: 2 
          }}
        >
          AI Insights unavailable: {aiInsightsError}
        </Alert>
      )}
    </React.Fragment>
  );
}

export default ResultsSection;

Note: Single portfolio will be treated as a benchmark in the backtest system.
when two portfolio is both Benchmark Portfolio show the note to the user in a proper way so he knows
return me full updated code