import * as React from "react";
import * as Yup from "yup";
import { useFormik } from "formik";
import { useMutation } from "urql";
import { useNavigate } from "react-router-dom";
import { toast } from "react-toastify";
import {
  UserPasswordResetRequestMutationDocument,
  UserPasswordResetRequestbackInput,
  UserPasswordResetRequestbackResponse,
} from "../../../../gql-codegen/graphql";
import { Form } from "../../../Form";
import { AuthLayout } from "../../../AuthLayout";
import { AnchorLinkElement } from "../_molecules/_atoms/AnchorLinkElement";
import { EmailInputElement } from "../_molecules/_atoms/EmailInputElement";
import { SocialButtonGroup } from "../../../SocialButtonGroup";
import { SubmitButtonElement } from "../_molecules/_atoms/SubmitButtonElement";

export function ForgotPassword() {
  const navigate = useNavigate();

  const [{ fetching }, executeMutation] = useMutation<
    UserPasswordResetRequestbackResponse,
    { input: UserPasswordResetRequestbackInput }
  >(UserPasswordResetRequestMutationDocument);

  const validation = useFormik({
    enableReinitialize: true,

    initialValues: {
      email: "",
    },
    validationSchema: Yup.object().shape({
      email: Yup.string()
        .email("You must enter a valid email address.")
        .required("You must enter an email address."),
    }),
    onSubmit: ({ email }) => {
      executeMutation({
        input: {
          email: email.trim(),
        } as UserPasswordResetRequestbackInput,
      }).then((result) => {
        if (result.data) {
          toast.success(
            "Please check your inbox. You will receive an email if a user exists.",
            {
              position: toast.POSITION.BOTTOM_RIGHT,
            },
          );

          navigate("/login");
        }

        if (result.error) {
          toast.error("Something went wrong, please try again...", {
            position: toast.POSITION.BOTTOM_RIGHT,
          });
        }
      });
    },
  });

  return (
    <AuthLayout type={"ForgotPassword"}>
      <Form
        id="login"
        onSubmit={(e: React.FormEvent) => {
          e.preventDefault();
          validation.handleSubmit();
          return false;
        }}
      >
        <div className="flex mt-2 flex-row items-center text-sm mb-4">
          <span>Fill in your email address to reset your password.&nbsp;</span>
        </div>
        <EmailInputElement
          name="email"
          disabled={Boolean(fetching)}
          required
          error={validation.errors.email ? true : false}
          onChange={validation.handleChange}
          onBlur={validation.handleBlur}
          helperText={validation.errors.email}
        />
        <div className="flex flex-row w-full justify-end">
          <AnchorLinkElement
            classes="mb-2 mt-2"
            toLink="/login"
            text=" Sign in"
          />
        </div>
        <SubmitButtonElement
          content="Send Request"
          disabled={Boolean(fetching) || !validation.dirty}
          type="submit"
        />
        <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>
  );
}
