import Head from "next/head";
import { Box, Grid, Container, IconButton } from "@mui/material";
import { Apple as AppleIcon, Google as GoogleIcon } from "@mui/icons-material";
import { signIn, getSession } from "next-auth/react";

const Login = ({ session }) => {
  const buttonStyles = {
    borderRadius: 500,
    width: "100%",
    fontSize: "16px",
    fontWeight: "bold",
  };

  return (
    <>
      <Head>
        <title>Login</title>
      </Head>
      <Grid container direction="row-reverse" sx={{ p: 3 }}>
        <Grid item />
      </Grid>
      <Container maxWidth="md" sx={{ mt: 3, mb: 20 }}>
        <Grid container spacing={2} direction="column" alignItems="center">
          <Grid item>
            <Box sx={{ maxWidth: 200 }} />
          </Grid>
          <Grid item sx={{ textAlign: "center" }} />

          <Grid item>
            {!session ? (
              <Grid
                container
                spacing={3}
                direction="column"
                alignItems="center"
                sx={{ width: 450, mt: 1 }}
              >
                <Grid item sx={{ width: "100%" }}>
                  <IconButton
                    sx={buttonStyles}
                    onClick={() =>
                      signIn("google", {
                        callbackUrl: `${window.location.origin}/setup`,
                      })
                    }
                  >
                    <GoogleIcon sx={{ mr: 1 }} />
                  </IconButton>
                </Grid>
                <Grid item sx={{ width: "100%" }}>
                  <IconButton
                    sx={buttonStyles}
                    onClick={() =>
                      signIn("apple", {
                        callbackUrl: `${window.location.origin}/setup`,
                      })
                    }
                  >
                    <AppleIcon sx={{ mr: 1 }} />
                  </IconButton>
                </Grid>
                <Grid item sx={{ mt: 2 }} />
              </Grid>
            ) : null}
            {session ? (
              <Box component="h4">
                {` ${session.user.name ?? session.user.email}.`}
              </Box>
            ) : null}
          </Grid>
        </Grid>
      </Container>
    </>
  );
};

export default Login;

export async function getServerSideProps(context) {
  const session = (await getSession(context)) ?? null;

  return {
    props: { session },
  };
}
