//src\components\LateStartReportGen\LateStartReportGen.tsx
"use client";
import React, { useMemo, useState } from "react";
// import SearchBox, { Criterion } from "../ReportSearchBoxe1";
import { useTranslation } from "react-i18next";
import { FinancialStatus, TeamCombo } from "@/app/api/reporte1";
import SearchBox, { Criterion } from "@/components/SearchBox";
import { FinancialStatusReportFilter } from "@/app/api/reports";
import { fetchAllClientSubsidiaryProjects } from "@/app/api/clientprojects/actions";
import { fetchProjectsFinancialStatusReport } from "@/app/api/reporte1/action";
import { downloadFile } from "@/app/utils/commonUtil";
import { SessionStaff } from "@/config/authConfig";
import FinancialStatusReportGenLoading from "./FinancialStatusReportGenLoading";
import dayjs from "dayjs";
//import { DownloadReportButton } from './DownloadReportButton';
interface Props {
  projects: FinancialStatus[];
  teamCombo : TeamCombo[];
  userStaff: SessionStaff;
}


interface SubComponents {
  Loading: typeof FinancialStatusReportGenLoading;
}

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

const GenFinancialStatusReport: React.FC<Props> & SubComponents = ({ projects, teamCombo, userStaff }) => {
  const { t } = useTranslation("projects");

  const combo = teamCombo.map(combo => {return `${combo.code} - ${combo.name}`})

  const searchCriteria: Criterion<SearchParamNames>[] = useMemo(
    () => [
      { label: t("Team"), paramName: "code", type: "select", options: combo, needAll: !Boolean(userStaff?.isTeamLead) },
      {
        label: "Date From",
        label2: "Date To",
        paramName: "targetDate",
        type: "dateRange",
        needMonth: true,
      },
    ],
    [t],
  );

  const [loading, setLoading] = useState(false);

  return (
    <>
      {loading && <GenFinancialStatusReport.Loading />}
      {!loading &&
      <SearchBox
        criteria={searchCriteria}
        onSearch={async (query) => {
          setLoading(true)
          let postData = {
            teamLeadId: -1,
            startMonth: "1970-01",
            endMonth: dayjs().format("YYYY-MM").toString()
          }
          if(query.targetDate){
            postData.startMonth = query.targetDate
          }

          if(query.targetDateTo){
            postData.endMonth = query.targetDateTo
          }

          if(query.code.length > 0 && query.code.toLocaleLowerCase() !== "all") {
            const projectIndex = teamCombo.findIndex((project) => `${project.code} - ${project.name}` === query.code)
            postData.teamLeadId = teamCombo[projectIndex].id
          }

          try {
            const response = await fetchProjectsFinancialStatusReport(postData)
            if (response) {
                downloadFile(new Uint8Array(response.blobValue), response.filename!!)
            }
          }catch (error){
            console.log(error)
          }

          setLoading(false)

          // if (query.code.length > 0 && query.code.toLocaleLowerCase() !== "all") {
          //   const projectIndex = teamCombo.findIndex((project) => `${project.code} - ${project.name}` === query.code)
          //   console.log(query.targetDate)
          //   console.log(query.targetDateTo)
          //   const response = await fetchProjectsFinancialStatusReport({ teamLeadId: teamCombo[projectIndex].id, startMonth: query.targetDate, endMonth: query.targetDateTo })
          //   if (response) {
          //       downloadFile(new Uint8Array(response.blobValue), response.filename!!)
          //   }
          // }else{
          //   console.log(query.code)
          //   console.log(query.targetDate)
          //   console.log(query.targetDateTo)
          //   const response = await fetchProjectsFinancialStatusReport({ teamLeadId: -1, startMonth: query.targetDate, endMonth: query.targetDateTo })
          //   if (response) {
          //       downloadFile(new Uint8Array(response.blobValue), response.filename!!)
          //   }
          // } 
          setLoading(false)
        }}
        formType="download"
      />}
      {/* <DownloadReportButton /> */}
    </>
  );
};

GenFinancialStatusReport.Loading = FinancialStatusReportGenLoading

export default GenFinancialStatusReport;
