"use client";

import { ProjectManhourSummaryReportFilter } from "@/app/api/reports";
import SearchBox, { Criterion } from "../SearchBox";
import { useMemo } from "react";
import { useTranslation } from "react-i18next";
import { TeamResult } from "@/app/api/team";
import { fetchProjectManhourSummaryReport } from "@/app/api/reports/actions";
import { downloadFile } from "@/app/utils/commonUtil";
import dayjs from "dayjs";

interface Props {
    teams: TeamResult[]
}

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

const ProjectManhourSummaryReport: React.FC<Props> = ({ teams }) => {
  const { t } = useTranslation("report");
  const teamsCombo = teams.map((team) => ({label: `${team.code} - ${team.name}`, value: team.id}))

    const searchCriteria: Criterion<SearchParamNames>[] = useMemo(
        () => [
          {
            label: t("Start Date"),
            paramName: "startDate",
            type: "monthYear",
          },
          {
            label: t("End Date"),
            paramName: "endDate",
            type: "monthYear",
          },
          {
            label: t("Team"),
            paramName: "teamId",
            type: "autocomplete",
            options: teamsCombo,
            needAll: false,
          },
        ],
        [t]
      );
      return (
        <>
          <SearchBox
            formType={"download"}
            criteria={searchCriteria}
            onSearch={async (query: any) => {
                console.log(query);
                var startDate = dayjs(query.startDate).format("YYYY-MM-DD")
                var endDate = dayjs(query.endDate).add(1, "month").format("YYYY-MM-DD")
                const args = {
                  teamId: query.teamId,
                  startDate: startDate,
                  endDate: endDate,
                }
                console.log(args)
                const response = await fetchProjectManhourSummaryReport(args);//
                if (response) {
                  downloadFile(
                    new Uint8Array(response.blobValue),
                    response.filename!!
                  );
                }
            }}
          />
        </>)
}
export default ProjectManhourSummaryReport