import React, { useCallback, useMemo } from "react";
import {
  Box,
  Button,
  Card,
  CardActions,
  CardContent,
  Modal,
  ModalProps,
  SxProps,
  Typography,
} from "@mui/material";
import TimesheetTable from "../TimesheetTable";
import { useTranslation } from "react-i18next";
import { Check, Close } from "@mui/icons-material";
import { FormProvider, SubmitHandler, useForm } from "react-hook-form";
import {
  RecordLeaveInput,
  RecordTimesheetInput,
  saveTimesheet,
} from "@/app/api/timesheets/actions";
import dayjs from "dayjs";
import { INPUT_DATE_FORMAT } from "@/app/utils/formatUtil";
import { AssignedProject, ProjectWithTasks } from "@/app/api/projects";
import FullscreenModal from "../FullscreenModal";
import MobileTimesheetTable from "../TimesheetTable/MobileTimesheetTable";
import useIsMobile from "@/app/utils/useIsMobile";
import { HolidaysResult } from "@/app/api/holidays";
import {
  DAILY_NORMAL_MAX_HOURS,
  TIMESHEET_DAILY_MAX_HOURS,
  validateTimesheet,
} from "@/app/api/timesheets/utils";
import ErrorAlert from "../ErrorAlert";

interface Props {
  isOpen: boolean;
  onClose: () => void;
  allProjects: ProjectWithTasks[];
  assignedProjects: AssignedProject[];
  username: string;
  defaultTimesheets?: RecordTimesheetInput;
  leaveRecords: RecordLeaveInput;
  companyHolidays: HolidaysResult[];
  fastEntryEnabled?: boolean;
}

const modalSx: SxProps = {
  position: "absolute",
  top: "50%",
  left: "50%",
  transform: "translate(-50%, -50%)",
  width: { xs: "calc(100% - 2rem)", sm: "90%" },
  maxHeight: "90%",
  maxWidth: 1400,
};

const TimesheetModal: React.FC<Props> = ({
  isOpen,
  onClose,
  allProjects,
  assignedProjects,
  username,
  defaultTimesheets,
  leaveRecords,
  companyHolidays,
  fastEntryEnabled,
}) => {
  const { t } = useTranslation("home");

  const defaultValues = useMemo(() => {
    const today = dayjs();
    return Array(7)
      .fill(undefined)
      .reduce<RecordTimesheetInput>((acc, _, index) => {
        const date = today.subtract(index, "day").format(INPUT_DATE_FORMAT);
        return {
          ...acc,
          [date]: defaultTimesheets?.[date] ?? [],
        };
      }, {});
  }, [defaultTimesheets]);

  const formProps = useForm<RecordTimesheetInput>({ defaultValues });

  const onSubmit = useCallback<SubmitHandler<RecordTimesheetInput>>(
    async (data) => {
      const errors = validateTimesheet(data, leaveRecords, companyHolidays);
      if (errors) {
        Object.keys(errors).forEach((date) =>
          formProps.setError(date, {
            message: errors[date],
          }),
        );
        return;
      }
      const savedRecords = await saveTimesheet(data, username);

      const today = dayjs();
      const newFormValues = Array(7)
        .fill(undefined)
        .reduce<RecordTimesheetInput>((acc, _, index) => {
          const date = today.subtract(index, "day").format(INPUT_DATE_FORMAT);
          return {
            ...acc,
            [date]: savedRecords[date] ?? [],
          };
        }, {});

      formProps.reset(newFormValues);
      onClose();
    },
    [companyHolidays, formProps, leaveRecords, onClose, username],
  );

  const onCancel = useCallback(() => {
    formProps.reset(defaultValues);
    onClose();
  }, [defaultValues, formProps, onClose]);

  const onModalClose = useCallback<NonNullable<ModalProps["onClose"]>>(
    (_, reason) => {
      if (reason !== "backdropClick") {
        onClose();
      }
    },
    [onClose],
  );

  const errorComponent = (
    <ErrorAlert
      errors={Object.keys(formProps.formState.errors).map((date) => {
        const error = formProps.formState.errors[date]?.message;
        return error
          ? `${date}: ${t(error, {
              TIMESHEET_DAILY_MAX_HOURS,
              DAILY_NORMAL_MAX_HOURS,
            })}`
          : undefined;
      })}
    />
  );

  const matches = useIsMobile();

  return (
    <FormProvider {...formProps}>
      {!matches ? (
        // Desktop version
        <Modal open={isOpen} onClose={onModalClose}>
          <Card sx={modalSx}>
            <CardContent
              component="form"
              onSubmit={formProps.handleSubmit(onSubmit)}
            >
              <Typography variant="overline" display="block" marginBlockEnd={1}>
                {t("Timesheet Input")}
              </Typography>
              <Box
                sx={{
                  marginInline: -3,
                  marginBlock: 4,
                }}
              >
                <TimesheetTable
                  companyHolidays={companyHolidays}
                  assignedProjects={assignedProjects}
                  allProjects={allProjects}
                  leaveRecords={leaveRecords}
                  fastEntryEnabled={fastEntryEnabled}
                />
              </Box>
              {errorComponent}
              <CardActions sx={{ justifyContent: "flex-end" }}>
                <Button
                  variant="outlined"
                  startIcon={<Close />}
                  onClick={onCancel}
                >
                  {t("Cancel")}
                </Button>
                <Button variant="contained" startIcon={<Check />} type="submit">
                  {t("Save")}
                </Button>
              </CardActions>
            </CardContent>
          </Card>
        </Modal>
      ) : (
        // Mobile version
        <FullscreenModal
          open={isOpen}
          onClose={onModalClose}
          closeModal={onCancel}
        >
          <Box
            display="flex"
            flexDirection="column"
            gap={2}
            height="100%"
            component="form"
            onSubmit={formProps.handleSubmit(onSubmit)}
          >
            <Typography variant="h6" padding={2} flex="none">
              {t("Timesheet Input")}
            </Typography>
            <MobileTimesheetTable
              fastEntryEnabled={fastEntryEnabled}
              companyHolidays={companyHolidays}
              assignedProjects={assignedProjects}
              allProjects={allProjects}
              leaveRecords={leaveRecords}
              errorComponent={errorComponent}
            />
          </Box>
        </FullscreenModal>
      )}
    </FormProvider>
  );
};

export default TimesheetModal;
