"use client";
import React, { useMemo } from "react";
import SearchBox, { Criterion } from "../SearchBox";
import { useTranslation } from "react-i18next";
import { ProjectResult } from "@/app/api/projects";
import { fetchMonthlyWorkHoursReport, fetchProjectCashFlowReport, fetchProjectResourceOverconsumptionReport } from "@/app/api/reports/actions";
import { downloadFile, readIntFromString } from "@/app/utils/commonUtil";
import { BASE_API_URL } from "@/config/api";
import { ProjectResourceOverconsumptionReportFilter, ProjectResourceOverconsumptionReportRequest } from "@/app/api/reports";
import { StaffResult } from "@/app/api/staff";
import { TeamResult } from "@/app/api/team";
import { Customer } from "@/app/api/customer";
import { Subsidiary } from "@/app/api/subsidiary";
import CostAndExpenseReportLoading from "../CostAndExpenseReport/CostAndExpenseReportLoading";

interface Props {
    team: TeamResult[]
    customer: Customer[]
    subsidiaries: Subsidiary[]
    needAll: boolean
}

type combo = {
    value: string,
    label: string,
    group: string
}

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

const ResourceOverconsumptionReport: React.FC<Props> = ({ team, customer, subsidiaries, needAll }) => {
    const { t } = useTranslation("report");
    const statusCombo = ["Potential Overconsumption"]
    const sortedTeam = team.sort((a, b) => a.code.localeCompare(b.code));
    const sortedCust = customer.sort((a, b) => a.code.localeCompare(b.code));
    const sortedSubs = subsidiaries.sort((a, b) => a.code.localeCompare(b.code));
    const teamCombo = sortedTeam.map(t => `${t.code} - ${t.name}`)
    const custCombo: combo[] = sortedCust.map(c => ({
        value: `custId-${c.id}`,
        label: `${c.code} - ${c.name}`, 
        group: t("Client")
        }))
    const subsidiariesCombo: combo[] = sortedSubs.map(sub => ({
        value: `subsidiaryId-${sub.id}`,
        label: `${sub.code} - ${sub.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: [...subsidiariesCombo, ...custCombo], 
                // needAll: true
            },
            { 
                label: t("Status"), 
                paramName: "status", 
                type: "select", 
                options: statusCombo, 
                needAll: true
            },
            { 
                label: t("Potential Overconsumption Threshold"), 
                paramName: "lowerLimit", 
                type: "number",
            },
        ],
        [t],
    );

return (
    <>
    <SearchBox
        formType={"download"}
        criteria={searchCriteria}
        onSearch={async (query: any) => {
            const [custType, id] = readIntFromString(query.customer) as [string, number]
            let postData: ProjectResourceOverconsumptionReportRequest = {
                status: "All",
                lowerLimit: 0.9
            }
            if (query.team.length > 0 && query.team.toLocaleLowerCase() !== "all") {        
                const index = teamCombo.findIndex(team => team === query.team)
                const teamId = sortedTeam[index].id
                postData.teamId = teamId
            }
            if (Boolean(query.lowerLimit)) {
                postData.lowerLimit = query.lowerLimit/100
            }
            if (id) {
                postData[custType] = id
            }
            postData.status = query.status
            console.log(postData)
            const response = await fetchProjectResourceOverconsumptionReport(postData)
            if (response) {
                downloadFile(new Uint8Array(response.blobValue), response.filename!!)
            }
        }
    }
    />
</>
    )
}

export default ResourceOverconsumptionReport