"use client";

import React, { useMemo } from "react";
import SearchBox, { Criterion } from "../SearchBox";
import { useTranslation } from "react-i18next";
import { CrossTeamChargeReportFilter } from "@/app/api/reports";
import { fetchCrossTeamChargeReport } from "@/app/api/reports/actions";
import { downloadFile } from "@/app/utils/commonUtil";
import { TeamResult } from "@/app/api/team";
import { SessionStaff } from "@/config/authConfig";

interface Props {
    _teams: TeamResult[];
    userStaff: SessionStaff;
}

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

const GenerateCrossTeamChargeReport: React.FC<Props> = ({ _teams, userStaff }) => {
    const { t } = useTranslation("report");
    let teams = _teams
    if (Boolean(userStaff?.isTeamLead)) {
        teams.filter(team => team.id == userStaff.teamId)
    }
    const teamCombo = teams.map(team => `${team.code} - ${team.name}`)

    const searchCriteria: Criterion<SearchParamNames>[] = useMemo(
        () => [
            {
                label: t("Month"),
                paramName: "month",
                type: "monthYear",
            },
            { 
                label: t("Team"), 
                paramName: "team", 
                type: "select", 
                options: teamCombo, 
                needAll: !Boolean(userStaff?.isTeamLead) 
            },
        ],
        [t],
    );

    return (
        <>
            <SearchBox
                criteria={searchCriteria}
                onSearch={async (query) => {

                    console.log(query)
                    if (Boolean(query.month) && Boolean(query.team)) {
                        // const projectIndex = projectCombo.findIndex(({value}) => value === parseInt(query.project))
                        const teamIndex = teamCombo.findIndex(team => team === query.team)

                        const response = await fetchCrossTeamChargeReport(
                            { 
                                month: query.month, 
                                teamId: teamIndex >= 0 ? teams[teamIndex].id : "All",
                            })
                        if (response) {
                            downloadFile(new Uint8Array(response.blobValue), response.filename!!)
                        }
                    }
                }}
                formType={"download"}
            />
        </>
    );
};

export default GenerateCrossTeamChargeReport;