'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 } 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';

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[]>([]);

  useEffect(() => {
    console.log('Fetching data for rewardId:', rewardId);

    // Fetch Score Summary
    const fetchScoreSummary = async () => {
      try {
        const { data } = await axiosInstancee.get(`/api/projects/${rewardId}/scores/summary`);
        console.log('Score Summary:', data);
        setScoreSummary(data);
      } catch (error) {
        console.error('Error fetching score summary:', error);
      }
    };

    // Fetch Employee Scores
    const fetchEmployeeScores = async () => {
      try {
        const { data } = await axiosInstancee.get(`/api/projects/${rewardId}/scores/employees`);
        console.log('Employee Scores:', data);
        setEmployeeScores(data);
      } catch (error) {
        console.error('Error fetching employee scores:', error);
      }
    };

    // Fetch Top Collaborators
    const fetchTopCollaborators = async () => {
      try {
        const response = await axiosInstancee.get(`/api/projects/${rewardId}/top-collaborators`);
        console.log('Response Status:', response.status);
        console.log('Response Headers:', response.headers);
        console.log('Top Collaborators Response Data:', response.data);
        setTopCollaborators(response.data);
      } catch (error: unknown) {
        console.error('Error fetching top collaborators:', error instanceof Error ? error.message : 'Unknown error');
        console.error('Full error object:', error);
      }
    };

    // Execute all fetches
    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>
              <AnalyticsConversionRates
                subheader="The scores for the reward"
                chart={{
                  series: Array.isArray(employeeScores)
                    ? employeeScores.map((score) => ({
                        label: score.employeeName,
                        value: score.score,
                      }))
                    : [],
                }}
              />
            </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>
  );
}