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


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

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

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

const GenerateLastModifiedReport: 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("Date"),
        paramName: "date",
        type: "date",
      },
      {
        label: t("Range"),
        paramName: "dayRange",
        type: "autocomplete",
        options: [
          {label: t("Past 30 Days"), value: 30},
          {label: t("Past 60 Days"), value: 60},
          {label: t("Past 90 Days"), value: 90},
        ],
        needAll: false
      }
    ],
    [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 = {
            dateString: dayjs().format("YYYY-MM-DD").toString(),
            holidays: uniqueHoliday,
            dayRange: query.dayRange
          };
          console.log(query.date.length > 0)
          if (query.date.length > 0) {
            postData.dateString = query.date
          }
          console.log(postData)
          const response = await fetchLastModifiedReport(postData);
          if (response) {
            downloadFile(
              new Uint8Array(response.blobValue),
              response.filename!!
            );
          }
        }}
      />
    </> 
  );
};

export default GenerateLastModifiedReport;
