import { CreateProjectInputs } from "@/app/api/projects/actions";
import { TaskGroup } from "@/app/api/tasks";
import { moneyFormatter, sumMoney } from "@/app/utils/formatUtil";
import {
  Button,
  Divider,
  Modal,
  Paper,
  Stack,
  SxProps,
  Typography,
} from "@mui/material";
import React, { useCallback, useState } from "react";
import { useFormContext } from "react-hook-form";
import { useTranslation } from "react-i18next";
import PaymentSummary from "./PaymentSummary";

interface Props {
  taskGroups: TaskGroup[];
}

const modalSx: SxProps = {
  position: "absolute",
  top: "50%",
  left: "50%",
  transform: "translate(-50%, -50%)",
  width: "90%",
  maxHeight: "90%",
  padding: 3,
  display: "flex",
  flexDirection: "column",
  gap: 2,
};

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

  const [paymentSummaryOpen, setPaymentSummaryOpen] = useState(false);
  const closePaymentSummary = useCallback(() => {
    setPaymentSummaryOpen(false);
  }, []);
  const openPaymentSummary = useCallback(() => {
    setPaymentSummaryOpen(true);
  }, []);

  let projectTotal = 0;

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

        projectTotal = sumMoney(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>
        );
      })}
      <Button
        variant="outlined"
        size="small"
        sx={{ alignSelf: "flex-start" }}
        onClick={openPaymentSummary}
      >
        {t("View payment breakdown")}
      </Button>
      <Modal open={paymentSummaryOpen} onClose={closePaymentSummary}>
        <Paper sx={modalSx}>
          <PaymentSummary taskGroups={taskGroups} />
        </Paper>
      </Modal>
      <Divider sx={{ paddingBlockStart: 2 }} />
      <Stack direction="row" justifyContent="space-between">
        <Typography variant="h6">
          {t("Sum of Payment Milestone Fee")}
        </Typography>
        <Typography>{moneyFormatter.format(projectTotal)}</Typography>
      </Stack>
      <Divider sx={{ paddingBlockStart: 2 }} />
      <Stack direction="row" justifyContent="space-between">
        <Typography variant="h6">{t("Expected Total Fee")}</Typography>
        <Typography>{moneyFormatter.format(expectedTotalFee)}</Typography>
      </Stack>
      {projectTotal !== expectedTotalFee && (
        <Typography variant="caption" color="warning.main" alignSelf="flex-end">
          {t(
            "Sum of Payment Milestone Fee should be same as the expected total fee!",
          )}
        </Typography>
      )}
    </Stack>
  );
};

export default ProjectTotalFee;
