import axios from "axios";
import Head from "next/head";
import React, { useCallback, useEffect } from "react";
import style from "./password.module.css";
import { Cancel, CheckCircleRounded } from "@mui/icons-material";
import { useRouter } from "next/router";
import { authApi } from "../../api/api";
import { accountStoreActions } from "@/store/account";
import { useDispatch } from "react-redux";
import InputText from "../../components/utils/inputText";
import { Email } from "@mui/icons-material";
import { useRef, useState } from "react";
import ReCAPTCHA from "react-google-recaptcha";
import Loader from "@/components/utils/loader";
import { usePasswordValidation } from "@/customHook/useValidation";
import { GoogleReCaptcha } from "react-google-recaptcha-v3";

const SuccessPage = ({ data }) => {
  const [newData, setNewData] = useState({ ...data });
  const router = useRouter();
  const dispatch = useDispatch();
  const [error, setError] = useState("");
  const [refreshReCaptcha, setRefreshReCaptcha] = useState(false);
  const [captcha, setCaptcha] = useState();
  const [fpLoader, setFPLoader] = useState();
  const [resetSuccess, setResetSuccess] = useState(false);
  const [fpData, setFPData] = useState({ password: "", confirmPassword: "" });
  const passwordValidation = usePasswordValidation(fpData.password);

  const onVerify = useCallback((token) => {
    setCaptcha(token);
  }, []);

  const forgetPasswordSubmitHandler = async (e) => {
    e.preventDefault();
    if (!captcha) {
      setError("Complete Captcha!");
      return 0;
    }
    if (!fpData.password || !fpData.confirmPassword) {
      setError("Complete Required Field");
      return 0;
    }
    if (fpData.password != fpData.confirmPassword) {
      setError("Password Doesnt Match");
      return 0;
    }

    if (passwordValidation.value === false) {
      setError("Wrong Password Format");
      return 0;
    }
    setError();
    await authApi
      .post("/customer/password/reset", {
        ...fpData,
        rtoken: newData.token,
        userid: newData.userid,
        token: captcha,
      })
      .then((res) => {
        console.log(":res.status ", res.status);
        if (res.data.success === true) {
          setResetSuccess(true);
        } else {
          setError("Password Reset Failed");
          setRefreshReCaptcha((prev) => !prev);
        }
        setFPLoader(false);
      })
      .catch((err) => {
        console.log("err: ", err);
        setError("Password Reset Failed");
        setRefreshReCaptcha((prev) => !prev);
        setFPLoader(false);
      });
  };
  return (
    <React.Fragment>
      <Head>
        <title>Email Confirmation - Vandaway</title>
      </Head>
      {newData.status === true && !resetSuccess && (
        <div className={style.fp_form}>
          <div className={style.section_box}>
            <form onSubmit={forgetPasswordSubmitHandler}>
              <div className={style.input_section}>
                <InputText
                  type="password"
                  name="password"
                  placeholder="Enter New Password"
                  getValue={(value) => {
                    setFPData((prev) => {
                      let newObject = { ...prev };
                      newObject["password"] = value;
                      return newObject;
                    });
                  }}
                  required={true}
                  label={"New Password"}
                  customClass={style.customInputClass}
                  message="Atleast one special character, one numeric, one capital letter, 10 minimum length & maximum 20 length"
                />

                <InputText
                  type="text"
                  name="password"
                  placeholder="Confirm New Password"
                  getValue={(value) => {
                    setFPData((prev) => {
                      let newObject = { ...prev };
                      newObject["confirmPassword"] = value;
                      return newObject;
                    });
                  }}
                  required={true}
                  label={"Confirm Password"}
                  customClass={style.customInputClass}
                />
                <center>
                  <GoogleReCaptcha
                    onVerify={onVerify}
                    refreshReCaptcha={refreshReCaptcha}
                  />
                </center>
                <div className={style.status}>
                  {error && (
                    <div className={`${style.error_status}`}>{error}</div>
                  )}
                </div>
                <button
                  type="submit"
                  className={`primary_btn_no_animation ${style.button} mt-2`}
                  disabled={fpLoader ? true : false}
                >
                  {fpLoader ? <Loader className={style.loader} /> : "Submit"}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
      {newData.status === false && (
        <div className={style.section}>
          <div className={style.icon_failed}>
            <Cancel />
          </div>
          <p className={style.order_success_text}>Reset Link Expired!!</p>
        </div>
      )}
      {resetSuccess === true && (
        <div className={style.section}>
          <div className={style.icon}>
            <CheckCircleRounded />
          </div>
          <p className={style.order_success_text}>Password Reset Success</p>
          <button
            type="button"
            className="secondary-btn"
            onClick={() => dispatch(accountStoreActions.openSignInUI())}
          >
            Login Now
          </button>
        </div>
      )}
    </React.Fragment>
  );
};

export default SuccessPage;

export const getServerSideProps = async (ctx) => {
  let status = false;
  if (!ctx.query.userid || !ctx.query.token)
    return {
      redirect: {
        destination: "/",
        permanent: false,
      },
    };
  await authApi
    .post("/token/confirm", {
      userid: ctx.query.userid,
      token: ctx.query.token,
      tokenType: "reset",
    })
    .then((res) => {
      if (res.data.success === true) {
        status = true;
      } else {
        status = false;
      }
    })
    .catch((err) => {
      return {
        redirect: {
          destination: "/",
          permanent: false,
        },
      };
    });

  return {
    props: {
      data: {
        status: status,
        token: ctx.query.token,
        userid: ctx.query.userid,
      },
    },
  };
};
