"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";

interface Props {
  staffs: StaffResult[];
}

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

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

  const searchCriteria: Criterion<SearchParamNames>[] = useMemo(
    () => [
      {
        label: t("Staff"),
        paramName: "staff",
        type: "select",
        options: staffCombo,
        needAll: false,
      },
      {
        label: t("Date"),
        paramName: "date",
        type: "monthYear",
      },
    ],
    [t]
  );

  return (
    <>
      <SearchBox
        formType={"download"}
        criteria={searchCriteria}
        onSearch={async (query: any) => {
          const index = staffCombo.findIndex((staff) => staff === query.staff);
          const response = await fetchMonthlyWorkHoursReport({
            id: staffs[index].id,
            yearMonth: query.date,
          });
          if (response) {
            downloadFile(
              new Uint8Array(response.blobValue),
              response.filename!!
            );
          }
        }}
      />
    </>
  );
};

export default GenerateMonthlyWorkHoursReport;
