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 }) {
  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'

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

  const portfolioNames = Object.keys(comparison)
  const mainPortfolio = portfolioNames[0]
  const comparisonPortfolio = portfolioNames[1]

  const showCorrelation = correlations && Object.keys(correlations.pearson.matrix).length > 1
  const tabs = [
    { 
      label: 'Overview', 
      component: PortfolioOverview,
      icon: ShowChartIcon,
      description: 'Key performance metrics and portfolio growth',
      color: theme.palette.primary.main
    },
    ...(showCorrelation ? [{
      label: 'Correlation Analysis',
      component: CorrelationAnalysis,
      icon: CompareIcon,
      description: 'Asset correlation and diversification analysis',
      color: theme.palette.info.main
    }] : []),
    { 
      label: 'Rebalancing Analysis',
      component: RebalancingAnalysis,
      icon: TimelineIcon,
      description: 'Impact of different rebalancing strategies',
      color: theme.palette.success.main
    },
    { 
      label: 'Drawdown Analysis',
      component: DrawdownAnalysis,
      icon: TrendingDownIcon,
      description: 'Analysis of significant portfolio declines',
      color: theme.palette.warning.main
    },
    { 
      label: 'Attribution Analysis',
      component: AttributionAnalysis,
      icon: AssessmentIcon,
      description: 'Performance attribution and factor analysis',
      color: theme.palette.secondary.main
    }
  ]

  return (
    <Box sx={{ height: '100%', overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
      <Fade in={true}>
        <Paper 
          elevation={0} 
          variant="outlined"
          sx={{ 
            p: 3, 
            mb: 3,
            background: `linear-gradient(45deg, 
              ${theme.palette.background.paper} 0%,
              ${theme.palette.background.default} 100%)`
          }}
        >
          <Stack direction="row" alignItems="center" spacing={3}>
            <BarChartIcon color="primary" sx={{ fontSize: 32 }} />
            <Box>
              <Typography variant="h5" gutterBottom>
                {isBenchmarkMode ? 'Benchmark Comparison' : 'Portfolio Comparison'}
              </Typography>
              <Stack direction="row" spacing={1} alignItems="center">
                <Chip 
                  label={mainPortfolio}
                  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>
            <Divider orientation="vertical" flexItem />
            <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>
          </Stack>
        </Paper>
      </Fade>

      {data_quality?.missing_values && (
        <Alert 
          severity="warning" 
          variant="outlined"
          sx={{ mb: 3 }}
        >
          Some data points are missing in the analysis period. Results may be affected.
        </Alert>
      )}

      <Paper 
        elevation={0} 
        variant="outlined"
        sx={{ mb: 3 }}
      >
        <Tabs 
          value={activeTab} 
          onChange={handleTabChange}
          variant="scrollable"
          scrollButtons="auto"
          sx={{
            borderBottom: 1,
            borderColor: 'divider',
            '& .MuiTab-root': {
              minHeight: 72,
              p: 2
            }
          }}
        >
          {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 }}>
                  <Typography variant="body2" component="div" sx={{ fontWeight: 500 }}>
                    {tab.label}
                  </Typography>
                  <Typography 
                    variant="caption" 
                    color="text.secondary" 
                    component="div"
                    sx={{ 
                      maxWidth: 200,
                      whiteSpace: 'normal',
                      lineHeight: 1.2
                    }}
                  >
                    {tab.description}
                  </Typography>
                </Box>
              }
              sx={{ 
                flexDirection: 'row',
                alignItems: 'center'
              }}
            />
          ))}
        </Tabs>
      </Paper>

      <Box sx={{ flex: 1, overflow: 'auto' }}>
        <Fade in={true} key={activeTab}>
          <Box>
            {tabs.map((tab, index) => (
              activeTab === index && (
                <tab.component
                  key={tab.label}
                  comparison={comparison}
                  dates={dates}
                  mode={mode}
                  correlations={correlations}
                />
              )
            ))}
          </Box>
        </Fade>
      </Box>
    </Box>
  )
}

export default ResultsSection


fix the scrolling for me as I cannot view some content and also cannot scroll, enhance it and return full updated code