import { CreateProjectInputs } from "@/app/api/projects/actions";
import { TaskGroup } from "@/app/api/tasks";
import { moneyFormatter } from "@/app/utils/formatUtil";
import { Divider, Stack, Typography } from "@mui/material";
import React, { useCallback, useEffect, useMemo } from "react";
import { useFormContext } from "react-hook-form";
import { useTranslation } from "react-i18next";

interface Props {
  taskGroups: TaskGroup[];
}

const ProjectTotalFee: React.FC<Props> = ({ taskGroups }) => {
  const { t } = useTranslation();
  const { watch, setError, clearErrors } = useFormContext<CreateProjectInputs>();
  const milestones = watch("milestones");
  const expectedTotalFee = watch("expectedProjectFee");

  let projectTotal = 0;

  useEffect(() => {
    console.log(Object.keys(milestones).reduce((acc, key) => acc + milestones[parseInt(key)].payments.reduce((acc2, value) => acc2 + value.amount, 0), 0))
    if (Object.keys(milestones).reduce((acc, key) => acc + milestones[parseInt(key)].payments.reduce((acc2, value) => acc2 + value.amount, 0), 0) !== expectedTotalFee) {
      setError("milestones", {message: "project total is not valid", type: "invalid"})
    } else {
      clearErrors("milestones")
    }
  }, [milestones])

  return (
    <Stack spacing={1}>
      {taskGroups.map((group, index) => {
        const payments = milestones[group.id]?.payments || [];
        const paymentTotal = payments.reduce((acc, p) => acc + p.amount, 0);

        projectTotal += paymentTotal;

        return (
          <Stack
            key={`${group.id}-${index}`}
            direction="row"
            justifyContent="space-between"
          >
            <Typography variant="subtitle2">{group.name}</Typography>
            <Typography>{moneyFormatter.format(paymentTotal)}</Typography>
          </Stack>
        );
      })}
      <Divider sx={{ paddingBlockStart: 2 }} />
      <Stack direction="row" justifyContent="space-between">
        <Typography variant="h6">{t("Project Total Fee")}</Typography>
        <Typography>{moneyFormatter.format(projectTotal)}</Typography>
      </Stack>
      {projectTotal !== expectedTotalFee && (
        <Typography variant="caption" color="warning.main" alignSelf="flex-end">
          {t("Project total fee should be same as the expected total fee!")}
        </Typography>
      )}
    </Stack>
  );
};

export default ProjectTotalFee;
