"use client";

import React, { useMemo } from "react";
import SearchBox, { Criterion } from "../SearchBox";
import { useTranslation } from "react-i18next";
import { ProjectResult } from "@/app/api/projects";
import { ProjectCashFlowReportFilter } from "@/app/api/reports";
import { fetchProjectCashFlowReport } from "@/app/api/reports/actions";
import { downloadFile } from "@/app/utils/commonUtil";
import { dateTypeCombo } from "@/app/utils/comboUtil";

interface Props {
    projects: ProjectResult[];
}

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

const GenerateProjectCashFlowReport: React.FC<Props> = ({ projects }) => {
    const { t } = useTranslation("report");
    const projectCombo = projects.map(project => ({
        value: project.id,
        label: `${project.code} - ${project.name}`
    }))

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

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

                    if (Boolean(query.project) && query.project !== "All") {
                        // const projectIndex = projectCombo.findIndex(({value}) => value === parseInt(query.project))
                        const response = await fetchProjectCashFlowReport({ projectId: parseInt(query.project), dateType: query.dateType })
                        if (response) {
                            downloadFile(new Uint8Array(response.blobValue), response.filename!!)
                        }
                    }
                }}
                formType={"download"}
            />
        </>
    );
};

export default GenerateProjectCashFlowReport;