"use client";
import { CostAndExpenseReportFilter, CostAndExpenseReportRequest } from "@/app/api/reports";
import { useTranslation } from "react-i18next";
import SearchBox, { Criterion } from "../SearchBox";
import { useMemo } from "react";
import { TeamResult } from "@/app/api/team";
import { Customer } from "@/app/api/customer";
import { fetchCostAndExpenseReport } from "@/app/api/reports/actions";
import { downloadFile } from "@/app/utils/commonUtil";

interface Props {
  team: TeamResult[];
  customer: Customer[];
}

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

const CostAndExpenseReport: React.FC<Props> = ({ team, customer }) => {
  const { t } = useTranslation("report");
  const teamCombo = team.map((t) => `${t.name} - ${t.code}`);
  const custCombo = customer.map(c => `${c.name} - ${c.code}`)

  const searchCriteria: Criterion<SearchParamNames>[] = useMemo(
    () => [
      {
        label: t("Team"),
        paramName: "team",
        type: "select",
        options: teamCombo,
        needAll: true,
      },
      {
        label: t("Client"),
        paramName: "customer",
        type: "select",
        options: custCombo,
        needAll: true,
      },
      {
        label: t("Remaining Percentage"),
        paramName: "budgetPercentage",
        type: "number",
      },
    ],
    [t]
  );

  return (
    <>
      <SearchBox
        formType={"download"}
        criteria={searchCriteria}
        onSearch={async (query: any) => {
            let index = 0
            let postData: CostAndExpenseReportRequest = {
                teamId: null,
                clientId: null,
                budgetPercentage: 0.5
            }
            console.log(query.budgetPercentage)
            if (query.team.length > 0 && query.team.toLocaleLowerCase() !== "all") {
                index = teamCombo.findIndex(team => team === query.team)
                postData.teamId = team[index].id
            } 
            if (query.customer.length > 0 && query.customer.toLocaleLowerCase() !== "all") {
                index = custCombo.findIndex(customer => customer === query.customer)
                postData.clientId = customer[index].id
            }
            if (Boolean(query.budgetPercentage)) {
                postData.budgetPercentage = query.budgetPercentage/100
            }
            console.log(postData)
            const response = await fetchCostAndExpenseReport(postData)
            if (response) {
                downloadFile(new Uint8Array(response.blobValue), response.filename!!)
            }
        }}
      />
    </>
  );
};

export default CostAndExpenseReport;
