import { Button } from "@material-ui/core";
import clsx from "clsx";
import React, { useEffect } from "react";

import { useUserContext } from "../Contexts/UserContext";
import useStyles from "../useStyles";

const getCode = (search) => {
  if (!search) return null;
  const s = new URLSearchParams(search);
  return s.get("code");
};

export default function SignInForm() {
  const classes = useStyles();
  const { getAuthorizeURL, signIn, fetching } = useUserContext();

  useEffect(() => {
    const code = getCode(document.location.search);
    if (!code) return;
    signIn(code);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <div className={clsx(classes.paper, classes.textJustifyAlign)}>
      <Button
        type="submit"
        variant="contained"
        color="primary"
        className={classes.submit}
        href={getAuthorizeURL()}
        disabled={fetching}
      >
        {fetching ? "Please wait..." : "Sign In"}
      </Button>
      <p><strong>Note: Your email address will be used as the user id</strong></p>
    </div>
  );
}
