"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";

interface Props {
    teams: TeamResult[];
    clients: Customer[];
}

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

const GenerateProjectPotentialDelayReport: React.FC<Props> = ({ teams, clients }) => {
    const { t } = useTranslation("report");
    const teamCombo = teams.map(team => `${team.code} - ${team.name}`)
    const clientCombo = clients.map(client => `${client.code} - ${client.name}`)
    const [errors, setErrors] = React.useState({
        numberOfDays: false,
        projectCompletion: false,
    })

    const searchCriteria: Criterion<SearchParamNames>[] = useMemo(
        () => [
            { label: t("Team"), paramName: "team", type: "select", options: teamCombo },
            { label: t("Client"), paramName: "client", type: "select", options: clientCombo },
            { label: t("Number Of Days"), paramName: "numberOfDays", type: "text", textType: "number", error: errors.numberOfDays, helperText: t("Can not be null and decimal, and should be >= 0") },
            { label: t("Project Completion (<= %)"), paramName: "projectCompletion", type: "text", textType: "number", error: errors.projectCompletion, 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.numberOfDays.length === 0 || !Number.isInteger(parseFloat(query.numberOfDays)) || parseInt(query.numberOfDays) < 0) {
                        setErrors((prev) => ({...prev, numberOfDays: true}))
                        hasError = true
                    } else {
                        setErrors((prev) => ({...prev, numberOfDays: false}))
                    }

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

                    if (hasError) return false

                    const teamIndex = teamCombo.findIndex(team => team === query.team)
                    const clientIndex = clientCombo.findIndex(client => client === query.client)
                    
                    const response = await fetchProjectPotentialDelayReport({ 
                        teamId: teams[teamIndex]?.id ?? "All", 
                        clientId: clients[clientIndex]?.id ?? "All",
                        numberOfDays: parseInt(query.numberOfDays),
                        projectCompletion: parseInt(query.projectCompletion)
                    })
                    if (response) {
                        downloadFile(new Uint8Array(response.blobValue), response.filename!!)
                    }
                }}
                formType={"download"}
            />
        </>
    );
};

export default GenerateProjectPotentialDelayReport;