import React from 'react'
import { Box, Grid, Paper, Typography, Divider, Tooltip, IconButton, Stack, Chip, useTheme } from '@mui/material'
import { formatPercent, formatCurrency } from '../../utils'
import PortfolioChart from './PortfolioChart'
import InfoOutlinedIcon from '@mui/icons-material/InfoOutlined'
import ShowChartIcon from '@mui/icons-material/ShowChart'
import TimelineIcon from '@mui/icons-material/Timeline'
import AssessmentIcon from '@mui/icons-material/Assessment'
import TrendingUpIcon from '@mui/icons-material/TrendingUp'
import TrendingDownIcon from '@mui/icons-material/TrendingDown'
import HelpOutlineIcon from '@mui/icons-material/HelpOutline'
import { alpha } from '@mui/material/styles'

const METRIC_DESCRIPTIONS = {
  'Annualized Return': 'The geometric mean of returns expressed as a yearly percentage (CAGR)',
  'Information Ratio': 'Measures portfolio returns above the benchmark relative to tracking error',
  'Alpha': 'Excess return of the investment relative to the benchmark',
  'Beta': 'Measure of volatility compared to the benchmark',
  'Volatility': 'Standard deviation of returns, annualized',
  'Maximum Drawdown': 'Largest peak-to-trough decline',
  'Sharpe Ratio': 'Risk-adjusted return relative to risk-free rate',
  'Sortino Ratio': 'Risk-adjusted return focusing on downside volatility',
  'Up Capture': 'Performance relative to benchmark during up markets',
  'Down Capture': 'Performance relative to benchmark during down markets',
  'R-Squared': 'Percentage of portfolio returns explained by benchmark movements',
  'Tracking Error': 'Standard deviation of excess returns relative to benchmark',
  'VaR (95%)': 'Value at Risk - Maximum expected loss with 95% confidence over a one-day period',
  'CVaR (95%)': 'Conditional Value at Risk - Expected loss when losses exceed VaR (95%)',
  'Skewness': 'Measure of return distribution asymmetry',
  'Kurtosis': 'Measure of return distribution tail thickness',
  'Active Return': 'Difference between portfolio return and benchmark return',
  'Rolling Volatility': '30-day rolling standard deviation of returns',
  'Rolling Returns': 'Returns calculated over different time periods',
  'Up/Down Markets': 'Performance in rising vs falling market conditions',
  'Turnover': 'Percentage of portfolio value that is traded annually',
  'Cost Impact': 'Effect of transaction costs on portfolio performance',
  'Weight Drift': 'How much portfolio weights deviate from targets over time',
  'Benchmark Type': 'Whether this is a benchmark portfolio (single asset) or active portfolio (multiple assets)'
}

function PortfolioOverview({ comparison, dates, mode }) {
  const theme = useTheme()
  const portfolioNames = Object.keys(comparison)
  const mainPortfolio = portfolioNames[0]
  const benchmarkPortfolio = portfolioNames[1]

  const mainMetrics = comparison[mainPortfolio].metrics
  const benchmarkMetrics = benchmarkPortfolio ? comparison[benchmarkPortfolio].metrics : null
  const isBenchmarkMode = mode === 'benchmark' && benchmarkPortfolio === 'SPY'

  const isValidValue = (value) => {
    return value !== undefined && 
           value !== null && 
           !isNaN(value) && 
           isFinite(value)
  }

  const renderMetricWithTooltip = (label, value, color = 'inherit') => {
    let displayValue = 'N/A'
    if (isValidValue(value)) {
      if (typeof value === 'number') {
        if (label.includes('Ratio') || label.includes('Beta') || label === 'Skewness' || label === 'Kurtosis') {
          displayValue = value.toFixed(2)
        } else if (label.includes('VaR') || label.includes('CVaR')) {
          displayValue = formatPercent(Math.abs(value))  // Show absolute value
        } else if (label.includes('Cost') && !label.includes('%')) {
          displayValue = formatCurrency(value)
        } else if (label.includes('Turnover') || label.includes('Drift')) {
          displayValue = formatPercent(value)
        } else {
          displayValue = formatPercent(value)
        }
      } else {
        displayValue = value.toString()
      }
    }

    return (
      <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5, mb: 1 }}>
        <Typography variant="body2" color="text.secondary">
          {label}
        </Typography>
        <Tooltip title={METRIC_DESCRIPTIONS[label] || ''} arrow placement="top">
          <IconButton size="small" sx={{ padding: 0 }}>
            <InfoOutlinedIcon fontSize="small" />
          </IconButton>
        </Tooltip>
        <Typography 
          variant="body1" 
          fontWeight="medium" 
          ml="auto" 
          color={
            label.includes('VaR') || label.includes('CVaR') || label.includes('Drawdown')
              ? 'error.main' 
              : label.includes('Up') || label.includes('Alpha') || label.includes('Return') > 0
                ? 'success.main'
                : color
          }
        >
          {displayValue}
        </Typography>
      </Box>
    )
  }

  const renderRiskMetrics = (metrics) => (
    <Box sx={{ mt: 2 }}>
      <Typography variant="subtitle2" gutterBottom color="text.secondary">
        Risk Metrics
      </Typography>
      <Grid container spacing={2}>
        <Grid item xs={12} sm={6}>
          {renderMetricWithTooltip('VaR (95%)', metrics.var_95)}
          {renderMetricWithTooltip('CVaR (95%)', metrics.cvar_95)}
        </Grid>
        <Grid item xs={12} sm={6}>
          {renderMetricWithTooltip('Skewness', metrics.skewness)}
          {renderMetricWithTooltip('Kurtosis', metrics.kurtosis)}
        </Grid>
      </Grid>
    </Box>
  )

  const renderBenchmarkMetrics = (metrics) => (
    <Box sx={{ mt: 2 }}>
      <Typography variant="subtitle2" gutterBottom color="text.secondary">
        Benchmark Analysis
      </Typography>
      <Grid container spacing={2}>
        <Grid item xs={12} sm={6}>
          {renderMetricWithTooltip('Alpha', metrics.alpha)}
          {renderMetricWithTooltip('Beta', metrics.beta)}
          {renderMetricWithTooltip('R-Squared', metrics.r_squared)}
        </Grid>
        <Grid item xs={12} sm={6}>
          {renderMetricWithTooltip('Information Ratio', metrics.information_ratio)}
          {renderMetricWithTooltip('Tracking Error', metrics.tracking_error)}
          {renderMetricWithTooltip('Active Return', metrics.active_return)}
        </Grid>
      </Grid>
    </Box>
  )

  const renderCostAnalysis = (metrics, isSingleAsset) => {
    if (isSingleAsset) {
      return (
        <Box sx={{ mt: 2 }}>
          <Typography variant="subtitle2" gutterBottom color="text.secondary">
            Cost Analysis
          </Typography>
          <Typography variant="body2" color="text.secondary" sx={{ fontStyle: 'italic' }}>
            Cost analysis is not applicable for benchmark portfolios as they are not actively rebalanced.
          </Typography>
        </Box>
      )
    }

    return (
      <Box sx={{ mt: 2 }}>
        <Typography variant="subtitle2" gutterBottom color="text.secondary">
          Cost & Turnover Analysis
        </Typography>
        <Grid container spacing={2}>
          <Grid item xs={12} sm={6}>
            {renderMetricWithTooltip('Portfolio Turnover', metrics.avg_turnover)}
            {renderMetricWithTooltip('Transaction Costs', metrics.total_costs)}
          </Grid>
          <Grid item xs={12} sm={6}>
            {renderMetricWithTooltip('Cost Impact', metrics.cost_percentage)}
            {renderMetricWithTooltip('Weight Drift', metrics.weight_drift?.mean)}
          </Grid>
        </Grid>
      </Box>
    )
  }

  const renderPerformanceHighlights = (name, metrics) => (
    <Box sx={{ 
      p: 3, 
      borderRadius: 2,
      bgcolor: theme.palette.mode === 'dark' 
        ? alpha(theme.palette.primary.main, 0.1)
        : alpha(theme.palette.primary.light, 0.1)
    }}>
      <Grid container spacing={3}>
        <Grid item xs={12} sm={6} md={3}>
          <Box>
            <Typography variant="subtitle2" color="text.secondary">Total Return</Typography>
            <Typography variant="h6" color="primary.main">
              {formatPercent(metrics.total_return)}
            </Typography>
          </Box>
        </Grid>
        <Grid item xs={12} sm={6} md={3}>
          <Box>
            <Typography variant="subtitle2" color="text.secondary">CAGR</Typography>
            <Typography variant="h6" color="primary.main">
              {formatPercent(metrics.cagr)}
            </Typography>
          </Box>
        </Grid>
        <Grid item xs={12} sm={6} md={3}>
          <Box>
            <Typography variant="subtitle2" color="text.secondary">Max Drawdown</Typography>
            <Typography variant="h6" color="error.main">
              {formatPercent(metrics.max_drawdown)}
            </Typography>
          </Box>
        </Grid>
        <Grid item xs={12} sm={6} md={3}>
          <Box>
            <Typography variant="subtitle2" color="text.secondary">Sharpe Ratio</Typography>
            <Typography variant="h6">
              {metrics.sharpe_ratio.toFixed(2)}
            </Typography>
          </Box>
        </Grid>
      </Grid>
    </Box>
  )

  const renderPortfolioType = (portfolio) => {
    const isSingleAsset = portfolio?.portfolio?.length === 1
    return (
      <Box sx={{ mb: 2 }}>
        <Chip
          icon={isSingleAsset ? <ShowChartIcon /> : <AssessmentIcon />}
          label={isSingleAsset ? 'Benchmark Portfolio' : 'Active Portfolio'}
          color={isSingleAsset ? 'secondary' : 'primary'}
          variant="outlined"
          size="small"
          sx={{ mr: 1 }}
        />
        <Tooltip title={
          isSingleAsset 
            ? "Single-asset portfolios are treated as benchmarks for comparison purposes" 
            : "Multi-asset portfolios are actively managed with rebalancing options"
        } arrow>
          <IconButton size="small">
            <HelpOutlineIcon fontSize="small" />
          </IconButton>
        </Tooltip>
      </Box>
    )
  }

  const renderRollingMetrics = (metrics) => {
    // Safely access rolling returns
    const rollingReturns = metrics.rolling_returns || {}
    
    return (
      <Box sx={{ mt: 2 }}>
        <Typography variant="subtitle2" gutterBottom color="text.secondary">
          Rolling Analysis
        </Typography>
        <Grid container spacing={2}>
          <Grid item xs={12} sm={6}>
            {renderMetricWithTooltip('1M Rolling Return', rollingReturns['1M'])}
            {renderMetricWithTooltip('3M Rolling Return', rollingReturns['3M'])}
          </Grid>
          <Grid item xs={12} sm={6}>
            {renderMetricWithTooltip('6M Rolling Return', rollingReturns['6M'])}
            {renderMetricWithTooltip('1Y Rolling Return', rollingReturns['1Y'])}
          </Grid>
        </Grid>
      </Box>
    )
  }

  const renderMarketBehavior = (metrics) => (
    <Box sx={{ mt: 2 }}>
      <Typography variant="subtitle2" gutterBottom color="text.secondary">
        Market Behavior
      </Typography>
      <Grid container spacing={2}>
        <Grid item xs={12} sm={6}>
          {renderMetricWithTooltip('Up Market Capture', metrics.up_capture, 'success.main')}
          {renderMetricWithTooltip('Down Market Capture', metrics.down_capture, 'error.main')}
        </Grid>
        <Grid item xs={12} sm={6}>
          {renderMetricWithTooltip('Active Return', metrics.active_return)}
          {renderMetricWithTooltip('Tracking Error', metrics.tracking_error)}
        </Grid>
      </Grid>
    </Box>
  )

  const renderComparisonSummary = () => (
    <Paper sx={{ p: 3, mb: 3 }}>
      <Typography variant="h6" gutterBottom>
        Performance Comparison Summary
      </Typography>
      <Grid container spacing={3}>
        {Object.entries(comparison).map(([name, data]) => {
          const metrics = data.metrics
          const isSingleAsset = data.portfolio.length === 1
          
          return (
            <Grid item xs={12} md={6} key={name}>
              <Box sx={{ 
                p: 2, 
                borderRadius: 2,
                bgcolor: theme.palette.mode === 'dark' 
                  ? alpha(isSingleAsset ? theme.palette.secondary.main : theme.palette.primary.main, 0.1)
                  : alpha(isSingleAsset ? theme.palette.secondary.light : theme.palette.primary.light, 0.1),
                border: `1px solid ${isSingleAsset ? theme.palette.secondary.main : theme.palette.primary.main}`,
              }}>
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 2 }}>
                  {isSingleAsset ? <ShowChartIcon color="secondary" /> : <AssessmentIcon color="primary" />}
                  <Typography variant="subtitle1" color={isSingleAsset ? 'secondary' : 'primary'}>
                    {name}
                  </Typography>
                  {renderPortfolioType(data)}
                </Box>

                <Grid container spacing={2}>
                  <Grid item xs={6}>
                    <Typography variant="caption" color="text.secondary">Total Return</Typography>
                    <Typography variant="h6" color={isSingleAsset ? 'secondary' : 'primary'}>
                      {formatPercent(metrics.total_return)}
                    </Typography>
                  </Grid>
                  <Grid item xs={6}>
                    <Typography variant="caption" color="text.secondary">CAGR</Typography>
                    <Typography variant="h6" color={isSingleAsset ? 'secondary' : 'primary'}>
                      {formatPercent(metrics.cagr)}
                    </Typography>
                  </Grid>
                  <Grid item xs={6}>
                    <Typography variant="caption" color="text.secondary">Volatility</Typography>
                    <Typography variant="body1">
                      {formatPercent(metrics.annual_volatility)}
                    </Typography>
                  </Grid>
                  <Grid item xs={6}>
                    <Typography variant="caption" color="text.secondary">Sharpe Ratio</Typography>
                    <Typography variant="body1">
                      {metrics.sharpe_ratio.toFixed(2)}
                    </Typography>
                  </Grid>
                </Grid>
              </Box>
            </Grid>
          )
        })}
      </Grid>
    </Paper>
  )

  const renderRelativePerformance = () => {
    if (!benchmarkMetrics || !mainMetrics) return null
    
    const relativeDifference = (metric) => {
      if (!isValidValue(mainMetrics[metric]) || !isValidValue(benchmarkMetrics[metric])) return null
      return (mainMetrics[metric] / benchmarkMetrics[metric] - 1)
    }

    return (
      <Paper sx={{ p: 3, mb: 3 }}>
        <Typography variant="h6" gutterBottom>
          Relative Performance Analysis
        </Typography>
        <Grid container spacing={2}>
          {[
            { label: 'Return', metric: 'cagr', icon: <TrendingUpIcon /> },
            { label: 'Risk', metric: 'annual_volatility', icon: <TimelineIcon /> },
            { label: 'Risk-Adjusted', metric: 'sharpe_ratio', icon: <AssessmentIcon /> }
          ].map(({ label, metric, icon }) => {
            const diff = relativeDifference(metric)
            return (
              <Grid item xs={12} sm={4} key={metric}>
                <Box sx={{ 
                  p: 2, 
                  borderRadius: 2,
                  bgcolor: 'background.default'
                }}>
                  <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 1 }}>
                    {icon}
                    <Typography variant="subtitle2">{label} Comparison</Typography>
                  </Box>
                  <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
                    <Typography variant="body2" color="text.secondary">
                      vs Benchmark
                    </Typography>
                    <Typography 
                      variant="h6" 
                      color={diff > 0 ? 'success.main' : diff < 0 ? 'error.main' : 'text.primary'}
                    >
                      {diff !== null ? formatPercent(diff) : 'N/A'}
                    </Typography>
                  </Box>
                </Box>
              </Grid>
            )
          })}
        </Grid>
      </Paper>
    )
  }

  const renderRiskAnalysis = (name, metrics, isSingleAsset) => (
    <Paper sx={{ p: 3, mb: 3 }}>
      <Box sx={{ 
        display: 'flex', 
        alignItems: 'center', 
        justifyContent: 'space-between',
        mb: 2 
      }}>
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
          <TimelineIcon color={isSingleAsset ? "secondary" : "primary"} />
          <Typography variant="h6">
            {name} - Risk Analysis
          </Typography>
        </Box>
        {renderPortfolioType({ portfolio: { length: isSingleAsset ? 1 : 2 }})}
      </Box>

      <Grid container spacing={3}>
        {/* Distribution Metrics */}
        <Grid item xs={12} md={4}>
          <Box sx={{ p: 2, bgcolor: 'background.default', borderRadius: 2 }}>
            <Typography variant="subtitle2" gutterBottom>Risk Distribution</Typography>
            <Grid container spacing={2}>
              <Grid item xs={6}>
                {renderMetricWithTooltip('VaR (95%)', metrics.var_95)}
                {renderMetricWithTooltip('CVaR (95%)', metrics.cvar_95)}
              </Grid>
              <Grid item xs={6}>
                {renderMetricWithTooltip('Skewness', metrics.skewness)}
                {renderMetricWithTooltip('Kurtosis', metrics.kurtosis)}
              </Grid>
            </Grid>
          </Box>
        </Grid>

        {/* Rolling Returns */}
        <Grid item xs={12} md={4}>
          <Box sx={{ p: 2, bgcolor: 'background.default', borderRadius: 2 }}>
            <Typography variant="subtitle2" gutterBottom>Rolling Returns</Typography>
            {renderRollingMetrics(metrics)}
          </Box>
        </Grid>

        {/* Risk Ratios */}
        <Grid item xs={12} md={4}>
          <Box sx={{ p: 2, bgcolor: 'background.default', borderRadius: 2 }}>
            <Typography variant="subtitle2" gutterBottom>Risk Ratios</Typography>
            {renderMetricWithTooltip('Sharpe Ratio', metrics.sharpe_ratio)}
            {renderMetricWithTooltip('Sortino Ratio', metrics.sortino_ratio)}
            {renderMetricWithTooltip('Information Ratio', metrics.information_ratio)}
            {renderMetricWithTooltip('Beta', metrics.beta)}
          </Box>
        </Grid>
      </Grid>
    </Paper>
  )

  const renderMarketAnalysis = () => (
    <Paper sx={{ p: 3, mt: 3 }}>
      <Typography variant="h6" gutterBottom>Market Behavior Analysis</Typography>
      <Grid container spacing={3}>
        {/* Market Capture */}
        <Grid item xs={12} md={6}>
          <Box sx={{ p: 2, bgcolor: 'background.default', borderRadius: 2 }}>
            <Typography variant="subtitle2" gutterBottom>Market Capture</Typography>
            {renderMarketBehavior(mainMetrics)}
          </Box>
        </Grid>

        {/* Benchmark Analysis */}
        <Grid item xs={12} md={6}>
          <Box sx={{ p: 2, bgcolor: 'background.default', borderRadius: 2 }}>
            <Typography variant="subtitle2" gutterBottom>Benchmark Analysis</Typography>
            {renderBenchmarkMetrics(mainMetrics)}
          </Box>
        </Grid>
      </Grid>
    </Paper>
  )

  const renderDataQualityInfo = () => (
    <Box sx={{ mt: 2, display: 'flex', gap: 2, justifyContent: 'flex-end' }}>
      <Chip
        icon={<TimelineIcon />}
        label={`${dates?.num_data_points || 0} Data Points`}
        variant="outlined"
        size="small"
      />
      <Chip
        icon={<ShowChartIcon />}
        label={`${dates?.date_range?.start} - ${dates?.date_range?.end}`}
        variant="outlined"
        size="small"
      />
    </Box>
  )

  return (
    <Box>
      {/* Header */}
      <Box sx={{ mb: 4 }}>
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 2 }}>
          <ShowChartIcon color="primary" />
          <Typography variant="h5">Performance Analysis</Typography>
          <Tooltip title="Comprehensive analysis of portfolio performance and risk metrics" arrow>
            <IconButton size="small">
              <InfoOutlinedIcon fontSize="small" />
            </IconButton>
          </Tooltip>
        </Box>
        <Typography variant="body2" color="text.secondary">
          Compare performance, risk metrics, and market behavior across portfolios
        </Typography>
      </Box>

      {/* Performance Summary */}
      {renderComparisonSummary()}

      {/* Relative Performance */}
      {isBenchmarkMode && renderRelativePerformance()}

      {/* Individual Portfolio Analysis */}
      {Object.entries(comparison).map(([name, data]) => (
        <React.Fragment key={name}>
          {renderRiskAnalysis(name, data.metrics, data.portfolio.length === 1)}
        </React.Fragment>
      ))}

      {/* Portfolio Growth Chart */}
      <Paper sx={{ p: 3 }}>
        <Box sx={{ 
          display: 'flex', 
          justifyContent: 'space-between', 
          alignItems: 'center',
          mb: 2
        }}>
          <Typography variant="h6">Portfolio Growth</Typography>
          {renderDataQualityInfo()}
        </Box>
        <PortfolioChart 
          results={{ 
            comparison: comparison,
            data_quality: dates
          }} 
        />
      </Paper>

      {/* Market Analysis */}
      {isBenchmarkMode && mainMetrics && renderMarketAnalysis()}
    </Box>
  )
}

export default PortfolioOverview

// ResultsSection.js
import { 
  Box, 
  Paper, 
  Typography, 
  Tabs, 
  Tab, 
  Alert, 
  Fade, 
  Chip, 
  Stack, 
  Divider, 
  useTheme 
} from '@mui/material';
import { useState } from 'react';
import PortfolioOverview from './results/PortfolioOverview';
import CorrelationAnalysis from './results/CorrelationAnalysis';
import RebalancingAnalysis from './results/RebalancingAnalysis';
import DrawdownAnalysis from './results/DrawdownAnalysis';
import AttributionAnalysis from './results/AttributionAnalysis';
import CompareIcon from '@mui/icons-material/Compare';
import TimelineIcon from '@mui/icons-material/Timeline';
import BarChartIcon from '@mui/icons-material/BarChart';
import ShowChartIcon from '@mui/icons-material/ShowChart';
import TrendingDownIcon from '@mui/icons-material/TrendingDown';
import AssessmentIcon from '@mui/icons-material/Assessment';
import { formatDate } from '../utils';

function ResultsSection({ results, comparisonPortfolios, onRemoveComparison }) {
  const [activeTab, setActiveTab] = useState(0);
  const theme = useTheme();

  if (!results) return null;

  const { comparison, dates, correlations, data_quality } = results;
  const mode = data_quality?.mode || 'portfolio_comparison';
  const isBenchmarkMode = mode === 'benchmark';

  console.log('ResultsSection data_quality:', data_quality);

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

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

  const showCorrelation = correlations && 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
    },
    ...(showCorrelation ? [{
      label: 'Correlation Analysis',
      component: CorrelationAnalysis,
      icon: CompareIcon,
      description: 'Asset relationships and diversification',
      color: theme.palette.info.main
    }] : []),
    { 
      label: 'Rebalancing Analysis',
      component: RebalancingAnalysis,
      icon: TimelineIcon,
      description: 'Portfolio rebalancing strategies',
      color: theme.palette.success.main
    },
    { 
      label: 'Drawdown Analysis',
      component: DrawdownAnalysis,
      icon: TrendingDownIcon,
      description: 'Historical portfolio declines',
      color: theme.palette.warning.main
    },
    { 
      label: 'Attribution Analysis',
      component: AttributionAnalysis,
      icon: AssessmentIcon,
      description: 'Performance drivers and factors',
      color: theme.palette.secondary.main
    }
  ];

  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
          }}
        >
          <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 }
        }}
      >
        <Tabs 
          value={activeTab} 
          onChange={handleTabChange}
          variant="scrollable"
          scrollButtons="auto"
          allowScrollButtonsMobile
          sx={{
            borderBottom: 1,
            borderColor: 'divider',
            '& .MuiTab-root': {
              minHeight: { xs: 60, sm: 72 },
              p: { xs: 1, sm: 2 },
              minWidth: { xs: '100%', sm: 'auto' }
            },
            '& .MuiTabs-scrollButtons': {
              display: { xs: 'flex', sm: 'none' }
            }
          }}
        >
          {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: '100%'
              }}
            />
          ))}
        </Tabs>
      </Paper>

      <Box 
        sx={{ 
          flexGrow: 1, 
          overflow: 'auto', 
          minHeight: 0,
          px: { xs: 0, sm: 0 }
        }}
      >
        <Fade in={true} key={activeTab}>
          <Box>
            {tabs.map((tab, index) => (
              activeTab === index && (
                <tab.component
                  key={tab.label}
                  comparison={comparison}
                  dates={data_quality}
                  mode={mode}
                  correlations={correlations}
                  comparisonPortfolios={Object.entries(comparison)
                    .filter(([name]) => name !== Object.keys(comparison)[0])
                    .map(([name, data]) => ({
                      name,
                      correlations: data.correlations,
                      portfolio: data.portfolio
                    }))}
                />
              )
            ))}
          </Box>
        </Fade>
      </Box>
    </Box>
  );
}

export default ResultsSection;

Performance Analysis
Compare performance, risk metrics, and market behavior across portfolios

Performance Comparison Summary
Current Portfolio
Active Portfolio
Total Return
195.19%
CAGR
24.21%
Volatility
27.03%

Sharpe Ratio
0.86

SPY
Benchmark Portfolio
Total Return
93.77%
CAGR
14.17%
Volatility
21.00%

Sharpe Ratio
0.64

Current Portfolio - Risk Analysis
Active Portfolio
Risk Distribution
VaR (95%)

2.45%

CVaR (95%)

4.07%

Skewness

-0.54

Kurtosis

5.96

Rolling Returns
Rolling Analysis
1M Rolling Return

-0.46%

3M Rolling Return

6.51%

6M Rolling Return

18.83%

1Y Rolling Return

49.54%

Risk Ratios
Sharpe Ratio

0.86

Sortino Ratio

1.22

Information Ratio

0.63

Beta

1.04

SPY - Risk Analysis
Benchmark Portfolio
Risk Distribution
VaR (95%)

1.87%

CVaR (95%)

3.19%

Skewness

-0.55

Kurtosis

11.48

Rolling Returns
Rolling Analysis
1M Rolling Return

3.31%

3M Rolling Return

10.46%

6M Rolling Return

14.95%

1Y Rolling Return

38.01%

Risk Ratios
Sharpe Ratio

0.64

Sortino Ratio

0.89

Information Ratio

0.00

Beta

1.00

Portfolio Growth
1258 Data Points
2019-11-12 - 2024-11-11
Portfolio Growth
Analysis Period
Nov 12, 2019 - Nov 11, 2024

Data Points
1,258

continue enhancing the existing portfolio overview components, I really like MUI, please enhance the interface more with MUI design and make it more user-friendly while the website more modern and good looking, return full updated code for both js