Signup.js 16.4 KB
import React, { useState, useRef, useEffect } from "react";
import { Formik } from "formik";
import Link from "next/link";
import { Fragment } from "react";
import { Button, Form } from "react-bootstrap";
import * as Yup from "yup";
import { renderImage } from "../../services/imageHandling";
import Image from "next/image";
import { useRouter } from "next/router";
import axios from "axios";
import { useDispatch } from "react-redux";
import { registerUser } from "../../redux/actions/userActions";
import { toast } from "react-toastify";
import OTPInput from "../common-components/OTPInput";
import { finishVendorOtpVerification } from "../../redux/actions/vendorActions";
import { signIn } from "next-auth/react";
import { Loader } from "react-bootstrap-typeahead";
import qs from "qs";
import PhoneInput from "react-phone-input-2";
import OtpTimer from "../common-components/OtpTimer";
import TermsAndConditionModel from "./TermsAndConditionModel";
const Signup = props => {
  const [showPassword, setShowPassword] = useState(false);
  const [confirmShowPassword, setConfirmShowPassword] = useState(false);
  const [isOpenEis, setIsOpenEis] = useState(false);
  console.log("props.type", props.type);
  const [otp, setOtp] = useState(new Array(4).fill(""));
  const [isOtpSent, setOtpSent] = useState(false);
  const [otpVerified, setOtpVerified] = useState(false);
  const [otpTimer, setotpTimer] = useState(30);
  const [loading, setLoading] = useState();
  const dispatch = useDispatch();
  const router = useRouter();
  const otpValue = useRef();
  const changeOtpRef = value => {
    console.log(otpValue);
    if (otpValue.current?.length > 0) {
      otpValue.current = [...otpValue.current, value];
    } else {
      otpValue.current = [value];
    }
  };

  const signupValidationSchema = Yup.object().shape({
    fullname: Yup.string().required("Full name is required"),
    email: Yup.string().required("Email Id is Required").email("Please Enter An Valid Email Id"),
    password: Yup.string().required("Password is Required").min(6, "Password must be minimum 6 characters"),
    confirmPassword: Yup.string()
      .required("Confirm Password is Required")
      .oneOf([Yup.ref("password"), null], "Passwords must match"),
    countryCode: Yup.string().required("Country Code is Required"),
    mobile: Yup.string().required("Mobile Number is Required"),
    // .matches(/^[0-9\s]+$/, "Please Enter Correct Mobile No."),
    termsConditions: Yup.bool().oneOf([true], "Please Accept Terms & Conditions"),
    otp: Yup.string().when("isOtpSent", {
      is: true,
      then: Yup.string()
        .required("Otp is Required")
        .matches(/^[0-9\s]+$/, "Please Enter Correct OTP")
    })
  });

  // Initial errors for required fields
  const initialErrors = {
    fullname: "Full Name is required",
    email: "Email is required",
    password: "Password is required",
    confirmPassword: "Confirm Password is required",
    countryCode: "Country Code is Required",
    mobile: "Mobile Number is Required"
  };

  const handleSendOtp = values => {
    setOtpSent(true);
  };

  const handleVerifyOtp = values => {
    setOtpVerified(true);
    if (props.type == "user") {
    }
  };
  const startTimer = () => {
    setotpTimer(otpTimer - 1);
    // while (otpTimer > 0) {
    //   setTimeout(() => {
    //   }, 1000);
    // }
  };
  return (
    <Fragment>
      <div className="contaier-fluid login-banner-image">
        {(props?.type == "user" || (props?.type == "vendor" && !otpVerified)) && (
          <div className="row">
            <div className="col-11 col-lg-4 login-div signupdiv">
              <div className="">
                <h2>{props.type == "vendor" ? "Vendor Signup" : "Signup to get more out of the platform"}</h2>
                <div className="form-container">
                  <Formik
                    initialValues={{
                      fullname: "",
                      email: "",
                      password: "",
                      confirmPassword: "",
                      countryCode: "",
                      mobile: "",
                      termsConditions: false
                      //   otp: Otp ? Otp : ""
                    }}
                    // initialErrors={initialErrors}
                    validationSchema={signupValidationSchema}
                    enableReinitialize={true}
                  // onSubmit={e => {
                  //     // e.preventDefault();
                  //     console.log("signup values", e);
                  //     setOtpSent(true)
                  //     if (!isOtpSent) {
                  //     //   handleSendOtp(values);
                  //     }
                  //     if (isOtpSent) {
                  //     //   handleVerifyOtp(values);
                  //     }
                  //   }}
                  >
                    {({ values, errors, touched, handleChange, handleBlur, handleSubmit, isValid, isSubmitting, setValues, setFieldValue }) => (
                      <Form
                        onSubmit={async e => {
                          e.preventDefault();
                          const userConfig = {
                            headers: {
                              "Content-Type": "application/json"
                            }
                          };
                          // const query = {
                          //   filters: {
                          //     $or: [{ email: { $eq: values.email } }, { phone: { $eq: values.mobile } }]
                          //   }
                          //   // populate: ["role"],
                          //   // fields: ["email", "role"]
                          // };
                          // const queryString = qs.stringify(query, {
                          //   encodeValuesOnly: true
                          // });
                          // const existingUser = await axios.get(`${process.env.NEXT_PUBLIC_BACKEND_API_URL}/api/users?${queryString}`, userConfig);
                          // if (existingUser) {
                          //   console.log("existingUser", existingUser);
                          //   if (existingUser.data && existingUser.data.length > 0) {
                          //     if (existingUser.data[0].confirmed) {
                          //       toast.warning("Email or phone number already registered, please use a different phone or email.");
                          //     } else {
                          //       toast.warning("Seems like you have already registered, please confirm the OTP")
                          //     }
                          //   }
                          //   return;
                          // }
                          // return;
                          if (!isOtpSent) {
                            setLoading(true);
                            e.preventDefault();
                            console.log("values", values);
                            let user;
                            if (props.type == "vendor") {
                              user = await dispatch(registerUser({ ...values, role: "vendor" }));
                            }
                            if (props.type == "user") {
                              user = await dispatch(registerUser({ ...values, role: "endUser" }));
                            }
                            console.log("response", user);
                            if (user?.data?.status == "fail") {
                              toast.error(user?.data.message);
                              setLoading(false);
                              return;
                            }
                            setOtpSent(true);
                            setLoading(false);
                            // startTimer();
                          } else {
                            e.preventDefault();
                            setLoading(true);
                            const oneTimePassword = otp.join("");
                            // setLoading(false);
                            const otpRes = await finishVendorOtpVerification({ email: values.email, oneTimePassword });
                            console.log("otpRes", otpRes);
                            if (otpRes.data.ok) {
                              const result = await signIn("credentials", {
                                email: values.email,
                                password: values.password,
                                redirect: false
                              });
                              setLoading(false);
                              console.log("result", result);
                              if (props.type == "vendor") {
                                router.push("/vendor/business-details");
                              }
                              if (props.type == "user") {
                                router.push("/signup/user/thankyou");
                              }
                              //   toast.success("User registered successflly");
                            } else if (!otpRes.data.ok) {
                              setLoading(false);
                              setOtp(new Array(4).fill(""));
                              toast.error("Invalid OTP, please try again.");
                            }
                          }
                        }}
                      >
                        <div className="input-group">
                          <label>Full Name</label>
                          <input type="text" name="fullname" onChange={handleChange} onBlur={handleBlur} value={values.fullname} placeholder="Your name" />
                          {errors.fullname && touched.fullname && <span className="form-error">{errors.fullname}</span>}
                        </div>
                        <div className="input-group">
                          <label>Email Id</label>
                          <input type="text" name="email" onChange={handleChange} onBlur={handleBlur} value={values.email} placeholder="yourname@example.com" />
                          {errors.email && touched.email && <span className="form-error">{errors.email}</span>}
                        </div>
                        <div className="input-group password-field">
                          <label>Password</label>
                          <input
                            // type="password"
                            type={showPassword ? "text" : "password"}
                            name="password" onChange={handleChange} onBlur={handleBlur} value={values.password} placeholder="Enter password" />
                          {errors.password && touched.password && <span className="form-error">{errors.password}</span>}
                          <div onClick={() => setShowPassword(!showPassword)}>{showPassword ? <span className="eye-slash"></span> : <span className="eye"></span>}</div>
                        </div>
                        <div className="input-group password-field">
                          <label>Confirm Password</label>
                          <input
                            type={confirmShowPassword ? "text" : "password"}
                            name="confirmPassword"
                            onChange={handleChange}
                            onBlur={handleBlur}
                            value={values.confirmPassword}
                            placeholder="Re-enter password"
                          />
                          {errors.confirmPassword && touched.confirmPassword && <span className="form-error">{errors.confirmPassword}</span>}
                          <div onClick={() => setConfirmShowPassword(!confirmShowPassword)}>
                            {confirmShowPassword ? <span className="eye-slash"></span> : <span className="eye"></span>}
                          </div>
                        </div>
                        <div className="input-group ">
                          <label>Mobile No.</label>
                          <div className="contact-numbe w-100">
                            {/* <input name="mobile" onChange={handleChange} onBlur={handleBlur} value={values.mobile} placeholder="" style={{ flex: "0 100%" }} /> */}
                            <PhoneInput
                              placeholder="Enter phone number"
                              name="mobile"
                              onChange={e => {
                                console.log(values.mobile);
                                setValues({ ...values, mobile: e });
                                // handleChange(e);
                              }}
                              onBlur={handleBlur}
                              value={values.mobile}
                            // placeholder=""
                            // style={{ flex: "0 100%" }}
                            // value={value}
                            // onChange={setValue}
                            />
                          </div>
                          {errors.mobile && touched.mobile && <span className="form-error">{errors.mobile}</span>}
                        </div>
                        <div className="input-group mb-3">
                          <label className="check-container mb-0 pt-1" htmlFor="termsConditions">
                            <input
                              type="checkbox"
                              id="termsConditions"
                              name="termsConditions"
                              className="check-box me-2"
                              checked={values.termsConditions}
                              onChange={handleChange}
                              onBlur={handleBlur}
                            />
                            <span className="checkmark"></span>I Agree to the <a onClick={() => { setIsOpenEis(true) }}>terms & conditions*</a>
                          </label>
                          <br />

                          {errors.termsConditions && touched.termsConditions && <span className="form-error">{errors.termsConditions}</span>}
                        </div>
                        {isOtpSent && (
                          // true isOtpSent
                          <>
                            <div className="input-group">
                              {/* <label>
                                OTP <span style={{ marginLeft: "190px" }}>{otpTimer}</span>
                              </label> */}

                              <div className="otp-input">
                                <OTPInput setOtp={setOtp} otp={otp} />
                              </div>
                              {errors.otp && touched.otp && <span className="form-error">{errors.otp}</span>}
                            </div>
                            <div>
                              {/* <p>OTP Timer Example</p> */}
                              <OtpTimer
                                initialTime={30}
                                role={props.type}
                                userData={{ mobile: values.mobile, name: values.fullname, email: values.email, password: values.password }}
                              />
                            </div>
                            <div>
                              <p className="mt-4">4 digit OTP is been sent on your email address.</p>
                              <div className="d-flex align-items-center mb-4">
                                <p className="mb-0 me-5">Didnt Receive Yet?</p>
                                {/* <div className="d-flex resend-otp">
                                  <span className="image-container me-2">
                                    <Image src={renderImage("/images/login/icon-resend.png")} layout="fill" className="image" />
                                  </span>
                                  <p className="mb-0">Resend</p>
                                </div> */}
                              </div>
                            </div>
                          </>
                        )}
                        <div className="input-group mb-0">
                          <Button type="submit" className="btn btn-primary btn-submit" disabled={(!values.termsConditions && !isValid) || loading}>
                            {loading ? <Loader /> : `${isOtpSent ? "Verify OTP" : "Sign Up Now"}`}
                          </Button>
                        </div>
                      </Form>
                    )}
                  </Formik>
                </div>
              </div>
            </div>
          </div>
        )}
      </div>
      <TermsAndConditionModel isOpenEis={isOpenEis} setIsOpenEis={setIsOpenEis} />
    </Fragment>
  );
};

export default Signup;