"use client";
import * as React from "react";
import Grid from "@mui/material/Grid";
import { useState, useEffect, useMemo } from "react";
import Paper from "@mui/material/Paper";
import { TFunction } from "i18next";
import { useTranslation } from "react-i18next";
import { Card, CardHeader } from "@mui/material";
import CustomSearchForm from "../CustomSearchForm/CustomSearchForm";
import CustomDatagrid from "../CustomDatagrid/CustomDatagrid";
import ReactApexChart from "react-apexcharts";
import { ApexOptions } from "apexcharts";
import { GridColDef, GridRowSelectionModel } from "@mui/x-data-grid";
import ReportProblemIcon from "@mui/icons-material/ReportProblem";
import dynamic from "next/dynamic";
import "../../app/global.css";
import { AnyARecord, AnyCnameRecord } from "dns";
import SearchBox, { Criterion } from "../SearchBox";
import ProgressByClientSearch from "@/components/ProgressByClientSearch";
import { Suspense } from "react";
import ProgressCashFlowSearch from "@/components/ProgressCashFlowSearch";
import { Input, Label } from "reactstrap";
import Select, { components } from "react-select";
import { DateCalendar } from "@mui/x-date-pickers/DateCalendar";
import { DatePicker } from "@mui/x-date-pickers/DatePicker";
import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import dayjs, { Dayjs } from "dayjs";
import isBetweenPlugin from "dayjs/plugin/isBetween";
import { PickersDay, PickersDayProps } from "@mui/x-date-pickers/PickersDay";
import { styled } from "@mui/material/styles";
import Holidays from "date-holidays";
import moment from "moment";
import { fetchTeamCombo, fetchweeklyTeamTotalManhours, fetchmonthlyTeamTotalManhours, fetchTotalManhoursByGrade, fetchWeeklyUnsubmit, fetchMonthlyUnsubmit, fetchStaffCombo, fetchDailyIndividualStaffManhours, fetchWeeklyIndividualStaffManhours, fetchMonthlyIndividualStaffManhours } from "@/app/api/staffUtilization";
import { SessionStaff } from "@/config/authConfig";
import { VIEW_DASHBOARD_ALL } from "@/middleware";
import { QrCode } from "@mui/icons-material";
import Typography from "@mui/material/Typography";

dayjs.extend(isBetweenPlugin);
interface CustomPickerDayProps extends PickersDayProps<Dayjs> {
  isSelected: boolean;
  isHovered: boolean;
}

const CustomPickersDay = styled(PickersDay, {
  shouldForwardProp: (prop) => prop !== "isSelected" && prop !== "isHovered",
})<CustomPickerDayProps>(({ theme, isSelected, isHovered, day }) => ({
  borderRadius: 0,
  ...(isSelected && {
    backgroundColor: theme.palette.primary.main,
    color: theme.palette.primary.contrastText,
    "&:hover, &:focus": {
      backgroundColor: theme.palette.primary.main,
    },
  }),
  ...(isHovered && {
    backgroundColor: theme.palette.primary[theme.palette.mode],
    "&:hover, &:focus": {
      backgroundColor: theme.palette.primary[theme.palette.mode],
    },
  }),
  ...(day.day() === 0 && {
    borderTopLeftRadius: "50%",
    borderBottomLeftRadius: "50%",
  }),
  ...(day.day() === 6 && {
    borderTopRightRadius: "50%",
    borderBottomRightRadius: "50%",
  }),
})) as React.ComponentType<CustomPickerDayProps>;

const isInSameWeek = (dayA: Dayjs, dayB: Dayjs | null | undefined) => {
  if (dayB == null) {
    return false;
  }

  return dayA.isSame(dayB, "week");
};

function Day(
  props: PickersDayProps<Dayjs> & {
    selectedDay?: Dayjs | null;
    hoveredDay?: Dayjs | null;
  },
) {
  const { day, selectedDay, hoveredDay, ...other } = props;

  return (
    <CustomPickersDay
      {...other}
      day={day}
      sx={{ px: 2.5 }}
      disableMargin
      selected={false}
      isSelected={isInSameWeek(day, selectedDay)}
      isHovered={isInSameWeek(day, hoveredDay)}
    />
  );
}

interface Props {
  abilities: string[];
  staff: SessionStaff;
}

const StaffUtilization: React.FC<Props> = ({ abilities, staff }) => {
  const { t } = useTranslation("dashboard");
  const abilityViewDashboardAll = abilities.includes(VIEW_DASHBOARD_ALL)

  const todayDate = new Date();
  const firstDayOfWeek = new Date();
  const lastDayOfWeek = new Date();
  firstDayOfWeek.setDate(todayDate.getDate() - todayDate.getDay() + 0);
  lastDayOfWeek.setDate(todayDate.getDate() - todayDate.getDay() + 6);
  const firstDayOfMonth = new Date(
    todayDate.getFullYear(),
    todayDate.getMonth(),
    1,
  );
  const lastDayOfMonth = new Date(
    todayDate.getFullYear(),
    todayDate.getMonth() + 1,
    0,
  );
  const [firstDayOfWeekString, setFirstDayOfWeekString] = React.useState(
    dayjs(firstDayOfWeek).format("DD MMM YYYY"),
  );
  const [lastDayOfWeekString, setLastDayOfWeekString] = React.useState(
    dayjs(lastDayOfWeek).format("DD MMM YYYY"),
  );
  const [firstDayOfMonthString, setFirstDayOfMonthString] = React.useState(
    dayjs(firstDayOfMonth).format("DD MMM YYYY"),
  );
  const [lastDayOfMonthString, setLastDayOfMonthString] = React.useState(
    dayjs(lastDayOfMonth).format("DD MMM YYYY"),
  );
  const [selectionModel, setSelectionModel]: any[] = React.useState([]);
  const [manHoursSpentPeriod, setManHoursSpentPeriod]: any[] = React.useState(
    firstDayOfWeekString + " to " + lastDayOfWeekString,
  );
  const [unsubmittedTimeSheetSelect, setUnsubmittedTimeSheetSelect]: any =
    React.useState("Monthly");
  const [teamTotalManhoursSpentSelect, setTeamTotalManhoursSpentSelect]: any =
    React.useState("Monthly");
  const [staffGradeManhoursSpentSelect, setStaffGradeManhoursSpentSelect]: any =
    React.useState("Monthly");
  const [
    individualStaffManhoursSpentSelect,
    setIndividualStaffManhoursSpentSelect,
  ]: any = React.useState("Monthly");
  const weekDates: any[] = [];
  const monthDates: any[] = [];
  const currentDate = dayjs();
  const sixMonthsAgo = currentDate.subtract(6, "month");
  for (let i = 0; i < 7; i++) {
    const currentDate = new Date(firstDayOfWeek);
    currentDate.setDate(firstDayOfWeek.getDate() + i);
    const formattedDate = dayjs(currentDate).format("DD MMM (ddd)");
    weekDates.push(formattedDate);
  }
  for (
    let date = sixMonthsAgo.clone();
    date.isBefore(currentDate, "month");
    date = date.add(1, "month")
  ) {
    monthDates.push(date.format("MM-YYYY"));
  }
  monthDates.push(currentDate.format("MM-YYYY"));
  //   for (let i = firstDayOfMonth.getDate(); i <= lastDayOfMonth.getDate(); i++) {
  //     const currentDate = new Date(todayDate.getFullYear(), todayDate.getMonth(), i);
  //     const formattedDate = dayjs(currentDate).format('DD MMM');
  //     monthDates.push(formattedDate);
  // }
  const [teamTotalManhoursSpentPeriod, setTeamTotalManhoursSpentPeriod]: any[] =
    React.useState(monthDates);
  const [
    teamTotalManhoursByStaffGrade,
    setTeamTotalManhoursByStaffGrade,
  ]: any[] = React.useState(weekDates);
  const [
    individualStaffManhoursSpentPeriod,
    setIndividualStaffManhoursSpentPeriod,
  ]: any[] = React.useState(weekDates);
  const [
    unsubmittedTimeSheetPeriod,
    setUnsubmittedTimeSheetPeriod,
  ]: any[] = React.useState(weekDates);
  const [
    teamTotalManhoursSpentPlanData,
    setTeamTotalManhoursSpentPlanData,
  ]: any[] = React.useState([0, 0, 0, 0, 0, 0, 0]);
  const [
    teamTotalManhoursSpentActualData,
    setTeamTotalManhoursSpentActualData,
  ]: any[] = React.useState([0, 0, 0, 0, 0, 0, 0]);
  const [hoveredDay, setHoveredDay] = React.useState<Dayjs | null>(null);
  const [value, setValue] = React.useState<Dayjs>(dayjs().startOf('week'));
  const [weeklyValueByStaffGrade, setWeeklyValueByStaffGrade] =
    React.useState<Dayjs>(dayjs().startOf('week'));
  const [weeklyToValueByStaffGrade, setWeeklyToValueByStaffGrade] =
    React.useState<Dayjs>(dayjs().startOf('week').add(6, 'day'));
  const [weeklyValueByIndividualStaff, setWeeklyValueByIndividualStaff] =
    React.useState<Dayjs>(dayjs().startOf('week'));
  const [weeklyUnsubmittedTimeSheet, setWeeklyUnsubmittedTimeSheet] =
    React.useState<Dayjs>(dayjs().startOf('week'));
  const [staffGradeManhoursSpentValue, setStaffGradeManhoursSpentValue] =
    React.useState<Dayjs>(dayjs());
  const [totalManHoursMonthlyFromValue, setTotalManHoursMonthlyFromValue] =
    React.useState<Dayjs>(dayjs(new Date()).subtract(6, "month"));
  const [totalManHoursMonthlyToValue, setTotalManHoursMonthlyToValue] =
    React.useState<Dayjs>(dayjs());
  const [unsubmitMonthlyFromValue, setUnsubmitMonthlyFromValue] =
    React.useState<Dayjs>(dayjs(new Date()));
  const [unsubmitMonthlyToValue, setUnsubmitMonthlyToValue] =
    React.useState<Dayjs>(dayjs());
  const [indivdualManHoursMonthlyFromValue, setIndivdualManHoursMonthlyFromValue] =
    React.useState<Dayjs>(dayjs());
  const [indivdualManHoursMonthlyToValue, setIndivdualManHoursMonthlyToValue] =
    React.useState<Dayjs>(dayjs());
  const [
    totalManHoursByStaffGradeMonthlyFromValue,
    setTotalManHoursByStaffGradeMonthlyFromValue,
  ] = React.useState<Dayjs>(dayjs(new Date()).subtract(6, "month"));
  const [
    totalManHoursByStaffGradeMonthlyToValue,
    setTotalManHoursByStaffGradeMonthlyToValue,
  ] = React.useState<Dayjs>(dayjs());
  const [
    totalManHoursByIndividualStaffMonthlyFromValue,
    setTotalManHoursByIndividualStaffMonthlyFromValue,
  ] = React.useState<Dayjs>(dayjs(new Date()).subtract(6, "month"));
  const [
    totalManHoursByIndividualStaffMonthlyToValue,
    setTotalManHoursByIndividualStaffMonthlyToValue,
  ] = React.useState<Dayjs>(dayjs());
  const [
    totalManHoursByIndividualStaffDailyFromValue,
    setTotalManHoursByIndividualStaffDailyFromValue,
  ] = React.useState<Dayjs>(dayjs(new Date()));
  const [
    totalManHoursByIndividualStaffDailyToValue,
    setTotalManHoursByIndividualStaffDailyToValue,
  ] = React.useState<Dayjs>(dayjs());
  const hd = new Holidays('HK');
  const currentYear = new Date().getFullYear();
  const years = [currentYear - 2, currentYear - 1, currentYear, currentYear + 1, currentYear + 2];
  let allHolidays: any[] = [];
  years.forEach(year => {
    const holidays = hd.getHolidays(year);
    allHolidays = allHolidays.concat(holidays);
  });
  const holidayDates = allHolidays.map(holiday => moment(holiday.date).format('YYYY-MM-DD')).join(',');
  const [totalManHoursMaxValue, setTotalManHoursMaxValue] = React.useState(5);
  const [totalManHoursByGradeMaxValue, setTotalManHoursByGradeMaxValue] = React.useState(5);
  const [individualManhoursMaxValue, setIndividualManhoursMaxValue] = React.useState(12);
  const [unsubmittedMaxValue, setUnsubmittedMaxValue] = React.useState(5);
  const [totalManhourByGradeActualManhours, setTotalManhourByGradeActualManhours]: any[] = React.useState([]);
  const [totalManhourByGradePlannedManhours, setTotalManhourByGradePlannedManhours]: any[] = React.useState([]);
  const [gradeNameList, setGradeNameList]: any[] = React.useState([]);
  const [teamManhoursTeamOptions, setTeamManhoursTeamOptions]: any[] = React.useState([]);
  const [staffOptions, setStaffOptions]: any[] = React.useState([]);
  const [teamManhoursTeamId, setTeamManhoursTeamId]: any[] = React.useState(abilityViewDashboardAll ? 0 : staff.teamId);
  const [teamUnsubmitTeamId, setTeamUnsubmitTeamId]: any[] = React.useState(abilityViewDashboardAll ? 0 : staff.teamId);
  const [staffGradeTeamId, setStaffGradeTeamId]: any[] = React.useState(abilityViewDashboardAll ? 0 : staff.teamId);
  const [staffId, setStaffId]: any[] = React.useState(0);
  const [unsubmitCount, setUnsubmitCount]: any[] = React.useState([]);
  const [currentPageUnsubmitStaffList, setCurrentPageUnsubmitStaffList]: any[] = React.useState([]);
  const [currentPageunsubmitCount, setCurrentPageUnsubmitCount]: any[] = React.useState([]);
  const [unsubmitStaffList, setUnsubmitStaffList]: any[] = React.useState([]);
  const [individualStaffProjectList, setIndividualStaffProjectList]: any[] = React.useState([]);
  const [individualStaffProjectCodeList, setIndividualStaffProjectCodeList]: any[] = React.useState([]);
  const [individualStaffManhours, setIndividualStaffManhours]: any[] = React.useState([]);
  const [individualStaffManhoursPercentage, setIndividualStaffManhoursPercentage]: any[] = React.useState([]);
  const [totalNormalConsumption, setTotalNormalConsumption]: any = React.useState('NA');
  const [totalOtConsumption, setTotalOtConsumption]: any = React.useState('NA');
  const [totalLeaveHours, setTotalLeaveHours]: any = React.useState('NA');
  const [currentPage, setCurrentPage] = useState(1);
  const recordsPerPage = 10;
  const [datePickerToLabel, setDatePickerToLabel] = React.useState(t("To"));
  const [datePickerToLabel2, setDatePickerToLabel2] = React.useState(t("To"));

  const fetchComboData = async () => {
    const staffComboList = []
    const teamComboList = []
    const teamCombo = await fetchTeamCombo();
    const staffCombo = await fetchStaffCombo();
    if (abilityViewDashboardAll) {
      for (var i = 0; i < teamCombo.records.length; i++) {
        teamComboList.push({ value: teamCombo.records[i].id, label: teamCombo.records[i].label })
      }
    } else {
      const tempTeam = teamCombo.records.find(team => team.id === staff.teamId)
      teamComboList.push({ value: tempTeam?.id, label: tempTeam?.label })
    }
    for (var i = 0; i < staffCombo.length; i++) {
      staffComboList.push({ value: staffCombo[i].id, label: staffCombo[i].label })
    }
    setTeamManhoursTeamOptions(teamComboList)
    setStaffOptions(staffComboList)
  }

  const fetchWeeklyTeamManhourSpentData = async () => {
    const fetchResult = await fetchweeklyTeamTotalManhours(teamManhoursTeamId, value.format('YYYY-MM-DD'));
    const weeklyActual = fetchResult[0].weeklyActualTeamTotalManhoursSpent
    const weeklyPlanned = fetchResult[0].weeklyPlannedTeamTotalManhoursSpent
    const weeklyActualList = []
    const weeklyPlannedList = []
    var chartMax = 5
    for (var i = 0; i < weeklyActual.length; i++) {
      if (chartMax < weeklyActual[i].TotalManhourConsumed) {
        chartMax = weeklyActual[i].TotalManhourConsumed
      }
      weeklyActualList.push(weeklyActual[i].TotalManhourConsumed)
    }
    if (weekDates.length > 0) {
      for (var i = 0; i < weeklyPlanned.length; i++) {
        const weeklyPlannedSubList = []
        const startCount = weeklyPlanned[i].startCount
        const endCount = weeklyPlanned[i].endCount
        for (var j = 0; j < weeklyPlanned[i].searchDuration; j++) {
          if (j >= startCount && j < endCount) {
            weeklyPlannedSubList.push(weeklyPlanned[i].AverageManhours)
          } else {
            weeklyPlannedSubList.push(0)
          }
        }
        weeklyPlannedList.push(weeklyPlannedSubList)
      }
      if (weeklyPlannedList.length > 0) {
        const result = new Array(weeklyPlannedList[0].length).fill(0);
        for (const arr of weeklyPlannedList) {
          for (let i = 0; i < arr.length; i++) {
            result[i] = Number((result[i] + arr[i]).toFixed(2));
            if (chartMax < result[i]) {
              chartMax = result[i]
            }
          }
        }
        setTeamTotalManhoursSpentPlanData(result)
      }
      else {
        const result = new Array(weekDates.length).fill(0);
        setTeamTotalManhoursSpentPlanData(result)
      }
    } 
    setTeamTotalManhoursSpentActualData(weeklyActualList);
    setTotalManHoursMaxValue(chartMax)
  }
  const fetchMonthlyTeamManhourSpentData = async () => {
    const fetchResult = await fetchmonthlyTeamTotalManhours(teamManhoursTeamId, totalManHoursMonthlyFromValue.format('YYYY-MM-DD'), totalManHoursMonthlyToValue.endOf('month').format('YYYY-MM-DD'));
    const weeklyActual = fetchResult[0].monthlyActualTeamTotalManhoursSpent
    const weeklyPlanned = fetchResult[0].monthlyPlannedTeamTotalManhoursSpent
    const weeklyActualList = []
    const weeklyPlannedList = []
    var chartMax = 5
    for (var i = 0; i < weeklyActual.length; i++) {
      if (chartMax < weeklyActual[i].TotalManhourConsumed) {
        chartMax = weeklyActual[i].TotalManhourConsumed
      }
      weeklyActualList.push(weeklyActual[i].TotalManhourConsumed)
    }
    if (weekDates.length > 0) {
      for (var i = 0; i < weeklyPlanned.length; i++) {
        const weeklyPlannedSubList = []
        const startCount = weeklyPlanned[i].startCount
        const endCount = weeklyPlanned[i].endCount
        for (var j = 0; j < weeklyPlanned[i].searchDuration; j++) {
          if (j >= startCount && j <= endCount) {
            weeklyPlannedSubList.push(weeklyPlanned[i].AverageManhours)
          } else {
            weeklyPlannedSubList.push(0)
          }
        }
        weeklyPlannedList.push(weeklyPlannedSubList)
      }
      if (weeklyPlannedList.length > 0) {
        const result = new Array(weeklyPlannedList[0].length).fill(0);
        for (const arr of weeklyPlannedList) {
          for (let i = 0; i < arr.length; i++) {
            result[i] = Number((result[i] + arr[i]).toFixed(2));
            if (chartMax < result[i]) {
              chartMax = result[i]
            }
          }
        }
        setTeamTotalManhoursSpentPlanData(result)
      } else {
        const result = new Array(weekDates.length).fill(0);
        setTeamTotalManhoursSpentPlanData(result)
      } 
    }
    setTeamTotalManhoursSpentActualData(weeklyActualList);
    setTotalManHoursMaxValue(chartMax)
  }

  const fetchTotalManhoursByGradeData = async () => {
    const fetchResult = await fetchTotalManhoursByGrade(weeklyValueByStaffGrade.format('YYYY-MM-DD'), weeklyToValueByStaffGrade.format('YYYY-MM-DD'),staffGradeTeamId);
    const actualManhours = fetchResult[0].staffGradeTotalManhours
    const plannedManhours = fetchResult[0].staffGradeTotalPlannedManhours
    var chartMax = 5
    const gradeList = []
    const actualList = []
    const plannedList = []

    var manhours = 0
    for (var i = 0; i < actualManhours.length; i++) {
      actualList.push(actualManhours[i].manhours.toFixed(2))
      gradeList.push(actualManhours[i].gradeName)
      if (chartMax < actualManhours[i].manhours) {
        chartMax = actualManhours[i].manhours
      }
    }
    if (plannedManhours.length > 0) {
      var gradeId = plannedManhours[0].id
      for (var i = 0; i < plannedManhours.length; i++) {
        if (plannedManhours[i].id === gradeId) {
          manhours += (plannedManhours[i].searchDuration - plannedManhours[i].startDiff - plannedManhours[i].endDiff) * plannedManhours[i].avgGradeManhour
          if (chartMax < manhours) {
            chartMax = manhours
          }
          if (i === plannedManhours.length - 1) {
            plannedList.push(manhours.toFixed(2))
          }
        } else {
          plannedList.push(manhours.toFixed(2))
          manhours = 0
          gradeId = plannedManhours[i].id
          manhours += (plannedManhours[i].searchDuration - plannedManhours[i].startDiff - plannedManhours[i].endDiff) * plannedManhours[i].avgGradeManhour
          if (chartMax < manhours) {
            chartMax = manhours
          }
          if (i === plannedManhours.length - 1) {
            plannedList.push(manhours.toFixed(2))
          }
        }
      }
    }
    setGradeNameList(gradeList)
    setTotalManhourByGradePlannedManhours(plannedList)
    setTotalManhourByGradeActualManhours(actualList);
    setTotalManHoursByGradeMaxValue(chartMax)
  }
  const fetchMonthlyTotalManhoursByGradeData = async () => {
    const fetchResult = await fetchTotalManhoursByGrade(totalManHoursMonthlyFromValue.format('YYYY-MM-DD'), totalManHoursMonthlyToValue.endOf('month').format('YYYY-MM-DD'),staffGradeTeamId);
    const actualManhours = fetchResult[0].staffGradeTotalManhours
    const plannedManhours = fetchResult[0].staffGradeTotalPlannedManhours
    var chartMax = 5
    const gradeList = []
    const actualList = []
    const plannedList = []

    var manhours = 0
    for (var i = 0; i < actualManhours.length; i++) {
      actualList.push(actualManhours[i].manhours.toFixed(2))
      gradeList.push(actualManhours[i].gradeName)
      if (chartMax < actualManhours[i].manhours) {
        chartMax = actualManhours[i].manhours
      }
    }
    if (plannedManhours.length > 0) {
      var gradeId = plannedManhours[0].id
      for (var i = 0; i < plannedManhours.length; i++) {
        if (plannedManhours[i].id === gradeId) {
          manhours += (plannedManhours[i].searchDuration - plannedManhours[i].startDiff - plannedManhours[i].endDiff) * plannedManhours[i].avgGradeManhour
          if (chartMax < manhours) {
            chartMax = manhours
          }
          if (i === plannedManhours.length - 1) {
            plannedList.push(manhours.toFixed(2))
          }
        } else {
          plannedList.push(manhours.toFixed(2))
          manhours = 0
          gradeId = plannedManhours[i].id
          manhours += (plannedManhours[i].searchDuration - plannedManhours[i].startDiff - plannedManhours[i].endDiff) * plannedManhours[i].avgGradeManhour
          if (chartMax < manhours) {
            chartMax = manhours
          }
          if (i === plannedManhours.length - 1) {
            plannedList.push(manhours.toFixed(2))
          }
        }
      }
    }
    setGradeNameList(gradeList)
    setTotalManhourByGradePlannedManhours(plannedList)
    setTotalManhourByGradeActualManhours(actualList);
    setTotalManHoursByGradeMaxValue(chartMax)
  }
  const fetchWeeklyUnsubmittedData = async () => {
    const fetchResult = await fetchWeeklyUnsubmit(teamUnsubmitTeamId, weeklyUnsubmittedTimeSheet.format('YYYY-MM-DD'), holidayDates);
    const result = []
    const staffList = []
    var maxValue = 5
    for (var i = 0; i < fetchResult.length; i++) {
      if (maxValue < fetchResult[i].UnsubmittedCount) {
        maxValue = fetchResult[i].UnsubmittedCount
      }
      result.push(fetchResult[i].UnsubmittedCount)
      staffList.push(fetchResult[i].name)
    }
    setUnsubmittedMaxValue(maxValue)
    setUnsubmitCount(result)
    setUnsubmitStaffList(staffList)
  }


  const fetchMonthlyUnsubmittedData = async () => {
    const fetchResult = await fetchMonthlyUnsubmit(teamUnsubmitTeamId, unsubmitMonthlyFromValue.startOf('month').format('YYYY-MM-DD'), unsubmitMonthlyToValue.endOf('month').format('YYYY-MM-DD'), holidayDates);

    const result = []
    const staffList = []
    var maxValue = 5
    for (var i = 0; i < fetchResult.length; i++) {
      if (maxValue < fetchResult[i].UnsubmittedCount) {
        maxValue = fetchResult[i].UnsubmittedCount
      }
      result.push(fetchResult[i].UnsubmittedCount)
      staffList.push(fetchResult[i].name)
    }
    setUnsubmittedMaxValue(maxValue)
    setUnsubmitCount(result)
    setUnsubmitStaffList(staffList)
  }
  const fetchDailyIndividualManhoursData = async () => {
    console.log(weeklyValueByIndividualStaff.add(6, 'days').format('YYYY-MM-DD'))
    const fetchResult = await fetchDailyIndividualStaffManhours(staffId, totalManHoursByIndividualStaffDailyFromValue.format('YYYY-MM-DD'));
    console.log(fetchResult)
    const manhoursResult = fetchResult[0].individualStaffManhoursSpentByDay
    const totalResult = fetchResult[0].individualStaffTotalManhoursSpentByDay
    const leaveResult = fetchResult[0].individualStaffTotalLeaveHoursByDay
    const result = []
    const projectList = []
    const projectCodeList = []
    const percentageList = []
    var maxValue = 12
    
    console.log(manhoursResult)
    if (manhoursResult.length > 0) {
      for (var i = 0; i < manhoursResult.length; i++) {
        if (manhoursResult[i].id !== null) {
          if (maxValue < manhoursResult[i].manhours) {
            maxValue = manhoursResult[i].manhours
          }
          result.push(manhoursResult[i].manhours)
          projectCodeList.push(manhoursResult[i].projectNo)
          projectList.push(manhoursResult[i].projectName)
          percentageList.push(manhoursResult[i].manhours)
        }
      }
      setIndividualManhoursMaxValue(maxValue)
      setIndividualStaffProjectCodeList(projectCodeList)
      setIndividualStaffProjectList(projectList)
      setIndividualStaffManhours(result)
      setIndividualStaffManhoursPercentage(percentageList)
      setTotalNormalConsumption(totalResult[0].normalManhours)
      setTotalOtConsumption(totalResult[0].otManhours)
      setTotalLeaveHours(leaveResult[0].leaveHours)
    }

  }

  const fetchWeeklyIndividualManhoursData = async () => {
    console.log(weeklyValueByIndividualStaff)
    const fetchResult = await fetchWeeklyIndividualStaffManhours(staffId, weeklyValueByIndividualStaff.format('YYYY-MM-DD'), weeklyValueByIndividualStaff.add(6, 'days').format('YYYY-MM-DD'));
    console.log(fetchResult)
    const manhoursResult = fetchResult[0].individualStaffManhoursSpentWeekly
    const totalResult = fetchResult[0].individualStaffTotalManhoursSpentWeekly
    const leaveResult = fetchResult[0].individualStaffTotalLeaveHoursWeekly
    const result: any[] = []
    const projectList: any[] = []
    const projectCodeList: any[] = []
    const percentageList: any[] = []
    var maxValue = 12
    if (manhoursResult.length > 0) {
      for (var i = 0; i < manhoursResult.length; i++) {
        if (maxValue < manhoursResult[i].manhours) {
          maxValue = manhoursResult[i].manhours
        }
        result.push(manhoursResult[i].manhours)
        projectCodeList.push(manhoursResult[i].projectNo)
        projectList.push(manhoursResult[i].projectName)
        percentageList.push(manhoursResult[i].manhours)
      }
      setIndividualManhoursMaxValue(maxValue)
      setIndividualStaffProjectList(projectList)
      setIndividualStaffProjectCodeList(projectCodeList)
      setIndividualStaffManhours(result)
      setIndividualStaffManhoursPercentage(percentageList)
      setTotalNormalConsumption(totalResult[0].normalManhours)
      setTotalOtConsumption(totalResult[0].otManhours)
      setTotalLeaveHours(leaveResult[0].leaveHours)
    }else{
      setIndividualManhoursMaxValue(maxValue)
      setIndividualStaffProjectList(projectList)
      setIndividualStaffProjectCodeList(projectCodeList)
      setIndividualStaffManhours(result)
      setIndividualStaffManhoursPercentage(percentageList)
      setTotalNormalConsumption(0)
      setTotalOtConsumption(0)
      setTotalLeaveHours(0)
    }

  }

  const fetchMonthlyIndividualManhoursData = async () => {
    const fetchResult = await fetchMonthlyIndividualStaffManhours(staffId, indivdualManHoursMonthlyFromValue.format('YYYY-MM-01'));
    const manhoursResult = fetchResult[0].individualStaffManhoursSpentByMonth
    const totalResult = fetchResult[0].individualStaffTotalManhoursSpentByMonth
    const leaveResult = fetchResult[0].individualStaffTotalLeaveHoursByMonth
    const result: any[] = []
    const projectList: any[] = []
    const projectCodeList: any[] = []
    const percentageList: any[] = []
    var maxValue = 12
    if (manhoursResult.length > 0) {
      for (var i = 0; i < manhoursResult.length; i++) {
        if (maxValue < manhoursResult[i].manhours) {
          maxValue = manhoursResult[i].manhours
        }
        result.push(manhoursResult[i].manhours)
        projectCodeList.push(manhoursResult[i].projectNo)
        projectList.push(manhoursResult[i].projectName)
        percentageList.push(manhoursResult[i].manhours)
      }
      setIndividualManhoursMaxValue(maxValue)
      setIndividualStaffProjectList(projectList)
      setIndividualStaffProjectCodeList(projectCodeList)
      setIndividualStaffManhours(result)
      setIndividualStaffManhoursPercentage(percentageList)
      setTotalNormalConsumption(totalResult[0].normalManhours)
      setTotalOtConsumption(totalResult[0].otManhours)
      setTotalLeaveHours(leaveResult[0].leaveHours)
    }else{
      setIndividualManhoursMaxValue(maxValue)
      setIndividualStaffProjectList(projectList)
      setIndividualStaffProjectCodeList(projectCodeList)
      setIndividualStaffManhours(result)
      setIndividualStaffManhoursPercentage(percentageList)
      setTotalNormalConsumption(0)
      setTotalOtConsumption(0)
      setTotalLeaveHours(0)
    }

  }

  const startIndex = (currentPage - 1) * recordsPerPage;
  const endIndex = startIndex + recordsPerPage;
  useEffect(() => {
  const currentPageStaffData = unsubmitStaffList.slice(startIndex, endIndex)
  const currentPageData = unsubmitCount.slice(startIndex, endIndex);
  console.log(currentPage)
  console.log(Math.ceil(unsubmitStaffList.length / recordsPerPage))
  setCurrentPageUnsubmitStaffList(currentPageStaffData)
  setCurrentPageUnsubmitCount(currentPageData)
  }, [unsubmitCount,currentPage]);

  const handlePrevPage = () => {
    if (currentPage > 1) {
      setCurrentPage(currentPage - 1);
    }
  };

  const handleNextPage = () => {
    if (endIndex < unsubmitCount.length) {
      setCurrentPage(currentPage + 1);
    }
  };

  useEffect(() => {
    fetchComboData()
  }, []);


  useEffect(() => {
    if (teamTotalManhoursSpentSelect === "Weekly") {
      fetchWeeklyTeamManhourSpentData()
    }
  }, [value, teamManhoursTeamId]);

  useEffect(() => {
    if (teamTotalManhoursSpentSelect === "Monthly") {
      fetchMonthlyTeamManhourSpentData()
    }
  }, [totalManHoursMonthlyFromValue, totalManHoursMonthlyToValue, teamManhoursTeamId]);

  useEffect(() => {
    if (staffGradeManhoursSpentSelect === "Weekly") {
      fetchTotalManhoursByGradeData()
    }
  }, [staffGradeTeamId, weeklyValueByStaffGrade, weeklyToValueByStaffGrade]);

  useEffect(() => {
    if (staffGradeManhoursSpentSelect === "Monthly") {
      fetchMonthlyTotalManhoursByGradeData()
    }
  }, [staffGradeTeamId, totalManHoursMonthlyFromValue, totalManHoursMonthlyToValue]);

  useEffect(() => {
    if (unsubmittedTimeSheetSelect === "Weekly") {
      fetchWeeklyUnsubmittedData()
    }
  }, [teamUnsubmitTeamId, weeklyUnsubmittedTimeSheet]);

  useEffect(() => {
    if (unsubmittedTimeSheetSelect === "Monthly") {
      fetchMonthlyUnsubmittedData()
    }
  }, [teamUnsubmitTeamId, unsubmitMonthlyFromValue, unsubmitMonthlyToValue]);

  useEffect(() => {
    if (individualStaffManhoursSpentSelect === "Daily") {
      fetchDailyIndividualManhoursData()
    }
  }, [staffId, totalManHoursByIndividualStaffDailyFromValue, individualStaffManhoursSpentSelect]);

  useEffect(() => {
    if (individualStaffManhoursSpentSelect === "Weekly") {
      fetchWeeklyIndividualManhoursData()
    }
  }, [staffId, weeklyValueByIndividualStaff]);

  useEffect(() => {
    if (individualStaffManhoursSpentSelect === "Monthly") {
      fetchMonthlyIndividualManhoursData()
    }
  }, [staffId, indivdualManHoursMonthlyFromValue]);

  // useEffect(() => {
  //   console.log(unsubmittedTimeSheetSelect)
  //   if (unsubmittedTimeSheetSelect === "Monthly" || teamTotalManhoursSpentSelect === "Monthly" || staffGradeManhoursSpentSelect === "Monthly" || individualStaffManhoursSpentSelect === "Monthly") {
  //     setUnsubmittedTimeSheetSelect("Monthly")
  //     setTeamTotalManhoursSpentSelect("Monthly")
  //     setStaffGradeManhoursSpentSelect("Monthly")
  //     setIndividualStaffManhoursSpentSelect("Monthly")
  //   } else if (unsubmittedTimeSheetSelect === "Weekly" || teamTotalManhoursSpentSelect === "Weekly" || staffGradeManhoursSpentSelect === "Weekly" || individualStaffManhoursSpentSelect === "Weekly") {
  //     setUnsubmittedTimeSheetSelect("Weekly")
  //     setTeamTotalManhoursSpentSelect("Weekly")
  //     setStaffGradeManhoursSpentSelect("Weekly")
  //     setIndividualStaffManhoursSpentSelect("Weekly")
  //   }
  // }, [unsubmittedTimeSheetSelect, teamTotalManhoursSpentSelect, staffGradeManhoursSpentSelect, individualStaffManhoursSpentSelect]);




  const teamOptions = [
    { value: 1, label: "XXX Team" },
    { value: 2, label: "YYY Team" },
    { value: 3, label: "ZZZ Team" },
  ];

  const columns = [
    {
      id: "projectCode",
      field: "projectCode",
      headerName: "Project Code",
      flex: 1,
    },
    {
      id: "projectName",
      field: "projectName",
      headerName: "Project Name",
      flex: 1,
    },
    {
      id: "team",
      field: "team",
      headerName: "Team",
      flex: 1,
    },
    {
      id: "teamLeader",
      field: "teamLeader",
      headerName: "Team Leader",
      flex: 1,
    },
    {
      id: "startDate",
      field: "startDate",
      headerName: "Start Date",
      flex: 1,
    },
    {
      id: "targetEndDate",
      field: "targetEndDate",
      headerName: "Target End Date",
      flex: 1,
    },
    {
      id: "client",
      field: "client",
      headerName: "Client",
      flex: 1,
    },
    {
      id: "subsidiary",
      field: "subsidiary",
      headerName: "Subsidiary",
      flex: 1,
    },
  ];

  const options: ApexOptions = {
    tooltip: {
      y: {
        formatter: function (val) {
          return val.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
        }
      }
    },
    chart: {
      height: 350,
      type: "line",
    },
    stroke: {
      width: [2, 2],
    },
    plotOptions: {
      bar: {
        horizontal: false,
        distributed: false,
      },
    },
    dataLabels: {
      enabled: true,
    },
    xaxis: {
      categories: teamTotalManhoursSpentPeriod,
    },
    yaxis: [
      {
        title: {
          text: t("Team Total Manhours Spent (Hours)"),
          style: {
            fontSize: "14px"
          }
        },
        min: 0,
        max: totalManHoursMaxValue,
        tickAmount: 5,
        labels: {
          formatter: function (val) {
            return val.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })
          }
        }
      },
    ],
    grid: {
      borderColor: "#f1f1f1",
    },
    annotations: {},
    series: [
      {
        name: t("Planned"),
        type: "line",
        color: "#efbe7d",
        data: teamTotalManhoursSpentPlanData,
      },
      {
        name: t("Actual"),
        type: "line",
        color: "#7cd3f2",
        data: teamTotalManhoursSpentActualData,
      },
    ],
  };

  const staffGradeOptions: ApexOptions = {
    chart: {
      height: 350,
      type: "bar",
    },
    stroke: {
      width: [2, 2],
    },
    plotOptions: {
      bar: {
        horizontal: true,
        distributed: false,
      },
    },
    dataLabels: {
      enabled: true,
    },
    xaxis: {
      categories: gradeNameList,
    },
    yaxis: [
      {
        title: {
          text: t("Staff Grade"),
          style: {
            fontSize: "14px"
          }
        },
        min: 0,
        max: totalManHoursByGradeMaxValue,
        tickAmount: 5,
      },
    ],
    grid: {
      borderColor: "#f1f1f1",
    },
    annotations: {},
    series: [
      {
        name: t("Planned"),
        type: "bar",
        color: "#efbe7d",
        data: totalManhourByGradePlannedManhours,
      },
      {
        name: t("Actual"),
        type: "bar",
        color: "#00acb1",
        data: totalManhourByGradeActualManhours,
      },
    ],
  };

  const individualStaffOptions: ApexOptions = {
    chart: {
      height: 350,
      type: "line",
    },
    stroke: {
      width: [1],
    },
    plotOptions: {
      bar: {
        horizontal: true,
        distributed: false,
      },
    },
    dataLabels: {
      enabled: true,
    },
    xaxis: {
      categories: individualStaffProjectCodeList,
    },
    yaxis: [
      {
        title: {
          text: t("Project"),
          style: {
            fontSize: "14px"
          }
        },
        min: 0,
        max: individualManhoursMaxValue,
        tickAmount: 5,
      },
    ],
    grid: {
      borderColor: "#f1f1f1",
    },
    annotations: {},
    tooltip: {
      x: {
        formatter: (value, { series, seriesIndex, dataPointIndex, w }) => {
          return individualStaffProjectList[dataPointIndex];
        },
      },
    },
    series: [
      {
        name: t("Manhours (Hour)"),
        type: "bar",
        color: "#00acb1",
        data: individualStaffManhours,
      },
    ],
  };

  const unsubmittedTimeSheetOptions: ApexOptions = {
    chart: {
      height: 350,
      type: "line",
    },
    stroke: {
      width: [1],
    },
    plotOptions: {
      bar: {
        horizontal: true,
        distributed: false,
      },
    },
    dataLabels: {
      enabled: true,
    },
    xaxis: {
      categories: currentPageUnsubmitStaffList,
    },
    yaxis: [
      {
        title: {
          text: t("Staff"),
          style: {
            fontSize: "14px"
          }
        },
        min: 0,
        max: unsubmittedMaxValue,
        tickAmount: 5,
      },
    ],
    grid: {
      borderColor: "#f1f1f1",
    },
    annotations: {},
    series: [
      {
        name: t("Unsubmitted Time Sheet"),
        type: "bar",
        color: "#00acb1",
        data: currentPageunsubmitCount,
      },
    ],
  };

  const teamTotalManhoursSpentOnClick = (r: any) => {
    setTeamTotalManhoursSpentSelect(r);

    if (r === "Weekly") {
      fetchWeeklyTeamManhourSpentData()
      setValue(dayjs().startOf('week'));
      setTeamTotalManhoursSpentPeriod(weekDates);
    } else if (r === "Monthly") {
      fetchMonthlyTeamManhourSpentData()
      setTeamTotalManhoursSpentPeriod(monthDates);
    }
  };

  const individualStaffManhoursSpentOnClick = (r: any) => {
    setIndividualStaffManhoursSpentSelect(r);
    // if (r === "Weekly") {
    //   setValue(dayjs(new Date))
    //   setTeamTotalManhoursSpentPeriod(weekDates)
    //   setTeamTotalManhoursSpentPlanData([42,42,42,42,42,0,0])
    //   setTeamTotalManhoursSpentActualData([45,42,60,42,58,0,0])
    //   setTotalManHoursMaxValue(75)
    // } else if (r === "Monthly") {
    //   setTeamTotalManhoursSpentPeriod(monthDates)
    //   setTeamTotalManhoursSpentPlanData([840,840,840,840,840,840])
    //   setTeamTotalManhoursSpentActualData([900,840,1200,840,1160,840])
    //   setTotalManHoursMaxValue(1250)
    // }
  };

  const unsubmittedTimeSheetOnClick = (r: any) => {
    setUnsubmittedTimeSheetSelect(r);
  };

  const selectWeeklyPeriod = (r: any) => {
    const selectDate = new Date(r);
    const firstDayOfWeek = selectDate;
    firstDayOfWeek.setDate(selectDate.getDate() - selectDate.getDay() + 0);
    const weekDates: any[] = [];
    const weekFirstDate = new Date(firstDayOfWeek);
    for (let i = 0; i < 7; i++) {
      const currentDate = new Date(firstDayOfWeek);
      currentDate.setDate(firstDayOfWeek.getDate() + i);
      const formattedDate = dayjs(currentDate).format("DD MMM (ddd)");
      weekDates.push(formattedDate);
    }
    setTeamTotalManhoursSpentPeriod(weekDates);
    setValue(dayjs(firstDayOfWeek));
  };

  const selectWeeklyPeriodByStaffGrade = (r: any) => {
    const selectDate = new Date(r);
    const firstDayOfWeek = selectDate
    firstDayOfWeek.setDate(selectDate.getDate() - selectDate.getDay() + 0);
    const weekDates: any[] = [];
    for (let i = 0; i < 7; i++) {
      const currentDate = new Date(firstDayOfWeek);
      currentDate.setDate(firstDayOfWeek.getDate() + i);
      const formattedDate = dayjs(currentDate).format("DD MMM (ddd)");
      weekDates.push(formattedDate);
    }
    setTeamTotalManhoursByStaffGrade(weekDates);
    setWeeklyValueByStaffGrade(dayjs(firstDayOfWeek));
    setWeeklyToValueByStaffGrade(dayjs(firstDayOfWeek).add(6, 'day'))
  };

  const selectWeeklyPeriodUnsubmittedTimeSheet = (r: any) => {
    const selectDate = new Date(r);
    const firstDayOfWeek = selectDate;
    firstDayOfWeek.setDate(selectDate.getDate() - selectDate.getDay() + 0);
    const weekDates: any[] = [];
    for (let i = 0; i < 7; i++) {
      const currentDate = new Date(firstDayOfWeek);
      currentDate.setDate(firstDayOfWeek.getDate() + i);
      const formattedDate = dayjs(currentDate).format("DD MMM (ddd)");
      weekDates.push(formattedDate);
    }
    setUnsubmittedTimeSheetPeriod(weekDates);
    setWeeklyUnsubmittedTimeSheet(dayjs(firstDayOfWeek));
  };

  const selectWeeklyPeriodIndividualStaff = (r: any) => {
    const selectDate = new Date(r);
    const firstDayOfWeek = selectDate;
    firstDayOfWeek.setDate(selectDate.getDate() - selectDate.getDay() + 0);
    const weekDates: any[] = [];
    for (let i = 0; i < 7; i++) {
      const currentDate = new Date(firstDayOfWeek);
      currentDate.setDate(firstDayOfWeek.getDate() + i);
      const formattedDate = dayjs(currentDate).format("DD MMM (ddd)");
      weekDates.push(formattedDate);
    }
    setIndividualStaffManhoursSpentPeriod(weekDates);
    setWeeklyValueByIndividualStaff(dayjs(firstDayOfWeek));
  };

  const selectMonthlyPeriodFrom = (r: any) => {
    setTotalManHoursMonthlyFromValue(r)
    const monthDates: any[] = [];
    const monthPlanData: any[] = [];
    const monthActualData: any[] = [];
    const selectFromDate = dayjs(r);
    for (
      let date = selectFromDate.clone();
      date.isBefore(totalManHoursMonthlyToValue, "month");
      date = date.add(1, "month")
    ) {
      monthDates.push(date.format("MM-YYYY"));
      monthPlanData.push(840);
      monthActualData.push(Math.floor(Math.random() * (1200 - 840) + 840));
    }
    monthDates.push(totalManHoursMonthlyToValue.format("MM-YYYY"));
    monthPlanData.push(840);
    monthActualData.push(Math.floor(Math.random() * (1200 - 840) + 840));
    setTeamTotalManhoursSpentPlanData(monthPlanData);
    setTeamTotalManhoursSpentActualData(monthActualData);
    setTeamTotalManhoursSpentPeriod(monthDates);
  };

  const selectMonthlyPeriodTo = (r: any) => {
    setTotalManHoursMonthlyToValue(r)
    const monthDates: any[] = [];
    const monthPlanData: any[] = [];
    const monthActualData: any[] = [];
    const selectToDate = dayjs(r);
    for (
      let date = totalManHoursMonthlyFromValue.clone();
      date.isBefore(selectToDate, "month");
      date = date.add(1, "month")
    ) {
      monthDates.push(date.format("MM-YYYY"));
      monthPlanData.push(840);
      monthActualData.push(Math.floor(Math.random() * (1200 - 840) + 840));
    }
    monthDates.push(selectToDate.format("MM-YYYY"));
    monthPlanData.push(840);
    monthActualData.push(Math.floor(Math.random() * (1200 - 840) + 840));
    setTeamTotalManhoursSpentPlanData(monthPlanData);
    setTeamTotalManhoursSpentActualData(monthActualData);
    setTeamTotalManhoursSpentPeriod(monthDates);
  };

  const selectStaffGradeMonthlyPeriodFrom = (r: any) => {
    setTotalManHoursMonthlyFromValue(r)
    const monthDates: any[] = [];
    const monthPlanData: any[] = [];
    const monthActualData: any[] = [];
    const selectFromDate = dayjs(r);
    for (
      let date = selectFromDate.clone();
      date.isBefore(totalManHoursMonthlyToValue, "month");
      date = date.add(1, "month")
    ) {
      monthDates.push(date.format("MM-YYYY"));
      monthPlanData.push(840);
      monthActualData.push(Math.floor(Math.random() * (1200 - 840) + 840));
    }
    monthDates.push(totalManHoursMonthlyToValue.format("MM-YYYY"));
    monthPlanData.push(840);
    monthActualData.push(Math.floor(Math.random() * (1200 - 840) + 840));
    // setTeamTotalManhoursSpentPlanData(monthPlanData)
    // setTeamTotalManhoursSpentActualData(monthActualData)
    setTeamTotalManhoursByStaffGrade(weekDates);
  };

  const selectStaffGradeMonthlyPeriodTo = (r: any) => {
    setTotalManHoursMonthlyToValue(r)
    const monthDates: any[] = [];
    const monthPlanData: any[] = [];
    const monthActualData: any[] = [];
    const selectToDate = dayjs(r);
    for (
      let date = totalManHoursMonthlyFromValue.clone();
      date.isBefore(selectToDate, "month");
      date = date.add(1, "month")
    ) {
      monthDates.push(date.format("MM-YYYY"));
      monthPlanData.push(840);
      monthActualData.push(Math.floor(Math.random() * (1200 - 840) + 840));
    }
    monthDates.push(selectToDate.format("MM-YYYY"));
    monthPlanData.push(840);
    monthActualData.push(Math.floor(Math.random() * (1200 - 840) + 840));
    // setTeamTotalManhoursSpentPlanData(monthPlanData)
    // setTeamTotalManhoursSpentActualData(monthActualData)
    setTeamTotalManhoursByStaffGrade(weekDates);
  };

  const selectUnsubmittedTimeSheetMonthlyPeriodFrom = (r: any) => {
    setUnsubmitMonthlyFromValue(r)
    const monthDates: any[] = [];
    const monthPlanData: any[] = [];
    const monthActualData: any[] = [];
    const selectFromDate = dayjs(r);
    for (
      let date = selectFromDate.clone();
      date.isBefore(unsubmitMonthlyToValue, "month");
      date = date.add(1, "month")
    ) {
      monthDates.push(date.format("MM-YYYY"));
      monthPlanData.push(840);
      monthActualData.push(Math.floor(Math.random() * (1200 - 840) + 840));
    }
    monthDates.push(selectFromDate.format("MM-YYYY"));
    monthPlanData.push(840);
    monthActualData.push(Math.floor(Math.random() * (1200 - 840) + 840));
    // setTeamTotalManhoursSpentPlanData(monthPlanData)
    // setTeamTotalManhoursSpentActualData(monthActualData)
    setUnsubmittedTimeSheetPeriod(weekDates);
  };

  const selectIndividualStaffMonthlyPeriodFrom = (r: any) => {
    setIndivdualManHoursMonthlyFromValue(r)
    const monthDates: any[] = [];
    const monthPlanData: any[] = [];
    const monthActualData: any[] = [];
    const selectFromDate = dayjs(r);
    for (
      let date = selectFromDate.clone();
      date.isBefore(indivdualManHoursMonthlyToValue, "month");
      date = date.add(1, "month")
    ) {
      monthDates.push(date.format("MM-YYYY"));
      // monthPlanData.push(840);
      // monthActualData.push(Math.floor(Math.random() * (1200 - 840) + 840));
    }
    monthDates.push(selectFromDate.format("MM-YYYY"));
    // monthPlanData.push(840);
    // monthActualData.push(Math.floor(Math.random() * (1200 - 840) + 840));
    // setTeamTotalManhoursSpentPlanData(monthPlanData)
    // setTeamTotalManhoursSpentActualData(monthActualData)
    setIndividualStaffManhoursSpentPeriod(weekDates);
  };

  const selectUnsubmittedTimeSheetMonthlyPeriodTo = (r: any) => {
    setIndivdualManHoursMonthlyToValue(r)
    const monthDates: any[] = [];
    const monthPlanData: any[] = [];
    const monthActualData: any[] = [];
    const selectToDate = dayjs(r);
    for (
      let date = indivdualManHoursMonthlyToValue.clone();
      date.isBefore(selectToDate, "month");
      date = date.add(1, "month")
    ) {
      monthDates.push(date.format("MM-YYYY"));
      monthPlanData.push(840);
      monthActualData.push(Math.floor(Math.random() * (1200 - 840) + 840));
    }
    monthDates.push(selectToDate.format("MM-YYYY"));
    monthPlanData.push(840);
    monthActualData.push(Math.floor(Math.random() * (1200 - 840) + 840));
    // setTeamTotalManhoursSpentPlanData(monthPlanData)
    // setTeamTotalManhoursSpentActualData(monthActualData)
    setUnsubmittedTimeSheetPeriod(weekDates);
  };

  const selectIndividualStaffMonthlyPeriodTo = (r: any) => {
    setTotalManHoursMonthlyToValue(r)
    const monthDates: any[] = [];
    const monthPlanData: any[] = [];
    const monthActualData: any[] = [];
    const selectToDate = dayjs(r);
    for (
      let date = totalManHoursMonthlyFromValue.clone();
      date.isBefore(selectToDate, "month");
      date = date.add(1, "month")
    ) {
      monthDates.push(date.format("MM-YYYY"));
      monthPlanData.push(840);
      monthActualData.push(Math.floor(Math.random() * (1200 - 840) + 840));
    }
    monthDates.push(selectToDate.format("MM-YYYY"));
    monthPlanData.push(840);
    monthActualData.push(Math.floor(Math.random() * (1200 - 840) + 840));
    // setTeamTotalManhoursSpentPlanData(monthPlanData)
    // setTeamTotalManhoursSpentActualData(monthActualData)
    setIndividualStaffManhoursSpentPeriod(weekDates);
  };
  

  const options2: ApexOptions = {
    chart: {
      type: "donut",
    },
    colors: ['#f57f90', '#94f7d6', '#87c5f5', '#ab95f5', '#ab95f5'],
    plotOptions: {
      pie: {
        donut: {
          labels: {
            show: false,
            name: {
              show: true,
            },
            value: {
              show: false,
              fontWeight: 500,
              fontSize: "30px",
              color: "#3e98c7",
            },
            total: {
              show: false,
              showAlways: false,
              label: "Spent",
              fontFamily: "sans-serif",
              formatter: function (val) {
                return val + "%";
              },
            },
          },
        },
      },
    },
    series: individualStaffManhoursPercentage,
    labels: individualStaffProjectList,
    legend: {
      show: false,
    },
    responsive: [
      {
        breakpoint: 480,
        options: {
          chart: {
            width: 200,
          },
          legend: {
            position: "bottom",
            show: false,
          },
        },
      },
    ],
  };

  return (
    <>
      <Grid item sm>
        <Typography variant="h4" marginInlineEnd={2}>
          {t("Staff Utilization")}
        </Typography>
        <div style={{ display: "inline-block", width: "40%" }} className={"mt-5"}>
          <div>
            <Grid item xs={12} md={12} lg={12}>
              <Card>
                <CardHeader
                  className="text-slate-500"
                  title= {t("Team Total Manhours Spent")}
                />
                <div style={{ display: "inline-block", width: "99%" }}>
                  <div className="w-fit align-top mr-5 float-right">
                    {teamTotalManhoursSpentSelect === "Weekly" && (
                      <>
                        <button className="text-lg bg-lime-100 border-lime-600 text-lime-600 border-solid rounded-l-md w-32">
                          {t("Weekly")}
                        </button>
                        <button
                          onClick={() => {
                            teamTotalManhoursSpentOnClick("Monthly")
                            setUnsubmittedTimeSheetSelect("Monthly")
                            fetchMonthlyUnsubmittedData()
                            setStaffGradeManhoursSpentSelect("Monthly")
                            fetchMonthlyTotalManhoursByGradeData()
                            setIndividualStaffManhoursSpentSelect("Monthly")
                            fetchMonthlyIndividualManhoursData()
                            }
                          }
                          className="hover:cursor-pointer hover:bg-lime-50 text-lg bg-transparent border-lime-600 text-lime-600 border-solid rounded-r-md w-32"
                        >
                          {t("Monthly")}
                        </button>
                      </>
                    )}
                    {teamTotalManhoursSpentSelect === "Monthly" && (
                      <>
                        <button
                          onClick={() => {
                            teamTotalManhoursSpentOnClick("Weekly")
                            setUnsubmittedTimeSheetSelect("Weekly")
                            fetchWeeklyUnsubmittedData()
                            setStaffGradeManhoursSpentSelect("Weekly")
                            fetchTotalManhoursByGradeData()
                            setIndividualStaffManhoursSpentSelect("Weekly")
                            fetchWeeklyIndividualManhoursData()
                            }
                          }
                          className="hover:cursor-pointer hover:bg-lime-50 text-lg bg-transparent border-lime-600 text-lime-600 border-solid rounded-l-md w-32"
                        >
                          {t("Weekly")}
                        </button>
                        <button className="text-lg bg-lime-100 border-lime-600 text-lime-600 border-solid rounded-r-md w-32">
                          {t("Monthly")}
                        </button>
                      </>
                    )}
                  </div>
                  <div className="inline-block w-fit mt-2">
                    {abilityViewDashboardAll &&
                      <div className="inline-block">
                        <div className="inline-block ml-6">
                          <Label className="text-slate-500 font-medium">
                            {t("Team")}:&nbsp;
                          </Label>
                        </div>
                        <div className="inline-block ml-1 w-60">
                          <Select
                            placeholder={t("Please select a team")}
                            options={teamManhoursTeamOptions}
                            isClearable={true}
                            onChange={(selectedOption: any) => {
                              if (selectedOption === null) {
                                setTeamManhoursTeamId(null);
                              } else {
                                setTeamManhoursTeamId(selectedOption.value);
                              }
                            }}
                            onMenuOpen={() => {
                              setDatePickerToLabel("")
                            }}
                            onMenuClose={() => {
                              setDatePickerToLabel(t("To"))
                            }}
                          />
                        </div>
                      </div>}
                    <div className="ml-6 mt-2" style={{ verticalAlign: "top" }}>
                      {/* <Label className="text-slate-500 font-medium ml-6">
                          Period:&nbsp;
                        </Label> */}
                      {teamTotalManhoursSpentSelect === "Weekly" && (
                        <LocalizationProvider dateAdapter={AdapterDayjs}>
                          <DatePicker
                            className="w-72 h-10 align-top"
                            label= {t("Week") + ":"}
                            value={value}
                            format="DD-MM-YYYY"
                            onChange={(newValue) => {
                              selectWeeklyPeriod(newValue)
                            }
                            }
                            showDaysOutsideCurrentMonth
                            displayWeekNumber
                            slots={{ day: Day }}
                            slotProps={{
                              day: (ownerState) =>
                                ({
                                  selectedDay: value,
                                  hoveredDay,
                                  onPointerEnter: () =>
                                    setHoveredDay(ownerState.day),
                                  onPointerLeave: () => setHoveredDay(null),
                                }) as any,
                            }}
                          />
                        </LocalizationProvider>
                      )}
                      {teamTotalManhoursSpentSelect === "Monthly" && (
                        <LocalizationProvider dateAdapter={AdapterDayjs}>
                          <DatePicker
                            className="w-44 h-10 align-top"
                            onChange={(newValue) =>
                              selectMonthlyPeriodFrom(newValue)
                            }
                            defaultValue={totalManHoursMonthlyFromValue}
                            label={t("From")}
                            views={["month", "year"]}
                            format="MM-YYYY"
                          />
                          <DatePicker
                            className="w-40 h-10 align-top"
                            onChange={(newValue) =>
                              selectMonthlyPeriodTo(newValue)
                            }
                            defaultValue={totalManHoursMonthlyToValue}
                            label={datePickerToLabel}
                            views={["month", "year"]}
                            format="MM-YYYY"
                          />
                        </LocalizationProvider>
                      )}
                    </div>
                  </div>

                  <ReactApexChart
                    options={options}
                    series={options.series}
                    type="line"
                    height="400"
                  />
                </div>
              </Card>
            </Grid>
          </div>
          <div className="mt-5">
            <Grid item xs={12} md={12} lg={12}>
              <Card>
                <CardHeader
                  className="text-slate-500"
                  title= {t("Total Manhours Spent by Staff Grade")}
                />
                <div style={{ display: "inline-block", width: "99%" }}>
                  <div className="w-fit align-top mr-5 float-right">
                    {staffGradeManhoursSpentSelect === "Weekly" && (
                      <>
                        <button className="text-lg bg-lime-100 border-lime-600 text-lime-600 border-solid rounded-l-md w-32">
                          {t("Weekly")}
                        </button>
                        <button
                          onClick={() => {
                            teamTotalManhoursSpentOnClick("Monthly")
                            setUnsubmittedTimeSheetSelect("Monthly")
                            fetchMonthlyUnsubmittedData()
                            setStaffGradeManhoursSpentSelect("Monthly")
                            fetchMonthlyTotalManhoursByGradeData()
                            setIndividualStaffManhoursSpentSelect("Monthly")
                            fetchMonthlyIndividualManhoursData()
                          }
                          }
                          className="hover:cursor-pointer hover:bg-lime-50 text-lg bg-transparent border-lime-600 text-lime-600 border-solid rounded-r-md w-48"
                        >
                          {t("Monthly")}
                        </button>
                      </>
                    )}
                    {staffGradeManhoursSpentSelect === "Monthly" && (
                      <>
                        <button
                          onClick={() => {
                            teamTotalManhoursSpentOnClick("Weekly")
                            setUnsubmittedTimeSheetSelect("Weekly")
                            fetchWeeklyUnsubmittedData()
                            setStaffGradeManhoursSpentSelect("Weekly")
                            fetchTotalManhoursByGradeData()
                            setIndividualStaffManhoursSpentSelect("Weekly")
                            fetchWeeklyIndividualManhoursData()
                          }
                          }
                          className="hover:cursor-pointer hover:bg-lime-50 text-lg bg-transparent border-lime-600 text-lime-600 border-solid rounded-l-md w-32"
                        >
                          {t("Weekly")}
                        </button>
                        <button className="text-lg bg-lime-100 border-lime-600 text-lime-600 border-solid rounded-r-md w-48">
                          {t("Monthly")}
                        </button>
                      </>
                    )}
                  </div>
                  <div className="inline-block w-fit mt-2">
                    {abilityViewDashboardAll &&
                      <div className="inline-block">
                        <div className="inline-block ml-6">
                          <Label className="text-slate-500 font-medium">
                            {t("Team")}:&nbsp;
                          </Label>
                        </div>
                        <div className="inline-block ml-1 w-60">
                          <Select
                            placeholder={t("Please select a team")}
                            options={teamManhoursTeamOptions}
                            isClearable={true}
                            onChange={(selectedOption: any) => {
                              if (selectedOption === null) {
                                setStaffGradeTeamId(null);
                              } else {
                                setStaffGradeTeamId(selectedOption.value);
                              }
                            }}
                            onMenuOpen={() => {
                              setDatePickerToLabel2("")
                            }}
                            onMenuClose={() => {
                              setDatePickerToLabel2(t("To"))
                            }}
                          />
                        </div>
                      </div>}
                      <div className="ml-6 mt-2" style={{ verticalAlign: "top" }}>
                      {staffGradeManhoursSpentSelect === "Weekly" && (
                        <LocalizationProvider dateAdapter={AdapterDayjs}>
                          <DatePicker
                            className="w-72 h-10 align-top"
                            label={t("Week") + ":"}
                            value={weeklyValueByStaffGrade}
                            format="DD-MM-YYYY"
                            onChange={(newValue) =>
                              selectWeeklyPeriodByStaffGrade(newValue)
                            }
                            showDaysOutsideCurrentMonth
                            displayWeekNumber
                            slots={{ day: Day }}
                            slotProps={{
                              day: (ownerState) =>
                                ({
                                  selectedDay: value,
                                  hoveredDay,
                                  onPointerEnter: () =>
                                    setHoveredDay(ownerState.day),
                                  onPointerLeave: () => setHoveredDay(null),
                                }) as any,
                            }}
                          />
                        </LocalizationProvider>
                      )}
                      {staffGradeManhoursSpentSelect === "Monthly" && (
                        
                        <LocalizationProvider dateAdapter={AdapterDayjs}>
                          <DatePicker
                            className="w-44 h-10 align-top"
                            onChange={(newValue) =>
                              selectStaffGradeMonthlyPeriodFrom(newValue)
                            }
                            defaultValue={
                              totalManHoursByStaffGradeMonthlyFromValue
                            }
                            label={t("From")}
                            views={["month", "year"]}
                            format="MM-YYYY"
                          />
                          <DatePicker
                            className="w-40 h-10 align-top"
                            onChange={(newValue) =>
                              selectStaffGradeMonthlyPeriodTo(newValue)
                            }
                            defaultValue={
                              totalManHoursByStaffGradeMonthlyToValue
                            }
                            label={datePickerToLabel2}
                            views={["month", "year"]}
                            format="MM-YYYY"
                          />
                        </LocalizationProvider>
                      )}
                      {/* <Label className="text-slate-500 font-medium ml-6">
                          Period:&nbsp;
                        </Label>
                        <Input
                          id={'cashFlowYear'}
                          value={manHoursSpentPeriod}
                          readOnly={true}
                          bsSize="lg"
                          className="rounded-md text-base w-56 border-slate-200 border-solid text-slate-500 text-center"
                        /> */}
                    </div>
                  </div>
                  <ReactApexChart
                    options={staffGradeOptions}
                    series={staffGradeOptions.series}
                    type="bar"
                    height="400"
                  />
                </div>
              </Card>
            </Grid>
          </div>
        </div>
        <div
          style={{
            display: "inline-block",
            width: "59%",
            verticalAlign: "top",
            marginLeft: 10,
          }}
          className="mt-5"
        >
          <Grid item xs={12} md={12} lg={12}>
            <Card className="mb-5">
              <CardHeader
                className="text-slate-500"
                title= {t("Unsubmitted Time Sheet by Staff")}
              />
              <div style={{ display: "inline-block", width: "99%" }}>
                <div className="w-fit align-top mr-5 float-right">
                  {unsubmittedTimeSheetSelect === "Weekly" && (
                    <>
                      <button className="text-lg bg-lime-100 border-lime-600 text-lime-600 border-solid w-32">
                        {t("Weekly")}
                      </button>
                      <button
                        onClick={() => {
                          teamTotalManhoursSpentOnClick("Monthly")
                            setUnsubmittedTimeSheetSelect("Monthly")
                            fetchMonthlyUnsubmittedData()
                            setStaffGradeManhoursSpentSelect("Monthly")
                            fetchMonthlyTotalManhoursByGradeData()
                            setIndividualStaffManhoursSpentSelect("Monthly")
                            fetchMonthlyIndividualManhoursData()
                        }
                        }
                        className="hover:cursor-pointer hover:bg-lime-50 text-lg bg-transparent border-lime-600 text-lime-600 border-solid rounded-r-md w-32"
                      >
                        {t("Monthly")}
                      </button>
                    </>
                  )}
                  {unsubmittedTimeSheetSelect === "Monthly" && (
                    <>
                      <button
                        onClick={() => {
                          teamTotalManhoursSpentOnClick("Weekly")
                            setUnsubmittedTimeSheetSelect("Weekly")
                            fetchWeeklyUnsubmittedData()
                            setStaffGradeManhoursSpentSelect("Weekly")
                            fetchTotalManhoursByGradeData()
                            setIndividualStaffManhoursSpentSelect("Weekly")
                            fetchWeeklyIndividualManhoursData()
                        }
                        }
                        className="hover:cursor-pointer hover:bg-lime-50 text-lg bg-transparent border-lime-600 text-lime-600 border-solid w-32"
                      >
                        {t("Weekly")}
                      </button>
                      <button className="text-lg bg-lime-100 border-lime-600 text-lime-600 border-solid rounded-r-md w-32">
                        {t("Monthly")}
                      </button>
                    </>
                  )}
                </div>
                <div className="inline-block w-fit mt-2">
                  {abilityViewDashboardAll && <div className="inline-block">
                    <div className="inline-block ml-6">
                      <Label className="text-slate-500 font-medium">
                        {t("Team")}:&nbsp;
                      </Label>
                    </div>
                    <div className="inline-block ml-1 w-60">
                      <Select
                        placeholder={t("Please select a team")}
                        options={teamManhoursTeamOptions}
                        isClearable={true}
                        onChange={(selectedOption: any) => {
                          if (selectedOption === null) {
                            setTeamUnsubmitTeamId(null);
                          } else {
                            setTeamUnsubmitTeamId(selectedOption.value);
                          }
                        }}
                      />
                    </div>
                  </div>}

                  <div className="ml-6 mt-2" style={{ verticalAlign: "top" }}>
                    {/* <Label className="text-slate-500 font-medium ml-6">
                          Period:&nbsp;
                        </Label> */}
                    {unsubmittedTimeSheetSelect === "Weekly" && (
                      <LocalizationProvider dateAdapter={AdapterDayjs}>
                        <DatePicker
                          className="w-72 h-10 align-top"
                          label={t("Week") + ":"}
                          value={value}
                          format="DD-MM-YYYY"
                          onChange={(newValue) =>
                            selectWeeklyPeriodUnsubmittedTimeSheet(newValue)
                          }
                          showDaysOutsideCurrentMonth
                          displayWeekNumber
                          slots={{ day: Day }}
                          slotProps={{
                            day: (ownerState) =>
                              ({
                                selectedDay: value,
                                hoveredDay,
                                onPointerEnter: () =>
                                  setHoveredDay(ownerState.day),
                                onPointerLeave: () => setHoveredDay(null),
                              }) as any,
                          }}
                        />
                      </LocalizationProvider>
                    )}
                    {unsubmittedTimeSheetSelect === "Monthly" && (
                      <LocalizationProvider dateAdapter={AdapterDayjs}>
                        <DatePicker
                          className="w-40 h-10 align-top"
                          onChange={(newValue) =>
                            selectUnsubmittedTimeSheetMonthlyPeriodFrom(newValue)
                          }
                          defaultValue={
                            unsubmitMonthlyFromValue
                          }
                          label={t("Month") + ":"}
                          views={["month", "year"]}
                          format="MM-YYYY"
                        />
                        {/* <DatePicker
                            className="w-40 h-10 align-top"
                            onChange={(newValue) =>
                              selectUnsubmittedTimeSheetMonthlyPeriodTo(newValue)
                            }
                            defaultValue={
                              totalManHoursByIndividualStaffMonthlyToValue
                            }
                            label={"To"}
                            views={["month", "year"]}
                          /> */}
                      </LocalizationProvider>
                    )}
                  </div>
                </div>

                <ReactApexChart
                  options={unsubmittedTimeSheetOptions}
                  series={unsubmittedTimeSheetOptions.series}
                  type="bar"
                  height="380"
                />
                <div className="float-right mr-4 mb-10">
                  {currentPage === 1 && (
                    <button className="bg-lime-600 text-white font-bold py-2 px-4 opacity-50 cursor-not-allowed rounded-l">
                    {t("Previous")}
                    </button>
                  )}
                  {currentPage !== 1 && (
                    <button onClick={handlePrevPage} className="bg-lime-600 hover:bg-lime-700 text-white font-bold py-2 px-4 outline-none rounded-l">
                    {t("Previous")}
                    </button>
                  )}
                  {endIndex >= unsubmitCount.length && (
                    <button className="bg-lime-600 text-white font-bold py-2 px-4 opacity-50 cursor-not-allowed rounded-r mr-2">
                    {t("Next")}
                    </button>
                  )}
                  {endIndex < unsubmitCount.length && (
                  <button onClick={handleNextPage} className="bg-lime-600 hover:bg-lime-700 text-white font-bold py-2 px-4 outline-none rounded-r mr-2">
                    {t("Next")}
                  </button>
                  )}
                  {t("Page")}&nbsp;
                  {unsubmitCount.length === 0 && (
                    0
                  )}
                  {unsubmitCount.length > 0 && (
                    currentPage
                  )}
                  &nbsp;of&nbsp;
                  {Math.ceil(unsubmitCount.length / recordsPerPage)}
                  
                 </div>
              </div>
            </Card>
            <Card>
              <Card>
                <CardHeader
                  className="text-slate-500"
                  title={t("Manhours Spent by Individual Staff")}
                />
                <div style={{ display: "inline-block", width: "99%" }}>
                  <div className="w-fit align-top mr-5 float-right">
                    {individualStaffManhoursSpentSelect === "Daily" && (
                      <>
                        <button className="text-lg bg-lime-100 border-lime-600 text-lime-600 border-solid rounded-l-md w-32">
                          Daily
                        </button>
                        <button
                          onClick={() => {
                            individualStaffManhoursSpentOnClick("Weekly")
                            fetchWeeklyIndividualManhoursData()
                          }
                          }
                          className="hover:cursor-pointer hover:bg-lime-50 text-lg bg-transparent border-lime-600 text-lime-600 border-solid w-32"
                        >
                          {t("Weekly")}
                        </button>
                        <button
                          onClick={() => {
                            individualStaffManhoursSpentOnClick("Monthly")
                            fetchMonthlyIndividualManhoursData()
                          }
                          }
                          className="hover:cursor-pointer hover:bg-lime-50 text-lg bg-transparent border-lime-600 text-lime-600 border-solid rounded-r-md w-32"
                        >
                          {t("Monthly")}
                        </button>
                      </>
                    )}
                    {individualStaffManhoursSpentSelect === "Weekly" && (
                      <>
                        {/* <button
                          onClick={() => {
                            individualStaffManhoursSpentOnClick("Daily")
                            fetchDailyIndividualManhoursData()
                          }
                          }
                          className="hover:cursor-pointer hover:bg-violet-50 text-lg bg-transparent border-violet-500 text-violet-500 border-solid rounded-l-md w-32"
                        >
                          Daily
                        </button> */}
                        <button className="text-lg bg-lime-100 border-lime-600 text-lime-600 border-solid w-32">
                          {t("Weekly")}
                        </button>
                        <button
                          onClick={() => {
                            teamTotalManhoursSpentOnClick("Monthly")
                            setUnsubmittedTimeSheetSelect("Monthly")
                            fetchMonthlyUnsubmittedData()
                            setStaffGradeManhoursSpentSelect("Monthly")
                            fetchMonthlyTotalManhoursByGradeData()
                            setIndividualStaffManhoursSpentSelect("Monthly")
                            fetchMonthlyIndividualManhoursData()
                          }
                          }
                          className="hover:cursor-pointer hover:bg-lime-50 text-lg bg-transparent border-lime-600 text-lime-600 border-solid rounded-r-md w-32"
                        >
                          {t("Monthly")}
                        </button>
                      </>
                    )}
                    {individualStaffManhoursSpentSelect === "Monthly" && (
                      <>
                        {/* <button
                          onClick={() => {
                            individualStaffManhoursSpentOnClick("Daily")
                            fetchDailyIndividualManhoursData()
                          }
                          }
                          className="hover:cursor-pointer hover:bg-violet-50 text-lg bg-transparent border-violet-500 text-violet-500 border-solid rounded-l-md w-32"
                        >
                          Daily
                        </button> */}
                        <button
                          onClick={() => {
                            teamTotalManhoursSpentOnClick("Weekly")
                            setUnsubmittedTimeSheetSelect("Weekly")
                            fetchWeeklyUnsubmittedData()
                            setStaffGradeManhoursSpentSelect("Weekly")
                            fetchTotalManhoursByGradeData()
                            setIndividualStaffManhoursSpentSelect("Weekly")
                            fetchWeeklyIndividualManhoursData()
                          }
                          }
                          className="hover:cursor-pointer hover:bg-lime-50 text-lg bg-transparent border-lime-600 text-lime-600 border-solid w-32"
                        >
                          {t("Weekly")}
                        </button>
                        <button className="text-lg bg-lime-100 border-lime-600 text-lime-600 border-solid rounded-r-md w-32">
                          {t("Monthly")}
                        </button>
                      </>
                    )}
                  </div>
                  <div className="inline-block w-fit mt-2">
                    <div className="inline-block ml-6">
                      <Label className="text-slate-500 font-medium">
                        {t("Staff Code and Name")}:&nbsp;
                      </Label>
                    </div>
                    <div className="inline-block ml-1 w-60">
                      <Select
                        placeholder={t("Please select a staff")}
                        options={staffOptions}
                        isClearable={true}
                        onChange={(selectedOption: any) => {
                          if (selectedOption === null) {
                            setStaffId(null);
                          } else {
                            setStaffId(selectedOption.value);
                          }
                        }}
                      />
                    </div>
                    <div className="ml-6 mt-2" style={{ verticalAlign: "top" }}>
                      {/* <Label className="text-slate-500 font-medium ml-6">
                          Period:&nbsp;
                        </Label> */}
                      {individualStaffManhoursSpentSelect === "Daily" && (
                        <LocalizationProvider dateAdapter={AdapterDayjs}>
                          <DatePicker
                            className="w-40 h-10 align-top"
                            format="DD-MM-YYYY"
                            onChange={(newValue: any) =>
                              setTotalManHoursByIndividualStaffDailyFromValue(newValue)
                              // selectIndividualStaffMonthlyPeriodFrom(newValue)
                            }
                            defaultValue={
                              totalManHoursByIndividualStaffDailyFromValue
                            }
                            label={t("On")}
                            views={["day"]}
                          />
                          {/* <DatePicker
                            className="w-40 h-10 align-top"
                            onChange={(newValue) =>
                              selectIndividualStaffMonthlyPeriodTo(newValue)
                            }
                            defaultValue={
                              totalManHoursByIndividualStaffDailyToValue
                            }
                            label={"To"}
                            views={["day", "month", "year"]}
                          /> */}
                        </LocalizationProvider>
                      )}
                      {individualStaffManhoursSpentSelect === "Weekly" && (
                        <LocalizationProvider dateAdapter={AdapterDayjs}>
                          <DatePicker
                            className="w-72 h-10 align-top"
                            label={t("Week") + ":"}
                            value={value}
                            format="DD-MM-YYYY"
                            onChange={(newValue) =>
                              selectWeeklyPeriodIndividualStaff(newValue)
                            }
                            showDaysOutsideCurrentMonth
                            displayWeekNumber
                            slots={{ day: Day }}
                            slotProps={{
                              day: (ownerState) =>
                                ({
                                  selectedDay: value,
                                  hoveredDay,
                                  onPointerEnter: () =>
                                    setHoveredDay(ownerState.day),
                                  onPointerLeave: () => setHoveredDay(null),
                                }) as any,
                            }}
                          />
                        </LocalizationProvider>
                      )}
                      {individualStaffManhoursSpentSelect === "Monthly" && (
                        <LocalizationProvider dateAdapter={AdapterDayjs}>
                          <DatePicker
                            className="w-40 h-10 align-top"
                            onChange={(newValue: any) => {
                              console.log(newValue)
                              setIndivdualManHoursMonthlyFromValue(newValue)
                            }
                              // selectIndividualStaffMonthlyPeriodFrom(newValue)
                            }
                            defaultValue={
                              indivdualManHoursMonthlyFromValue
                            }
                            label={t("Month") + ":"}
                            views={["month", "year"]}
                            format="MM-YYYY"
                          />
                          {/* <DatePicker
                            className="w-40 h-10 align-top"
                            onChange={(newValue) =>
                              selectIndividualStaffMonthlyPeriodTo(newValue)
                            }
                            defaultValue={
                              totalManHoursByIndividualStaffMonthlyToValue
                            }
                            label={"To"}
                            views={["month", "year"]}
                          /> */}
                        </LocalizationProvider>
                      )}
                    </div>
                  </div>

                  <ReactApexChart
                    options={individualStaffOptions}
                    series={individualStaffOptions.series}
                    type="bar"
                    height="380"
                  />
                </div>
              </Card>
              <div style={{ display: "inline-block", width: "50%" }}>
                <div
                  style={{
                    display: "inline-block",
                    width: "47%",
                    marginTop: 10,
                    marginLeft: 10,
                  }}
                >
                  <Card style={{ height: 90 }}>
                    <div className="text-slate-500 text-center text-base">
                      {t("Total Normal Hours Spent")}
                    </div>
                    <div
                      className="text-center w-full text-3xl font-bold"
                      style={{ color: "#92c1e9" }}
                    >
                      {totalNormalConsumption.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
                    </div>
                  </Card>
                  <Card style={{ marginTop: 10, height: 90 }}>
                    <div className="text-slate-500 text-center text-base">
                      {t("Total Leave Hours")}
                    </div>
                    <div
                      className="text-center w-full text-3xl font-bold"
                      style={{ color: "#898d8d", marginTop: 10 }}
                    >
                      {totalLeaveHours.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
                    </div>
                  </Card>
                </div>
                <div
                  style={{
                    display: "inline-block",
                    width: "47%",
                    marginTop: 10,
                    marginLeft: 10,
                    verticalAlign: "top"
                  }}
                >
                  <Card style={{ height: 90 }}>
                    <div className="text-slate-500 text-center text-base">
                      {t("Total Other Hours Spent")}
                    </div>
                    <div
                      className="text-center w-full text-3xl font-bold"
                      style={{ color: "#92c1e9" }}
                    >
                      {totalOtConsumption.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
                    </div>
                  </Card>
                  {/* <Card style={{ marginTop: 10, height: 90 }}>
                    <div className="text-slate-500 text-center text-base">
                      Remaining Hours
                    </div>
                    <div
                      className="text-center w-full text-3xl font-bold"
                      style={{ color: "#898d8d", marginTop: 10 }}
                    >
                      0.00
                    </div>
                  </Card> */}
                </div>
              </div>
              <div style={{ display: "inline-block", width: "50%", verticalAlign: "top", marginTop: 10 }}>
                <Card>
                  <CardHeader className="text-slat-500" title= {t("Effort Proportion for individual Staff")} />
                  <ReactApexChart
                    options={options2}
                    series={options2.series}
                    type="donut"
                  />
                </Card>
              </div>
            </Card>
          </Grid>
        </div>
      </Grid>
    </>
  );
};

export default StaffUtilization;
