import { useFormik } from "formik";
import { useMutation } from "urql";
import * as React from "react";
import * as Yup from "yup";
import { useNavigate } from "react-router-dom";
import { Alert } from "../../../Alert";
import { AnchorLinkElement } from "../_molecules/_atoms/AnchorLinkElement";
import { AuthLayout } from "../../../AuthLayout";
import { EmailInputElement } from "../_molecules/_atoms/EmailInputElement";
import { Form } from "../../../Form";
import { PasswordInputElement } from "../_molecules/_atoms/PasswordInputElement";
import { SocialButtonGroup } from "../../../SocialButtonGroup";
import { SubmitButtonElement } from "../_molecules/_atoms/SubmitButtonElement";
import { Context as AuthContext } from "../../../../contexts/AuthContext";
import { UserContext } from "../../../../contexts/UserContext";
import { UserLoginMutationDocument } from "../../../../gql-codegen/graphql";
import {
  LOGIN_BUTTON,
  LOGIN_COMPONENT,
  LOGIN_EMAIL,
  LOGIN_ERROR,
  LOGIN_PASSWORD,
  SIGNUP_LINK,
} from "../../../../testing";

export function Login() {
  const [{ fetching, data, error }, executeMutation] = useMutation(
    UserLoginMutationDocument,
  );

  const auth = React.useContext(AuthContext);
  const userContext = React.useContext(UserContext);
  const navigate = useNavigate();

  const validation = useFormik({
    enableReinitialize: true,
    initialValues: {
      email: "",
      password: "",
    },
    validationSchema: Yup.object().shape({
      email: Yup.string()
        .email("You must enter a valid email address.")
        .required("You must enter an email address."),
      password: Yup.string()
        .min(8, "Password is too short - must be at least 8 chars.")
        .required("Please enter your password."),
    }),
    onSubmit: ({ email, password }) => {
      executeMutation({
        email: email.trim(),
        password: password.trim(),
      });

      userContext.getUser();
    },
  });

  React.useEffect(() => {
    const userLogin = data?.userLogin;

    const isSuccess = userLogin?.success;
    if (!isSuccess) {
      return;
    }

    const accessToken = userLogin?.accessToken as string;
    const refreshToken = userLogin?.refreshToken as string;

    auth.setValue({ accessToken, refreshToken });

    navigate("/dashboard");
  }, [data, auth.setValue]);

  return (
    <AuthLayout type={"Login"}>
      <Form
        id={LOGIN_COMPONENT}
        onSubmit={(e: React.FormEvent) => {
          e.preventDefault();
          validation.handleSubmit();
          return false;
        }}
      >
        <div className="flex mt-2 flex-row items-center text-sm mb-4">
          <span>Looking to create an account?&nbsp;</span>
          <AnchorLinkElement id={SIGNUP_LINK} toLink="/signup" text="Sign up" />
        </div>
        {(error || data?.userLogin?.success === false) && (
          <div
            id={LOGIN_ERROR}
            data-error={error?.message || data?.userLogin?.message}
          >
            <Alert
              color="red"
              // @ts-ignore
              message={error?.message || data?.userLogin?.message}
            />
          </div>
        )}
        <EmailInputElement
          name="email"
          disabled={Boolean(fetching)}
          required
          error={validation.errors.email ? true : false}
          onChange={validation.handleChange}
          onBlur={validation.handleBlur}
          helperText={validation.errors.email}
          id={LOGIN_EMAIL}
          value={validation.values.email}
        />
        <PasswordInputElement
          name="password"
          disabled={Boolean(fetching)}
          required
          error={validation.errors.password ? true : false}
          onChange={validation.handleChange}
          onBlur={validation.handleBlur}
          helperText={validation.errors.password}
          id={LOGIN_PASSWORD}
          value={validation.values.password}
        />
        <div className="flex flex-row w-full justify-end">
          <AnchorLinkElement
            classes="mb-2 mt-2"
            toLink="/forgot-password"
            text=" Forgot Password?"
          />
        </div>
        <SubmitButtonElement
          content="Login"
          disabled={Boolean(fetching)}
          type="submit"
          id={LOGIN_BUTTON}
        />
        <div className="flex items-center mt-32">
          <div className="flex-auto mt-px border-t"></div>
          <p className="MuiTypography-root MuiTypography-body1 mx-8 muiltr-f6jxy6-MuiTypography-root text-light-grey">
            Our socials
          </p>
          <div className="flex-auto mt-px border-t"></div>
        </div>
        <SocialButtonGroup />
      </Form>
    </AuthLayout>
  );
}
