import {
  RecordTimesheetInput,
  RecordLeaveInput,
} from "@/app/api/timesheets/actions";
import { manhourFormatter, shortDateFormatter } from "@/app/utils/formatUtil";
import { Box, Stack, Typography } from "@mui/material";
import dayjs from "dayjs";
import React, { useMemo } from "react";
import { useTranslation } from "react-i18next";
import TimeEntryCard from "../TimesheetTable/TimeEntryCard";
import LeaveEntryCard from "../LeaveTable/LeaveEntryCard";
import { ProjectWithTasks } from "@/app/api/projects";
import { LeaveType } from "@/app/api/timesheets";

interface Props {
  date: string;
  timesheet: RecordTimesheetInput;
  leaves: RecordLeaveInput;
  leaveTypes: LeaveType[];
  allProjects: ProjectWithTasks[];
}

const PastEntryList: React.FC<Props> = ({
  date,
  timesheet,
  leaves,
  leaveTypes,
  allProjects,
}) => {
  const {
    t,
    i18n: { language },
  } = useTranslation("home");

  const timeEntries = timesheet[date] || [];
  const leaveEntries = leaves[date] || [];

  const leaveTypeMap = useMemo<{ [id: LeaveType["id"]]: LeaveType }>(() => {
    return leaveTypes.reduce(
      (acc, leaveType) => ({ ...acc, [leaveType.id]: leaveType }),
      {},
    );
  }, [leaveTypes]);

  const projectMap = useMemo(() => {
    return allProjects.reduce<{
      [id: ProjectWithTasks["id"]]: ProjectWithTasks;
    }>((acc, project) => {
      return { ...acc, [project.id]: project };
    }, {});
  }, [allProjects]);

  if (!(timeEntries.length || leaveEntries.length)) {
    return null;
  }

  const dayJsObj = dayjs(date);

  return (
    <Stack
      gap={2}
      marginBlockEnd={2}
      minWidth={{ sm: 375 }}
      maxHeight={{ sm: 500 }}
    >
      <Typography
        variant="overline"
        color={dayJsObj.day() === 0 ? "error.main" : undefined}
      >
        {shortDateFormatter(language).format(dayJsObj.toDate())}
      </Typography>
      <Box
        flex={1}
        display="flex"
        flexDirection="column"
        gap={2}
        sx={{ overflowY: "scroll" }}
      >
        {timeEntries.map((entry, index) => {
          const project = entry.projectId
            ? projectMap[entry.projectId]
            : undefined;

          const task = project?.tasks.find((t) => t.id === entry.taskId);

          return (
            <TimeEntryCard
              key={`${entry.id}-${index}`}
              project={project}
              task={task}
              entry={entry}
            />
          );
        })}
        {leaveEntries.map((entry, index) => (
          <LeaveEntryCard
            key={`${entry.id}-${index}`}
            entry={entry}
            leaveTypeMap={leaveTypeMap}
          />
        ))}
      </Box>
      <Typography variant="overline">
        {`${t("Total Work Hours")}: ${manhourFormatter.format(
          timeEntries
            .map((entry) => (entry.inputHours ?? 0) + (entry.otHours ?? 0))
            .reduce((acc, cur) => {
              return acc + cur;
            }, 0),
        )}`}
      </Typography>
      <Typography variant="overline">
        {`${t("Total Leave Hours")}: ${manhourFormatter.format(
          leaveEntries
            .map((entry) => entry.inputHours)
            .reduce((acc, cur) => {
              return acc + cur;
            }, 0),
        )}`}
      </Typography>
    </Stack>
  );
};

export default PastEntryList;
