'use client';

import { useEffect, useState } from 'react';
import Grid from '@mui/material/Unstable_Grid2';
import Container from '@mui/material/Container';
import { useSettingsContext } from '@/shared/components/settings';
import AnalyticsConversionRates from './analytics-conversion-rates';
import AppTopCollaborator from './app-top-collaborator';
import { Stack, Card, CardHeader, Button, useTheme, Box, Typography } from '@mui/material';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns';
import { DesktopDatePicker } from '@mui/x-date-pickers';
import RewardWidgetSummary from './reward-widget-summary';
import axiosInstancee from '@/utils/axios';
import ConditionalComponent from '@/shared/components/ConditionalComponent';

export default function RewardAnalyticView({ rewardId }: { rewardId: number }) {
  const settings = useSettingsContext();
  const theme = useTheme();

  const [selectedDate, setSelectedDate] = useState<Date | null>(new Date());
  const [scoreSummary, setScoreSummary] = useState({ maxScore: 0, meanScore: 0, minScore: 0 });
  const [employeeScores, setEmployeeScores] = useState<any[]>([]); // Allow for debugging non-array responses
  const [topCollaborators, setTopCollaborators] = useState<any[]>([]);
  const [hasError, setHasError] = useState(false);

  useEffect(() => {
    const fetchScoreSummary = async () => {
      try {
        const { data } = await axiosInstancee.get(`/api/projects/${rewardId}/scores/summary`);
        
        setScoreSummary(data);
      } catch (error) {
        setHasError(true);
      }
    };


    const fetchEmployeeScores = async () => {
      try {
        const { data } = await axiosInstancee.get(`/api/projects/${rewardId}/scores/employees`);
        
        if (Array.isArray(data)) {
          setEmployeeScores(data);
        } else if (data && typeof data === 'object') {

          const scoresArray = Object.values(data);
        
          setEmployeeScores(scoresArray);
        } else {
          setEmployeeScores([]);
        }
      } catch (error) {
        

        setEmployeeScores([
          { employeeName: 'Test Employee 1', score: 5 },
          { employeeName: 'Test Employee 2', score: 3 },
        ]);
      }
    };


    const fetchTopCollaborators = async () => {
      try {
        const response = await axiosInstancee.get(`/api/projects/${rewardId}/top-collaborators`);
        setTopCollaborators(response.data);
      } catch (error: unknown) {
        setHasError(true);
      }
    };


    fetchScoreSummary();
    fetchEmployeeScores();
    fetchTopCollaborators();

  }, [rewardId]);

  return (
    <LocalizationProvider dateAdapter={AdapterDateFns}>
      <Container maxWidth={settings.themeStretch ? false : 'xl'}>
        <Stack spacing={1} direction={{ md: 'row', xs: 'column' }} sx={{ mb: 2 }}>
          <Grid xs={12} md={4}>
            <RewardWidgetSummary
              title="The maximum score"
              total={scoreSummary.maxScore}
              icon="mdi:arrow-top-right-bold-box"
              color={theme.palette.success.main}
            />
          </Grid>
          <Grid xs={12} md={4}>
            <RewardWidgetSummary
              title="The mean score"
              total={scoreSummary.meanScore}
              icon="covid:graph-cured-stable"
              color={theme.palette.info.main}
            />
          </Grid>
          <Grid xs={12} md={4}>
            <RewardWidgetSummary
              title="Minimum scores"
              total={scoreSummary.minScore}
              icon="mdi:arrow-bottom-left-bold-box"
              color={theme.palette.error.main}
            />
          </Grid>
        </Stack>
        <Grid container spacing={3}>
          <Grid xs={12} md={6} lg={8}>
            <Card>
              <CardHeader title="The grades obtained by each employee" />
              <Stack spacing={3} direction="row" sx={{ ml: 2, mt: 2 }}>
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  <DesktopDatePicker
                    label="Date"
                    value={selectedDate}
                    minDate={new Date('2017-01-01')}
                    onChange={(newValue) => setSelectedDate(newValue)}
                    slotProps={{
                      textField: { fullWidth: false },
                    }}
                  />
                </div>
              </Stack>

              <ConditionalComponent 
                isValid={Array.isArray(employeeScores) && employeeScores.length > 0}
                defaultComponent={
                  <Box sx={{ p: 3, textAlign: 'center' }}>
                    <Typography variant="body1" color="text.secondary">
                      No employee scores available for this reward.
                    </Typography>
                    <Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
                      This could be because no tasks have been assigned to employees yet,
                      or because the reward has not been fully processed.
                    </Typography>
                  </Box>
                }
              >
                <AnalyticsConversionRates
                  subheader="The scores for the reward"
                  chart={{
                    series: employeeScores.map((score) => ({
                      label: score.employeeName,
                      value: score.score,
                    })),
                  }}
                />
              </ConditionalComponent>
            </Card>
          </Grid>
          <Grid xs={12} md={6} lg={4} sx={{ display: 'flex', flexDirection: 'column' }}>
            <Card sx={{ flexGrow: 1 }}>
              <AppTopCollaborator title="Top Collaborators" list={topCollaborators} />
            </Card>
          </Grid>
        </Grid>
      </Container>
    </LocalizationProvider>
  );
}