import { useMemo } from "react";
import StyledDataGrid from "../StyledDataGrid";
import { GridColDef, GridValidRowModel } from "@mui/x-data-grid";
import { useTranslation } from "react-i18next";
import dayjs from "dayjs";
import { moneyFormatter, OUTPUT_DATE_FORMAT } from "@/app/utils/formatUtil";
import { CreateProjectInputs } from "@/app/api/projects/actions";
import { useFormContext } from "react-hook-form";
import { TaskGroup } from "@/app/api/tasks";

interface Props {
  taskGroups: TaskGroup[];
}

interface Row extends GridValidRowModel {
  taskStage: string;
  description: string;
  date: string;
  amount: number;
}

const PaymentSummary: React.FC<Props> = ({ taskGroups }) => {
  const { t } = useTranslation();

  const { watch } = useFormContext<CreateProjectInputs>();
  const milestones = watch("milestones");
  const rows = useMemo<Row[]>(() => {
    return taskGroups.flatMap((group) => {
      const payments = milestones[group.id]?.payments || [];
      return payments.map(({ description, date, amount, id }) => ({
        id,
        taskStage: group.name,
        description,
        date,
        amount,
      }));
    });
  }, [milestones, taskGroups]);

  const columns = useMemo<GridColDef<GridValidRowModel>[]>(
    () => [
      { field: "taskStage", headerName: t("Task Stage"), width: 300 },
      {
        field: "description",
        headerName: t("Payment Milestone Description"),
        width: 300,
      },
      {
        field: "date",
        headerName: t("Payment Milestone Date"),
        width: 200,
        type: "date",
        valueFormatter(params) {
          return dayjs(params.value).format(OUTPUT_DATE_FORMAT);
        },
      },
      {
        field: "amount",
        headerName: t("Payment Milestone Amount"),
        width: 300,
        type: "number",
        valueFormatter(params) {
          return moneyFormatter.format(params.value);
        },
      },
    ],
    [t],
  );

  return <StyledDataGrid columns={columns} rows={rows} />;
};

export default PaymentSummary;
