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

interface Props {
  team: TeamResult[];
  customer: Customer[];
  subsidiary: Subsidiary[];
  needAll: boolean | undefined;
}

interface SubComponents {
  Loading: typeof CostAndExpenseReportLoading;
}

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

const CostAndExpenseReport: React.FC<Props> & SubComponents = ({ team, customer, subsidiary, needAll }) => {
  const { t } = useTranslation("report");
  const teamCombo = team.map((t) => `${t.code} - ${t.name}`);
  // const custCombo = customer.map(c => ({label: `${c.name} - ${c.code}`, value: c.id}))
  
  const custCombo = customer.map(customer => ({
    value: `client: ${customer.id}` ,
    label: `${customer.code} - ${customer.name}`,
    group: t("Client")
}))

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


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

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

  return (
    <>
    {loading && <CostAndExpenseReport.Loading />}
    {!loading &&
      <SearchBox
        formType={"download"}
        criteria={searchCriteria}
        onSearch={async (query: any) => {
          setLoading(true);
            let index = 0
            let postData: CostAndExpenseReportRequest = {
                teamId: null,
                clientId: null,
                budgetPercentage: 1,
                type: "all"
            }
            console.log(query.budgetPercentage)
            const customerIndex = custCombo.findIndex(customer => customer.value === query.customer)
            const subsidiaryIndex = subsidiaryCombo.findIndex(subsidiary => subsidiary.value === query.customer)
            if (query.team.length > 0 && query.team.toLocaleLowerCase() !== "all") {
                index = teamCombo.findIndex(team => team === query.team)
                postData.teamId = team[index].id
            } 
            if (typeof query.customer === "string" && query.customer.toLocaleLowerCase() !== "all") {
                // postData.clientId = query.customer
                postData.clientId = customerIndex >= 0 ? customer[customerIndex].id : subsidiaryIndex >= 0 ? subsidiary[subsidiaryIndex].id : null
                postData.type = customerIndex >= 0 ? "client" : subsidiaryIndex >= 0 ? "subsidiary" : "all"
            }
            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!!)
            }
            setLoading(false);
        }}
      />}
    </>
  );
};

CostAndExpenseReport.Loading = CostAndExpenseReportLoading

export default CostAndExpenseReport;
