import { Metadata } from "next";
import { getServerI18n, I18nProvider } from "@/i18n";
import Typography from "@mui/material/Typography";
import { Stack } from "@mui/material";
import { Button } from "@mui/material";
import Link from "next/link";
import Add from "@mui/icons-material/Add";
import UserExcelSheetView from "../../../../components/UserSearch/UserExcelSheetView";
import { fetchUser } from "@/app/api/user";
import { fetchAuthBatchByUserIds } from "@/app/api/group/actions";

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

const User: React.FC = async () => {
  const { t } = await getServerI18n("user");
  const users = await fetchUser();
  const authBatchMap = await fetchAuthBatchByUserIds(users.map(user => user.id)).catch(
    () => ({} as Record<number, { id: number; v: number }[]>),
  );
  const usersWithDetails = users.map(user => {
    const authRecords = authBatchMap[user.id] ?? [];
    return {
      ...user,
      authIds: authRecords.filter(a => a.v === 1).map(a => a.id),
      auths: authRecords,
    };
  });
  return (
    <>
      <Stack
        direction="row"
        justifyContent="space-between"
        flexWrap="wrap"
        rowGap={2}
      >
        <Typography variant="h4" marginInlineEnd={2}>
          {t("User")}
        </Typography>
        <Button
          variant="contained"
          startIcon={<Add />}
          LinkComponent={Link}
          href="/settings/user/create"
        >
          {t("Create User")}
        </Button>
      </Stack>
      <I18nProvider namespaces={["user","navigation","common","dashboard"]}>
        <UserExcelSheetView users={usersWithDetails} />
      </I18nProvider>
    </>
  );
};
export default User;
