"use client";

import React, { useMemo } from "react";
import SearchBox, { Criterion } from "../SearchBox";
import { useTranslation } from "react-i18next";
import { ProjectResult } from "@/app/api/projects";
import { EX02ProjectCashFlowReportFilter } from "@/app/api/reports";
import { fetchEX02ProjectCashFlowReport } from "@/app/api/reports/actions";
import { downloadFile } from "@/app/utils/commonUtil";
import { BASE_API_URL } from "@/config/api";

interface Props {
    projects: ProjectResult[];
}

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

const GenerateEX02ProjectCashFlowReport: React.FC<Props> = ({ projects }) => {
    const { t } = useTranslation();
    const projectCombo = projects.map(project => `${project.code} - ${project.name}`)

    const searchCriteria: Criterion<SearchParamNames>[] = useMemo(
        () => [
            { label: t("Project"), paramName: "project", type: "select", options: projectCombo, needAll: false},
        ],
        [t],
    );

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

                    if (query.project.length > 0 && query.project.toLocaleLowerCase() !== "all") {
                        const projectIndex = projectCombo.findIndex(project => project === query.project)
                        const response = await fetchEX02ProjectCashFlowReport({ projectId: projects[projectIndex].id })
                        if (response) {
                            downloadFile(new Uint8Array(response.blobValue), response.filename!!)
                        }
                    }
                }}
            />
        </>
    );
};

export default GenerateEX02ProjectCashFlowReport;