//src\components\LateStartReportGen\LateStartReportGen.tsx
"use client";
import React, { useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { LateStart } from "@/app/api/report";
//import { DownloadReportButton } from './DownloadReportButton';
// import axios from 'axios';
import { apiPath } from '../../../auth/utils';
import { fetchTeamCombo } from "@/app/api/team/actions";
import SearchBox, { Criterion } from "@/components/SearchBox";
import { TeamResult, combo, comboProp } from "@/app/api/team";
import { Customer } from "@/app/api/customer";
import { downloadFile } from "@/app/utils/commonUtil";
import { fetchLateStartReport } from "@/app/api/reports/actions";
import { LateStartReportRequest } from "@/app/api/reports";
import { Subsidiary } from "@/app/api/subsidiary";
import { SessionStaff } from "@/config/authConfig";
//import { GET_QC_CATEGORY_COMBO } from 'utils/ApiPathConst';
interface Props {
  teams: TeamResult[];
  projects: LateStart[];
  clients: Customer[];
  subsidiaries: Subsidiary[];
  userStaff: SessionStaff;
}
type SearchQuery = Partial<Omit<LateStartReportRequest, "id">>;
type SearchParamNames = keyof SearchQuery;

const ProgressByClientSearch: React.FC<Props> = ({ teams, userStaff, projects, clients,subsidiaries }) => {
  //console.log(customers)
  const { t } = useTranslation("projects");
  const teamCombo = teams.map(team => `${team.code} - ${team.name}`)
  const [isLoading, setIsLoading] = useState(true)

  const clientCombo = clients.map(client => ({
    value: `client: ${client.id}` ,
    label: `${client.code} - ${client.name}`,
    group: t("Client")
}))

const subsidiaryCombo = subsidiaries.map(subsidiary => ({
    value: `subsidiary: ${subsidiary.id}`,
    label: `${subsidiary.code} - ${subsidiary.name}`,
    group: t("Subsidiary")
}))

  const searchCriteria: Criterion<SearchParamNames>[] = useMemo(
    () => [
      { label: "Team", paramName: "teamId", type: "select", options: teamCombo, needAll: !Boolean(userStaff?.isTeamLead) },
      //{ label: "Client", paramName: "clientId", type: "autocomplete", options: clients.map(customer => `${customer.code}-${customer.name}`) },
      { label: t("Client"), paramName: "clientId", type: "autocomplete", options: [...subsidiaryCombo, ...clientCombo] },
      {
        label: "Next Stage Due Date From",
        label2: "Next Stage Due Date To",
        paramName: "remainedDate",
        type: "dateRange",
      },
    ],
    [t, teamCombo, clients, userStaff],
  );

  return (
    <>
      <SearchBox
        formType={"download"}
        criteria={searchCriteria}
        onSearch={async (query) => {
          //console.log(query);

          try {
            // const teamId = teamCombo.find(team => team.label === query.teamId)?.id!!
            // const clientId = customers.find(customer => `${customer.code}-${customer.name}` === query.clientId)?.id!!
            const teamId = teams.find(team => `${team.code} - ${team.name}` === query.teamId)?.id || 0;
            const clientId = clients.find(customer => `${customer.code}-${customer.name}` === query.clientId)?.id || 0;
            const remainedDate = query.remainedDate || "1900-01-01";
            const remainedDateTo = query.remainedDateTo || "2100-12-31";
            const clientIndex = clientCombo.findIndex(client => client.value === query.clientId)
            const subsidiaryIndex = subsidiaryCombo.findIndex(subsidiary => subsidiary.value === query.clientId)

            const fileResponse = await fetchLateStartReport({teamId: teamId, 
              clientId: clientIndex >= 0 ? clients[clientIndex].id : subsidiaryIndex >= 0 ? subsidiaries[subsidiaryIndex].id : 0, 
              remainedDate: remainedDate, remainedDateTo: remainedDateTo,
              type: clientIndex >= 0 ? "client" : subsidiaryIndex >= 0 ? "subsidiary" : "All",});
            if (fileResponse) {
              downloadFile(new Uint8Array(fileResponse.blobValue), fileResponse.filename!!)
          }
          } catch (err) {
            console.log(err)
          }
          //console.log(teamCombo.find(team => team.label === query.team)?.id);
        }}
      />
      {/* <DownloadReportButton /> */}
    </>
  );
};

export default ProgressByClientSearch;
