import DepartmentSearch from "@/components/DepartmentSearch";
import { Metadata } from "next";
import { getServerI18n } from "@/i18n";
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 Link from "next/link";
import { Suspense } from "react";
import { fetchDepartments, preloadDepartments } from "@/app/api/departments";
import { fetchUserAbilities } from "@/app/utils/fetchUtil";
import { MAINTAIN_DEPARTMENT } from "@/middleware";

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

const Department: React.FC = async () => {
  const { t } = await getServerI18n("department");
  
  // Preload necessary dependencies
  // fetchDepartments();
  // preloadDepartments();
  
  const abilities = await fetchUserAbilities()
  const maintainDepartment = abilities.includes(MAINTAIN_DEPARTMENT)

  return (
    <>
      <Stack
        direction="row"
        justifyContent="space-between"
        flexWrap="wrap"
        rowGap={2}
      >
        <Typography variant="h4" marginInlineEnd={2}>
          {t("Department")}
        </Typography>
        {maintainDepartment && <Button
          variant="contained"
          startIcon={<Add />}
          LinkComponent={Link}
          href="/settings/department/new"
        >
          {t("Create Department")}
        </Button>}
      </Stack>
      <Suspense fallback={<DepartmentSearch.Loading />}>
        <DepartmentSearch/>
      </Suspense>
    </>
  )
};

export default Department;
