"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 {
}

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

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

  const searchCriteria: Criterion<SearchParamNames>[] = useMemo(
    () => [
      {
        label: t("startDate"),
        label2: t("endDate"),
        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) => {
          console.log(query);
          let postData: ProjectCompletionReportRequest = {
            startDate: "",
            endDate: dayjs().format(INPUT_DATE_FORMAT).toString(),
            outstanding: false
          };
          if (query.endDate && query.endDate.length > 0) {
            postData.endDate = query.endDate;
          }

          // check if start date exist
          if (query.startDate.length === 0) {
            setError(t("Start Date cant be empty"));
          } else {
            postData.startDate = query.startDate;
            if (query.outstanding && query.outstanding === "Outstanding Accounts Receivable") {
                // outstanding report
                postData.outstanding = true
            }
            console.log(postData)
            const response =
              await fetchProjectCompletionReport(
                postData
              );
            // normal report

            if (response) {
              downloadFile(
                new Uint8Array(response.blobValue),
                response.filename!!
              );
            }
          }
        }}
      />
    </>
  );
};

export default ProjectCompletionReport;
