"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 TimesheetModal from "../TimesheetModal";
import { AssignedProject, ProjectWithTasks } from "@/app/api/projects";
import {
  RecordLeaveInput,
  RecordTimesheetInput,
  revalidateCacheAfterAmendment,
} from "@/app/api/timesheets/actions";
import LeaveModal from "../LeaveModal";
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";

export interface Props {
  leaveTypes: LeaveType[];
  allProjects: ProjectWithTasks[];
  assignedProjects: AssignedProject[];
  username: string;
  defaultLeaveRecords: RecordLeaveInput;
  defaultTimesheets: RecordTimesheetInput;
  holidays: HolidaysResult[];
  teamTimesheets: TeamTimeSheets;
  teamLeaves: TeamLeaves;
  fastEntryEnabled?: boolean;
}

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

const UserWorkspacePage: React.FC<Props> = ({
  leaveTypes,
  allProjects,
  assignedProjects,
  username,
  defaultLeaveRecords,
  defaultTimesheets,
  holidays,
  teamTimesheets,
  teamLeaves,
  fastEntryEnabled,
}) => {
  const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null);

  const [isTimeheetModalVisible, setTimeheetModalVisible] = useState(false);
  const [isLeaveModalVisible, setLeaveModalVisible] = 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 handleAddTimesheetButtonClick = useCallback(() => {
    setAnchorEl(null);
    setTimeheetModalVisible(true);
  }, []);

  const handleCloseTimesheetModal = useCallback(() => {
    setTimeheetModalVisible(false);
  }, []);

  const handleAddLeaveButtonClick = useCallback(() => {
    setAnchorEl(null);
    setLeaveModalVisible(true);
  }, []);

  const handleCloseLeaveModal = useCallback(() => {
    setLeaveModalVisible(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();
  }, []);

  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={handleAddTimesheetButtonClick} sx={menuItemSx}>
          <MoreTime />
          {t("Enter Time")}
        </MenuItem>
        <MenuItem onClick={handleAddLeaveButtonClick} 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 Amendment")}
          </MenuItem>
        )}
      </Menu>
      <PastEntryCalendarModal
        open={isPastEventModalVisible}
        handleClose={handlePastEventClose}
        timesheet={defaultTimesheets}
        leaves={defaultLeaveRecords}
        allProjects={allProjects}
        leaveTypes={leaveTypes}
      />
      <TimesheetModal
        fastEntryEnabled={fastEntryEnabled}
        companyHolidays={holidays}
        isOpen={isTimeheetModalVisible}
        onClose={handleCloseTimesheetModal}
        allProjects={allProjects}
        assignedProjects={assignedProjects}
        username={username}
        defaultTimesheets={defaultTimesheets}
        leaveRecords={defaultLeaveRecords}
      />
      <LeaveModal
        companyHolidays={holidays}
        leaveTypes={leaveTypes}
        isOpen={isLeaveModalVisible}
        onClose={handleCloseLeaveModal}
        defaultLeaveRecords={defaultLeaveRecords}
        timesheetRecords={defaultTimesheets}
        username={username}
      />
      {assignedProjects.length > 0 ? (
        <AssignedProjects assignedProjects={assignedProjects} />
      ) : (
        <Typography variant="subtitle1">
          {t("You have no assigned projects!")}
        </Typography>
      )}
      {showTimesheetAmendment && (
        <TimesheetAmendmentModal
          allProjects={allProjects}
          leaveTypes={leaveTypes}
          companyHolidays={holidays}
          teamLeaves={teamLeaves}
          teamTimesheets={teamTimesheets}
          open={isTimesheetAmendmentVisible}
          onClose={handleAmendmentClose}
        />
      )}
    </>
  );
};

export default UserWorkspacePage;
