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

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

const Projects: React.FC = async () => {
    const { t } = await getServerI18n("projects");
    const abilities = await fetchUserAbilities()
    
    if (![MAINTAIN_PROJECT].some(ability => abilities.includes(ability))) {
        notFound();
      }

    // Preload necessary dependencies
    fetchAllTasks();
    fetchTaskTemplates();
    fetchProjectCategories();
    fetchProjectContractTypes();
    fetchProjectFundingTypes();
    fetchProjectLocationTypes();
    fetchProjectServiceTypes();
    fetchProjectBuildingTypes();
    fetchProjectWorkNatures();
    fetchAllCustomers();
    fetchAllSubsidiaries();
    fetchGrades();
    preloadTeamLeads();
    preloadStaff();
    try {
        const data = await fetchMainProjects();

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

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

export default Projects;
