"use client";

import React, { useMemo } from "react";
import SearchBox, { Criterion } from "../SearchBox";
import { useTranslation } from "react-i18next";
import { ProjectPotentialDelayReportFilter } from "@/app/api/reports";
import { fetchProjectPotentialDelayReport } from "@/app/api/reports/actions";
import { downloadFile } from "@/app/utils/commonUtil";
import { TeamResult } from "@/app/api/team";
import { Customer } from "@/app/api/customer";
import { Subsidiary } from "@/app/api/subsidiary";
import { SessionStaff } from "@/config/authConfig";

interface Props {
    teams: TeamResult[];
    clients: Customer[];
    subsidiaries: Subsidiary[];
    userStaff: SessionStaff;
}

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

const GenerateProjectPotentialDelayReport: React.FC<Props> = ({ teams, clients, subsidiaries, userStaff }) => {
    const { t } = useTranslation("report");
    const teamCombo = teams.map(team => `${team.code} - ${team.name}`)

    const clientCombo = clients.map(client => ({
        value: `client: ${client.id}` ,
        label: `${client.code} - ${client.name}`,
        group: t("Client")
    }))

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

    const [errors, setErrors] = React.useState({
        daysUntilCurrentStageEnd: false,
        resourceUtilizationPercentage: false,
    })

    const searchCriteria: Criterion<SearchParamNames>[] = useMemo(
        () => [
            { label: t("Team"), paramName: "team", type: "select", options: teamCombo, needAll: !Boolean(userStaff?.isTeamLead) },
            { label: t("Client"), paramName: "client", type: "autocomplete", options: [...subsidiaryCombo, ...clientCombo] },
            { label: t("Days until current stage end"), paramName: "daysUntilCurrentStageEnd", type: "text", textType: "number", error: errors.daysUntilCurrentStageEnd, helperText: t("Can not be null and decimal, and should be >= 0") },
            { label: t("Resource Utilization Percentage (<= %)"), paramName: "resourceUtilizationPercentage", type: "text", textType: "number", error: errors.resourceUtilizationPercentage, helperText: t("Can not be null and decimal, and should be in range of 0 - 100") },
        ],
        [t, errors],
    );

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

                    let hasError = false
                    if (query.daysUntilCurrentStageEnd.length === 0 || !Number.isInteger(parseFloat(query.daysUntilCurrentStageEnd)) || parseInt(query.daysUntilCurrentStageEnd) < 0) {
                        setErrors((prev) => ({...prev, daysUntilCurrentStageEnd: true}))
                        hasError = true
                    } else {
                        setErrors((prev) => ({...prev, daysUntilCurrentStageEnd: false}))
                    }

                    if (query.resourceUtilizationPercentage.length === 0 || !Number.isInteger(parseFloat(query.resourceUtilizationPercentage)) || parseInt(query.resourceUtilizationPercentage) < 0 || parseInt(query.resourceUtilizationPercentage) > 100) {
                        setErrors((prev) => ({...prev, resourceUtilizationPercentage: true}))
                        hasError = true
                    } else {
                        setErrors((prev) => ({...prev, resourceUtilizationPercentage: false}))
                    }

                    if (hasError) return false

                    const teamIndex = teamCombo.findIndex(team => team === query.team)
                    const clientIndex = clientCombo.findIndex(client => client.value === query.client)
                    const subsidiaryIndex = subsidiaryCombo.findIndex(subsidiary => subsidiary.value === query.client)

                    const response = await fetchProjectPotentialDelayReport({ 
                        teamId: teamIndex >= 0 ? teams[teamIndex].id : "All", 
                        clientId: clientIndex >= 0 ? clients[clientIndex].id : subsidiaryIndex >= 0 ? subsidiaries[subsidiaryIndex].id : "All",
                        daysUntilCurrentStageEnd: parseInt(query.daysUntilCurrentStageEnd),
                        resourceUtilizationPercentage: parseInt(query.resourceUtilizationPercentage),
                        type: clientIndex >= 0 ? "client" : subsidiaryIndex >= 0 ? "subsidiary" : "All",
                    })
                    if (response) {
                        downloadFile(new Uint8Array(response.blobValue), response.filename!!)
                    }
                }}
                formType={"download"}
            />
        </>
    );
};

export default GenerateProjectPotentialDelayReport;