"use client";
import React, { useMemo } from "react";
import SearchBox, { Criterion } from "../SearchBox";
import { useTranslation } from "react-i18next";
import { ProjectResult } from "@/app/api/projects";
import {
  fetchProjectMonthlyReport,
} from "@/app/api/reports/actions";
import { downloadFile } from "@/app/utils/commonUtil";
import { ProjectMonthlyReportFilter } from "@/app/api/reports";


import dayjs from "dayjs";
import { getPublicHolidaysForNYears } from "@/app/utils/holidayUtils";

interface Props {
  projects: ProjectResult[];
  companyHolidays: String[];
}

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

const GenerateProjectMonthlyReport: React.FC<Props> = ({ projects, companyHolidays }) => {
  const { t } = useTranslation("report");
  const projectCombo = projects.map((project) => ({label: `${project.code} - ${project.name}`, value: project.id}))
  console.log(companyHolidays)

  const searchCriteria: Criterion<SearchParamNames>[] = useMemo(
    () => [
      {
        label: t("Project"),
        paramName: "projects",
        type: "autocomplete",
        options: projectCombo,
        needAll: false,
      },
      {
        label: t("Date"),
        paramName: "date",
        type: "monthYear",
      },
    ],
    [t]
  );
  
  return (
    <>
      <SearchBox
        formType={"download"}
        criteria={searchCriteria}
        onSearch={async (query: any) => {
          
          console.log(query);
          const yearNeeded = parseInt(dayjs(query.date).format("YYYY"))
          const holidayList: String[] = [...getPublicHolidaysForNYears(1, yearNeeded).map((item) => dayjs(item.date).format("DD/MM/YYYY")), ...companyHolidays]
          const uniqueHoliday = holidayList.filter((value, index, arr) => index === arr.indexOf(value));

          let postData = {
            projectId: query.projects,
            yearMonth: dayjs().format("YYYY-MM").toString(),
            holidays: uniqueHoliday
          };
          console.log(query.date.length > 0)
          if (query.date.length > 0) {
            postData.yearMonth = query.date
          }
          console.log(postData)
          const response = await fetchProjectMonthlyReport(postData);
          if (response) {
            downloadFile(
              new Uint8Array(response.blobValue),
              response.filename!!
            );
          }
        }}
      />
    </> 
  );
};

export default GenerateProjectMonthlyReport;
