import * as React from "react";
import * as Yup from "yup";
import { useFormik } from "formik";
import { useMutation } from "urql";
import { useLocation, useNavigate } from "react-router-dom";
import { toast } from "react-toastify";
import {
  UserPasswordResetCallbackInput,
  UserPasswordResetCallbackMutationDocument,
  UserPasswordResetCallbackResponse,
} from "../../../../gql-codegen/graphql";
import { Form } from "../../../Form";
import { AuthLayout } from "../../../AuthLayout";
import { EmailInputElement } from "../_molecules/_atoms/EmailInputElement";
import { TextInputElement } from "../_molecules/_atoms/TextInputElement";
import { PasswordInputElement } from "../_molecules/_atoms/PasswordInputElement";
import { SocialButtonGroup } from "../../../SocialButtonGroup";
import { SubmitButtonElement } from "../_molecules/_atoms/SubmitButtonElement";

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

  const location = useLocation();
  const params = new URLSearchParams(location.search);
  const token = params.get("token") ?? "";

  const [{ fetching }, executeMutation] = useMutation<
    UserPasswordResetCallbackResponse,
    { input: UserPasswordResetCallbackInput }
  >(UserPasswordResetCallbackMutationDocument);

  const validation = useFormik({
    enableReinitialize: true,
    initialValues: {
      email: "",
      password: "",
      confirmPassword: "",
      token: token,
    },
    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."),
      confirmPassword: Yup.string()
        .required("Confirm Password is required")
        .oneOf([Yup.ref("password")], "Confirm Password does not match"),
      token: Yup.string()
        .min(3, "Token is required.")
        .required("Token is required"),
      acceptTerms: Yup.boolean().oneOf([true], "Please Accept"),
    }),
    onSubmit: ({ email, password }) => {
      executeMutation({
        input: {
          email: email.trim(),
          newPassword: password.trim(),
          resetToken: token,
        } as UserPasswordResetCallbackInput,
      }).then((result) => {
        if (result.data) {
          toast.success(
            "Please check your inbox. You will receive an email if it was successful.",
            {
              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={"ForgotPasswordCallback"}>
      <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 and a new password.&nbsp;</span>
        </div>
        <TextInputElement
          name="token"
          required
          disabled={token.length != 0 ?? false}
          value={token}
          label="Token"
          error={validation.errors.token ? true : false}
          helperText={validation.errors.token}
          onChange={validation.handleChange}
          onBlur={validation.handleBlur}
        />
        <EmailInputElement
          name="email"
          disabled={Boolean(fetching)}
          required
          error={validation.errors.email ? true : false}
          onChange={validation.handleChange}
          onBlur={validation.handleBlur}
          helperText={validation.errors.email}
        />
        <PasswordInputElement
          name="password"
          disabled={Boolean(fetching)}
          error={validation.errors.password ? true : false}
          onChange={validation.handleChange}
          onBlur={validation.handleBlur}
          helperText={validation.errors.password}
        />
        <PasswordInputElement
          name="confirmPassword"
          disabled={Boolean(fetching)}
          error={validation.errors.confirmPassword ? true : false}
          onChange={validation.handleChange}
          onBlur={validation.handleBlur}
          helperText={validation.errors.confirmPassword}
          isConfirm
        />
        <SubmitButtonElement
          content="Reset Password"
          disabled={Boolean(fetching)}
          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>
  );
}
