"use client";

import { FC, useEffect } from "react";
import { CircularProgress, Typography, Grid } from "@mui/material";
import { signIn, signOut, getSession } from "next-auth/react";
import { useLogin, useTranslate } from "react-admin";

export const authProvider = {
  login(o: any) {
    if (o.ok) return Promise.resolve();
    return Promise.reject();
  },
  async logout() {
    const session = await getSession();
    if (session) {
      await signOut();
    }
  },
  checkError(e: any) {
    if (e.graphQLErrors && e.graphQLErrors.length > 0) {
      const permDenied = e.graphQLErrors.some((e: any) =>
        e.message.match(/.*permission denied.*/)
      );
      if (permDenied)
        // eslint-disable-next-line  prefer-promise-reject-errors
        return Promise.reject({ message: "auth.permissionDenied" });
    }

    if (e.networkError && e.networkError.statusCode === 401) {
      return Promise.reject();
    }

    return Promise.resolve();
  },
  async checkAuth() {
    const session = await getSession();
    if (!session) {
      throw new Error("Invalid session");
    }
  },
  async getIdentity() {
    const session = await getSession();
    if (!session) throw new Error("Invalid session");

    return {
      id: session.user?.email,
      fullName: session.user?.name,
      avatar: session.user?.image,
    };
  },
  getPermissions: () => Promise.resolve(),
};

export const AdminLogin: FC = () => {
  const reactAdminLogin = useLogin();
  const translate = useTranslate();

  useEffect(() => {
    (async () => {
      const session = await getSession();
      if (session) {
        reactAdminLogin({ ok: true });
      } else {
        signIn();
      }
    })();
  });

  return (
    <Grid
      container
      spacing={5}
      direction="column"
      alignItems="center"
      justifyContent="center"
      style={{ minHeight: "100vh" }}
    >
      <Grid item xs={3}>
        <Typography variant="h4" color="textSecondary">
          {translate("auth.loggingIn")}
        </Typography>
      </Grid>
      <Grid item xs={3}>
        <CircularProgress size={80} />
      </Grid>
    </Grid>
  );
};
