"use client";

import React, { useCallback, useState } from "react";
import { useTranslation } from "react-i18next";
import Button from "@mui/material/Button";
import Stack from "@mui/material/Stack";
import {
  CalendarMonth,
  EditCalendar,
  Luggage,
  MoreTime,
} from "@mui/icons-material";
import { Menu, MenuItem, SxProps, Typography } from "@mui/material";
import AssignedProjects from "./AssignedProjects";
import { AssignedProject, ProjectWithTasks } from "@/app/api/projects";
import {
  RecordLeaveInput,
  RecordTimesheetInput,
  revalidateCacheAfterAmendment,
} from "@/app/api/timesheets/actions";
import { LeaveType, TeamLeaves, TeamTimeSheets } from "@/app/api/timesheets";
import { CalendarIcon } from "@mui/x-date-pickers";
import PastEntryCalendarModal from "../PastEntryCalendar/PastEntryCalendarModal";
import { HolidaysResult } from "@/app/api/holidays";
import { TimesheetAmendmentModal } from "../TimesheetAmendment/TimesheetAmendmentModal";
import TimeLeaveModal from "../TimeLeaveModal/TimeLeaveModal";
import LeaveModal from "../LeaveModal";
import { Task } from "@/app/api/tasks";
import dayjs from "dayjs";

export interface Props {
  leaveTypes: LeaveType[];
  allProjects: ProjectWithTasks[];
  assignedProjects: AssignedProject[];
  defaultLeaveRecords: RecordLeaveInput;
  defaultTimesheets: RecordTimesheetInput;
  holidays: HolidaysResult[];
  teamTimesheets: TeamTimeSheets;
  teamLeaves: TeamLeaves;
  fastEntryEnabled: boolean;
  maintainNormalStaffWorkspaceAbility: boolean;
  maintainManagementStaffWorkspaceAbility: boolean;
  isFullTime: boolean;
  joinDate?: number | null;
  miscTasks: Task[];
  isSaturdayWorker: boolean;
  userId: number;
}

const menuItemSx: SxProps = {
  gap: 1,
  color: "neutral.700",
};

const UserWorkspacePage: React.FC<Props> = ({
  leaveTypes,
  allProjects,
  assignedProjects,
  defaultLeaveRecords,
  defaultTimesheets,
  holidays,
  teamTimesheets,
  teamLeaves,
  fastEntryEnabled,
  maintainNormalStaffWorkspaceAbility,
  maintainManagementStaffWorkspaceAbility,
  isFullTime,
  joinDate,
  miscTasks,
  isSaturdayWorker,
  userId
}) => {
  const [latestTeamTimesheets, setLatestTeamTimesheets] = useState(teamTimesheets)
  const [latestTeamLeaves, setLatestTeamLeaves] = useState(teamLeaves)

  const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null);

  const [isTimeLeaveModalVisible, setTimeLeaveModalVisible] = useState(false);
  const [isLeaveCalendarVisible, setLeaveCalendarVisible] = useState(false);
  const [isPastEventModalVisible, setPastEventModalVisible] = useState(false);
  const [isTimesheetAmendmentVisible, setisTimesheetAmendmentVisible] =
    useState(false);
  const { t } = useTranslation("home");

  const showTimesheetAmendment = Object.keys(teamTimesheets).length > 0;

  const handleOpenActionMenu = useCallback<
    React.MouseEventHandler<HTMLButtonElement>
  >((event) => {
    setAnchorEl(event.currentTarget);
  }, []);

  const handleCloseActionMenu = useCallback(() => {
    setAnchorEl(null);
  }, []);

  const handleAddTimeLeaveButton = useCallback(() => {
    setAnchorEl(null);
    setTimeLeaveModalVisible(true);
  }, []);

  const handleCloseTimeLeaveModal = useCallback(() => {
    setTimeLeaveModalVisible(false);
  }, []);

  const handleOpenLeaveCalendarButton = useCallback(() => {
    setAnchorEl(null);
    setLeaveCalendarVisible(true);
  }, []);

  const handleCloseLeaveCalendarButton = useCallback(() => {
    setLeaveCalendarVisible(false);
  }, []);

  const handlePastEventClick = useCallback(() => {
    setAnchorEl(null);
    setPastEventModalVisible(true);
  }, []);

  const handlePastEventClose = useCallback(() => {
    setPastEventModalVisible(false);
  }, []);

  const handleAmendmentClick = useCallback(() => {
    setAnchorEl(null);
    setisTimesheetAmendmentVisible(true);
  }, []);

  const handleAmendmentClose = useCallback(() => {
    setisTimesheetAmendmentVisible(false);
    revalidateCacheAfterAmendment();
  }, []);


  const handleTeamTimesheetsUpdate = useCallback((ts: TeamTimeSheets) => {
    setLatestTeamTimesheets(() => ts)
  }, [])

  const handleTeamLeavesUpdate = useCallback((le: TeamLeaves) => {
    setLatestTeamLeaves(() => le)
  }, [])

  return (
    <>
      <Stack
        direction="row"
        justifyContent="space-between"
        flexWrap="wrap"
        rowGap={2}
      >
        <Typography variant="h4" marginInlineEnd={2}>
          {t("User Workspace")}
        </Typography>
        <Button
          startIcon={<CalendarIcon />}
          variant="contained"
          onClick={handleOpenActionMenu}
        >
          {t("Timesheet Actions")}
        </Button>
      </Stack>
      <Menu
        anchorEl={anchorEl}
        open={Boolean(anchorEl)}
        onClose={handleCloseActionMenu}
        anchorOrigin={{
          vertical: "bottom",
          horizontal: "right",
        }}
        transformOrigin={{
          vertical: "top",
          horizontal: "right",
        }}
      >
        <MenuItem onClick={handleAddTimeLeaveButton} sx={menuItemSx}>
          <MoreTime />
          {t("Enter Timesheet")}
        </MenuItem>
        <MenuItem onClick={handleOpenLeaveCalendarButton} sx={menuItemSx}>
          <Luggage />
          {t("Record Leave")}
        </MenuItem>
        <MenuItem onClick={handlePastEventClick} sx={menuItemSx}>
          <CalendarMonth />
          {t("View Past Entries")}
        </MenuItem>
        {showTimesheetAmendment && (
          <MenuItem onClick={handleAmendmentClick} sx={menuItemSx}>
            <EditCalendar />
            {t("Timesheet Amendments")}
          </MenuItem>
        )}
      </Menu>
      <PastEntryCalendarModal
        open={isPastEventModalVisible}
        handleClose={handlePastEventClose}
        timesheet={defaultTimesheets}
        leaves={defaultLeaveRecords}
        allProjects={allProjects}
        leaveTypes={leaveTypes}
        companyHolidays={holidays}
      />
      <TimeLeaveModal
        fastEntryEnabled={fastEntryEnabled}
        companyHolidays={holidays}
        isOpen={isTimeLeaveModalVisible}
        onClose={handleCloseTimeLeaveModal}
        leaveTypes={leaveTypes}
        allProjects={allProjects}
        assignedProjects={assignedProjects}
        timesheetRecords={defaultTimesheets}
        leaveRecords={defaultLeaveRecords}
        isFullTime={isFullTime}
        joinDate={dayjs(joinDate)}
        isSaturdayWorker={isSaturdayWorker}
        miscTasks={miscTasks}
      />
      <LeaveModal
        open={isLeaveCalendarVisible}
        onClose={handleCloseLeaveCalendarButton}
        leaveTypes={leaveTypes}
        companyHolidays={holidays}
        allProjects={allProjects}
        leaveRecords={defaultLeaveRecords}
        timesheetRecords={defaultTimesheets}
        isFullTime={isFullTime}
        joinDate={dayjs(joinDate)}
        isSaturdayWorker={isSaturdayWorker}
      />
      {assignedProjects.length > 0 ? (
        <AssignedProjects
          assignedProjects={assignedProjects}
          maintainNormalStaffWorkspaceAbility={
            maintainNormalStaffWorkspaceAbility
          }
          maintainManagementStaffWorkspaceAbility={
            maintainManagementStaffWorkspaceAbility
          }
        />
      ) : (
        <Typography variant="subtitle1">
          {t("You have no assigned projects!")}
        </Typography>
      )}
      {showTimesheetAmendment && (
        <TimesheetAmendmentModal
          allProjects={allProjects}
          leaveTypes={leaveTypes}
          companyHolidays={holidays}
          teamLeaves={latestTeamLeaves}
          handleTeamLeavesUpdate={handleTeamLeavesUpdate}
          teamTimesheets={latestTeamTimesheets}
          handleTeamTimesheetsUpdate={handleTeamTimesheetsUpdate}
          open={isTimesheetAmendmentVisible}
          onClose={handleAmendmentClose}
          miscTasks={miscTasks}
          isSaturdayWorker={isSaturdayWorker}
          userId={userId}
        />
      )}
    </>
  );
};

export default UserWorkspacePage;