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 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 } = useFormContext<CreateProjectInputs>();
  const milestones = watch("milestones");

  let projectTotal = 0;

  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>
    </Stack>
  );
};

export default ProjectTotalFee;
