import CompanySearch from "@/components/CompanySearch";
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 { fetchCompanys, preloadCompanys } from "@/app/api/companys";
import { fetchUserAbilities } from "@/app/utils/fetchUtil";
import { MAINTAIN_COMPANY } from "@/middleware";

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

const Company: React.FC = async () => {
  const { t } = await getServerI18n("companys");
  
  // Preload necessary dependencies
  fetchCompanys();
  preloadCompanys();
  
  const abilities = await fetchUserAbilities()
  const maintainCompany = abilities.includes(MAINTAIN_COMPANY)

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

export default Company;
