'use client';

import { useTheme } from '@mui/material/styles';
import Container from '@mui/material/Container';
import { useSettingsContext } from '@/shared/components/settings';
import ProjectAnalytic from './project-analytic-carte';
import { Autocomplete, Card, CardHeader, Divider, Grid, Stack, TextField } from '@mui/material';
import Scrollbar from '@/components/scrollbar';
import AnalyticsTasksDistribution from './analytics-task-distribution-status';
import AnalyticsTasksProgress from './analytics-task-progress';
import { DesktopDatePicker } from '@mui/x-date-pickers';
import { useState, useEffect } from 'react';
import TaskByGender from './analytics-task-by-type';
import TeamWorkload from './team-workload';
import { _teamWorkload } from '@/shared/_mock';
import { getProjectOverviewStats, getTaskDistributionStats, getTeamWorkloadStats, getTaskStatusDistribution, getTaskProgressStats } from '@/shared/api/project';
import axios from 'axios';
import { axiosInstance } from '@/utils/axios';
import { format } from 'date-fns';

type OverviewProjectViewPropsType = {
  projectId: number;
}

type ProjectStatsType = {
  done: number;
  updated: number;
  newTasks: number;
  due: number;
}

type DistributionStatsType = {
  bugs: number;
  features: number;
}

type StatusCountType = {
  status: string;
  count: number;
}

type UserInfoType = {
  user: {
    firstName: string;
    lastName: string;
  };
}

type WorkloadItemType = {
  collaboratorId: number;
  name: string | null;
  percentage: number;
  taskCount: number;
  rank: number;
}

type TaskProgressStatsType = {
  taskName: string;
  remainingDays: number;
  status: string;
}

type StatsType = {
  overview?: ProjectStatsType;
  distribution?: DistributionStatsType;
  statusDistribution?: StatusCountType[];
  workload?: WorkloadItemType[];
  taskProgress?: TaskProgressStatsType[];
}

// Add type options constant
const taskTypeOptions = ['All', 'BUG', 'FEATURE'];

// ----------------------------------------------------------------------

export default function OverviewProjectView({ projectId }: OverviewProjectViewPropsType) {
  const theme = useTheme();
  const settings = useSettingsContext();
  
  const [stats, setStats] = useState<StatsType>({});

  useEffect(() => {
    const fetchStats = async () => {
      try {
        const [overview, distributionData, workloadData, statusDist, taskProgress] = await Promise.all([
          getProjectOverviewStats(projectId),
          getTaskDistributionStats(projectId),
          getTeamWorkloadStats(projectId),
          getTaskStatusDistribution(projectId),
          getTaskProgressStats(projectId)
        ]);
        const workloadWithNames = await Promise.all(
          workloadData.map(async (item: WorkloadItemType) => {
            try {
              const userResponse = await axios.get(`${process.env.NEXT_PUBLIC_GATEWAY_API}/api/user/accountagency/id?Id=${item.collaboratorId}`);
              const userData: UserInfoType = userResponse.data;
              return {
                ...item,
                name: `${userData.user.firstName} ${userData.user.lastName}`
              };
            } catch (error) {
              console.error(`Error fetching user data for ID ${item.collaboratorId}:`, error);
              return item;
            }
          })
        );

        setStats({ 
          overview, 
          distribution: distributionData as DistributionStatsType,
          statusDistribution: statusDist,
          workload: workloadWithNames,
          taskProgress 
        });

      } catch (error) {
        console.error('Error fetching stats:', error);
      }
    };

    fetchStats();
  }, [projectId]);

  return (
    <Container maxWidth={settings.themeStretch ? false : 'xl'}>

      <Card
        sx={{
          mb: { xs: 2, md: 4 },
          ml:{md:-4,xs:-1}
        }}
      >
        <Scrollbar>
          <Stack
            direction="row"
            divider={<Divider orientation="vertical" flexItem sx={{ borderStyle: 'dashed' }} />}
            sx={{ py: 2 }}
          >
            <ProjectAnalytic
              title="Done"
              total={stats?.overview?.done || 0}
              icon="ic:baseline-file-download-done"
              color={theme.palette.success.main}
            />
            <ProjectAnalytic
              title="Updated"
              total={stats?.overview?.updated || 0}
              icon="clarity:edit-solid"
              color={theme.palette.info.main}
            />
            <ProjectAnalytic
              title="new"
              total={stats?.overview?.newTasks || 0}
              icon="mingcute:file-new-fill"
              color={theme.palette.grey[600]}
            />
            <ProjectAnalytic
              title="due"
              total={stats?.overview?.due || 0}
              icon="solar:bell-bing-bold-duotone"
              color={theme.palette.error.main}
            />
          </Stack>
        </Scrollbar>
      </Card>
      <Grid container spacing={2}>


        <Grid container spacing={2} sx={{ mt: 1 }}>
          <Grid item xs={12} md={6} lg={4}>
            <Card sx={{ml:{md:-2,xs:1}}}>
              <CardHeader title="Task distribution by Type" />
              <TaskByGender
                total={Number(stats?.distribution?.bugs || 0) + Number(stats?.distribution?.features || 0)}
                chart={{
                  series: [
                    { label: 'Bugs', value: Number(stats?.distribution?.bugs || 0) },
                    { label: 'Features', value: Number(stats?.distribution?.features || 0) },
                  ],
                }}
              />
            </Card>
          </Grid>

          <Grid item xs={12} md={6} lg={8} sx={{ display: 'flex', flexDirection: 'column' }}>
            <Card sx={{ flexGrow: 1,ml:{xs:1}}}>
              <CardHeader title="Your team's workload" />
              <TeamWorkload
                tableData={stats?.workload?.map(item => ({
                  id: item.collaboratorId.toString(),
                  name: item.name || 'Unknown',
                  email: '',
                  avatarUrl: '',
                  percent: item.percentage,
                  count: item.taskCount,
                  rank: item.rank.toString()
                })) || []}
                tableLabels={[
                  { id: 'name', label: 'Assignee' },
                  { id: 'percent', label: 'Percentage' },
                  { id: 'count', label: 'Count', align: 'right' },
                  { id: 'rank', label: 'Rank', align: 'right' },
                ]}
              />
            </Card>
          </Grid>
        </Grid>
        <Grid item xs={12} md={6} lg={6}>
          <Card sx={{ml:{md:-4,xs:-1}, height:'400px'}}>
            <CardHeader title="Task progress chart" />
            <AnalyticsTasksProgress
              series={[
                {
                  color: '#E72929',
                  name: 'Days Remaining',
                  data: stats?.taskProgress?.map(task => task.remainingDays) || [],
                  axis: stats?.taskProgress?.map(task => task.taskName) || [],
                }
              ]}
              searchValue={''}
            />
          
          </Card>
        </Grid>
        <Grid item xs={12} md={6} lg={6}>
          <Card sx={{ml:{xs:-1}}}>
            <CardHeader title="Task distribution by status" />
            <AnalyticsTasksDistribution
              chart={{
                series: stats?.statusDistribution?.map(item => ({
                  label: item.status,
                  value: item.count
                })) || []
              }}
            />
          </Card>
        </Grid>


      </Grid >

    </Container >
  );
}
