import { fetchAllCustomers, fetchAllSubsidiaries } from "@/app/api/customer";
import { fetchGrades } from "@/app/api/grades";
import {
    fetchMainProjects,
    fetchProjectBuildingTypes,
    fetchProjectCategories,
    fetchProjectContractTypes,
    fetchProjectDetails,
    fetchProjectFundingTypes,
    fetchProjectLocationTypes,
    fetchProjectServiceTypes,
    fetchProjectWorkNatures,
} from "@/app/api/projects";
import { preloadStaff, preloadTeamLeads } from "@/app/api/staff";
import { fetchAllTasks, fetchTaskTemplates } from "@/app/api/tasks";
import { getUserAbilities } from "@/app/utils/commonUtil";
import CreateProject from "@/components/CreateProject";
import { I18nProvider, getServerI18n } from "@/i18n";
import { MAINTAIN_PROJECT } from "@/middleware";
import Typography from "@mui/material/Typography";
import { isArray } from "lodash";
import { Metadata } from "next";
import { notFound } from "next/navigation";

interface Props {
    searchParams: { [key: string]: string | string[] | undefined };
}

export const metadata: Metadata = {
    title: "Edit Sub Project",
};

const Projects: React.FC<Props> = async ({ searchParams }) => {
    const { t } = await getServerI18n("projects");
    const projectId = searchParams["id"];

    const abilities = await getUserAbilities()
    if (!projectId || isArray(projectId) || !abilities.includes(MAINTAIN_PROJECT)) {
        notFound();
    }

    // Preload necessary dependencies
    fetchAllTasks();
    fetchTaskTemplates();
    fetchProjectCategories();
    fetchProjectContractTypes();
    fetchProjectFundingTypes();
    fetchProjectLocationTypes();
    fetchProjectServiceTypes();
    fetchProjectBuildingTypes();
    fetchProjectWorkNatures();
    fetchAllCustomers();
    fetchAllSubsidiaries();
    fetchGrades();
    preloadTeamLeads();
    preloadStaff();

    try {
        await fetchProjectDetails(projectId);
        const data = await fetchMainProjects();

        if (!Boolean(data) || data.length === 0) {
            notFound();
        }
    } catch (e) {
        notFound();
    }

    return (
        <>
            <Typography variant="h4">{t("Edit Sub Project")}</Typography>
            <I18nProvider namespaces={["projects"]}>
                <CreateProject isEditMode isSubProject projectId={projectId}/>
            </I18nProvider>
        </>
    );
};

export default Projects;
