OtpTimer.js 1.72 KB
import Image from "next/image";
import React, { useState, useEffect } from "react";
import { toast } from "react-toastify";
import { registerEndUser, registerVendor } from "../../redux/actions/userActions";
import { renderImage } from "../../services/imageHandling";

const OtpTimer = ({ initialTime, role, userData }) => {
  const [timeLeft, setTimeLeft] = useState(initialTime);
  const [isDisabled, setIsDisabled] = useState(true);

  useEffect(() => {
    if (timeLeft === 0) {
      setIsDisabled(false);
      return;
    }

    const timerId = setInterval(() => {
      setTimeLeft(prevTime => prevTime - 1);
    }, 1000);

    return () => clearInterval(timerId);
  }, [timeLeft]);

  const handleResend = async () => {
    setTimeLeft(initialTime);
    setIsDisabled(true);
    if (role == "user") {
      await registerEndUser(userData);
    }
    if (role == "vendor") {
      await registerVendor(userData);
    }
    toast.success("OTP has been sent again.");
    // if (onResend) {
    //   onResend();
    // }
  };

  const formatTime = seconds => {
    const minutes = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${minutes}:${secs < 10 ? "0" : ""}${secs}`;
  };

  return (
    <div>
      <p>Resend OTP in: {formatTime(timeLeft)}</p>
      <button className="d-flex resend-otp btn btn-primary btn-submit btn btn-primary" onClick={handleResend} disabled={isDisabled}>
        Resend OTP
      </button>
      {/* <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>
  );
};

export default OtpTimer;