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 { Metadata } from "next";
import Link from "next/link";
import { Suspense } from "react";
import { I18nProvider } from "@/i18n";
import { preloadAllSubsidiaries } from "@/app/api/subsidiary";
import SubsidiarySearch from "@/components/SubsidiarySearch";
import { fetchUserAbilities } from "@/app/utils/fetchUtil";
import { MAINTAIN_SUBSIDIARY } from "@/middleware";

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

const Subsidiary: React.FC = async () => {
    const { t } = await getServerI18n("subsidiary");
    preloadAllSubsidiaries();
    const abilities = await fetchUserAbilities()
    const maintainSubsidiary = abilities.includes(MAINTAIN_SUBSIDIARY)

    return (
        <>
            <Stack
                direction="row"
                justifyContent="space-between"
                flexWrap="wrap"
                rowGap={2}
            >
                <Typography variant="h4" marginInlineEnd={2}>
                    {t("Subsidiary")}
                </Typography>
                {maintainSubsidiary && <Button
                    variant="contained"
                    startIcon={<Add />}
                    LinkComponent={Link}
                    href="/settings/subsidiary/create"
                >
                    {t("Create Subsidiary")}
                </Button>}
            </Stack>
            <I18nProvider namespaces={["subsidiary", "common"]}>
                <Suspense fallback={<SubsidiarySearch.Loading />}>
                    <SubsidiarySearch />
                </Suspense>
            </I18nProvider>
        </>
    );
};

export default Subsidiary;
