"use client";
import {
  ProjectCompletionReportFilter,
  ProjectCompletionReportRequest,
} from "@/app/api/reports";
import React, { useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import SearchBox, { Criterion } from "../SearchBox";
import dayjs from "dayjs";
import { INPUT_DATE_FORMAT } from "@/app/utils/formatUtil";
import { downloadFile } from "@/app/utils/commonUtil";
import { fetchProjectCompletionReport } from "@/app/api/reports/actions";

interface Props {
  teamId: number| null
}

type SearchQuery = Partial<Omit<ProjectCompletionReportFilter, "id">>;
type SearchParamNames = keyof SearchQuery;

const ProjectCompletionReport: React.FC<Props> = (
  {
    teamId
  }
) => {
  const { t } = useTranslation("report");
  const [error, setError] = useState("");
  const outstandingList = ["Regular", "Outstanding Accounts Receivable"]

  const searchCriteria: Criterion<SearchParamNames>[] = useMemo(
    () => [
      {
        label: t("Completion Date From"),
        label2: t("Completion Date To"),
        paramName: "startDate",
        type: "dateRange",
      },
      {
        label: t("Type"),
        paramName: "outstanding",
        type: "select",
        needAll: false,
        options: outstandingList
      },
    ],
    [t]
  );

  return (
    <>
      <SearchBox
        formType={"download"}
        criteria={searchCriteria}
        onSearch={async (query: any) => {
          let postData: ProjectCompletionReportRequest = {
            startDate: "1900-01-01",
            endDate: dayjs().format(INPUT_DATE_FORMAT).toString(),
            outstanding: query.outstanding && query.outstanding === "Outstanding Accounts Receivable"
          };
          console.log(query)
          if (query.startDateTo && query.startDateTo.length > 0) {
            postData.endDate = query.startDateTo;
          }
          if (teamId) {
            postData.teamId = teamId
          }
          if (query.startDate && query.startDate.length > 0) {
            postData.startDate = query.startDate;
          }
          console.log(postData)
          const response = await fetchProjectCompletionReport(postData);
          if (response) {
            downloadFile(new Uint8Array(response.blobValue), response.filename!!);
          }
        }}
      />
    </>
  );
};

export default ProjectCompletionReport;
