"use client";
import React, { useMemo } from "react";
import SearchBox, { Criterion } from "../SearchBox";
import { useTranslation } from "react-i18next";
import { ProjectResult } from "@/app/api/projects";
import {
  fetchMonthlyWorkHoursReport,
  fetchProjectCashFlowReport,
} from "@/app/api/reports/actions";
import { downloadFile } from "@/app/utils/commonUtil";
import { BASE_API_URL } from "@/config/api";
import { MonthlyWorkHoursReportFilter } from "@/app/api/reports";
import { records } from "@/app/api/staff/actions";
import { StaffResult } from "@/app/api/staff";
import dayjs from "dayjs";
import { getPublicHolidaysForNYears } from "@/app/utils/holidayUtils";

interface Props {
  staffs: StaffResult[];
  companyHolidays: String[];
}

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

const GenerateMonthlyWorkHoursReport: React.FC<Props> = ({ staffs, companyHolidays }) => {
  const { t } = useTranslation("report");
  const staffCombo = staffs.map((staff) => ({label: `${staff.name} - ${staff.staffId}`, value: staff.id}))
  console.log(companyHolidays)

  const searchCriteria: Criterion<SearchParamNames>[] = useMemo(
    () => [
      {
        label: t("Staff"),
        paramName: "staff",
        type: "autocomplete",
        options: staffCombo,
        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 = {
            id: query.staff,
            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 fetchMonthlyWorkHoursReport(postData);
          if (response) {
            downloadFile(
              new Uint8Array(response.blobValue),
              response.filename!!
            );
          }
        }}
      />
    </> 
  );
};

export default GenerateMonthlyWorkHoursReport;
