import { fetchAllCustomers } from "@/app/api/customer";
import { fetchProjectCategories, fetchProjects } from "@/app/api/projects";
import { fetchTeam } from "@/app/api/team";
import { fetchUserAbilities } from "@/app/utils/fetchUtil";
import ProjectSearch from "@/components/ProjectSearch";
import { getServerI18n, I18nProvider } from "@/i18n";
import { MAINTAIN_PROJECT } from "@/middleware";
import Add from "@mui/icons-material/Add";
import Button from "@mui/material/Button";
import Stack from "@mui/material/Stack";
import Typography from "@mui/material/Typography";
import { Metadata } from "next";
import Link from "next/link";
import { notFound } from "next/navigation";
import { Suspense } from "react";

export const metadata: Metadata = {
  title: "Projects",
};

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

  return (
    <>
      <I18nProvider namespaces={["projects", "common"]}>
        <Stack
          direction="row"
          justifyContent="space-between"
          flexWrap="wrap"
          rowGap={2}
        >
          <Typography variant="h4" marginInlineEnd={2}>
            {t("Project Management")}
          </Typography>
          {abilities.includes(MAINTAIN_PROJECT) && (
            <Stack
              direction="row"
              justifyContent="space-between"
              flexWrap="wrap"
              rowGap={2}
              spacing={1}
            >
              {projects.filter(
                (project) => project.status.toLowerCase() !== "deleted",
              ).length > 0 && (
                <Button
                  variant="contained"
                  color="secondary"
                  startIcon={<Add />}
                  LinkComponent={Link}
                  href="/projects/createSub"
                >
                  {t("Create Sub Project")}
                </Button>
              )}
              <Button
                variant="contained"
                startIcon={<Add />}
                LinkComponent={Link}
                href="/projects/create"
              >
                {t("Create Project")}
              </Button>
            </Stack>
          )}
        </Stack>
        <Suspense fallback={<ProjectSearch.Loading />}>
          <ProjectSearch />
        </Suspense>
      </I18nProvider>
    </>
  );
};

export default Projects;
