import React, { useEffect, useState } from "react";
import Orange_Btn from "../../common_btn/orange_btn/Orange_Btn";
import { Form, Modal } from "react-bootstrap";
import { useForm } from "react-hook-form";
import "./Reset_Password_Modal.css";
import { faEye, faEyeSlash } from "@fortawesome/free-solid-svg-icons";
import PasswordChecklist from "react-password-checklist";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import Gray_Btn from "../../common_btn/gray_btn/Gray_Btn";
import Green_btn from "../../common_btn/green_btn/Green_btn";
import "./Reset_Password_Modal.css";
import { useDispatch, useSelector } from "react-redux";
import { sendMobileOtp, verifyOtp } from "../../../../features/auth/authSlice";
import { red } from "@mui/material/colors";
import { appSetup } from "../../../../features/master/masterSlice";
import Black_Btn from "../../common_btn/black_btn/Black_Btn";

const Reset_Password_Modal = ({
  email,
  contact,
  setContact,
  setEmail,
  ...props
}) => {
  const {
    control,
    register,
    reset,
    setError,
    handleSubmit,
    formState: { errors },
  } = useForm();
  const [otp, setOtp] = useState(["", "", "", ""]);
  // const [email, setEmail] = useState('');
  // const [contact, setContact] = useState('');
  const [showOtpDiv, setShowOtpDiv] = useState(false);
  const handleInputChange = (e, index) => {
    const value = e.target.value;
    if (isNaN(value) || value.length > 1) {
      return;
    }

    const newOtp = [...otp];
    newOtp[index] = value;
    setOtp(newOtp);

    // Focus the next input field
    if (value && index < otp.length - 1) {
      document.getElementById(`otp-${index + 1}`).focus();
    }
  };

  const data = {};
  const dispatch = useDispatch();
  const onSubmit = async (user) => {
    const validator = require("validator");

    if (validator.isEmail(user.email)) {
      console.log("The email address is valid.");
      setEmail(user.email);
      data.email = user.email;
    } else {
      console.log("The email address is invalid.");
      setContact(user.email);
      data.contact_no = user.email;
    }
    const res = await dispatch(sendMobileOtp(data));

    if (res.meta?.requestStatus === "fulfilled") {
      setTImer(90);
      setShowOtpDiv(true);
    } else if (res.meta?.requestStatus === "rejected") {
      setError("email", {
        type: "custom",
        message: "Email Address / Mobile  Number not Found",
      });
    }
  };

  const [showSignUp, setShowSignUp] = useState(false);
  const validateOTp = async () => {
    const enteredOtp = otp.join("");

    if (enteredOtp.length !== 4) {
      setError("otp", { type: "manual", message: "OTP is required" });
      return;
    }
    const data = {
      email: email,
      contact_no: contact,
      otp: otp.join(""),
    };

    const verify = await dispatch(verifyOtp(data));

    if (verify.meta?.requestStatus === "fulfilled") {
      props?.onHide();
      props?.setShowSetPassModal();
      setShowOtpDiv(false);
      setOtp(["", "", "", ""]);
    } else if (verify.meta?.requestStatus === "rejected") {
      setError("otp", { type: "custom", message: verify.payload?.errors });
    }
  };

  const handleKeyDown = async (e, index) => {
    if (e.key === "Backspace" && !otp[index] && index > 0) {
      document.getElementById(`otp-${index - 1}`).focus();
    }
  };

  const [timer, setTImer] = useState(30);
  const [disabled, setDisables] = useState(true);

  useEffect(() => {
    let interval;
    if (disabled) {
      interval = setInterval(() => {
        setTImer((prev) => {
          if (prev === 1) {
            clearInterval(interval);
            setDisables(false);
            return 0;
          }
          return prev - 1;
        });
      }, 1000);
    }
    return () => clearInterval(interval);
  }, [disabled]);

  const resendCode = async () => {
    setOtp(["", "", "", ""]);
    const data = {
      email: email,
      contact_no: contact,
    };
    if (disabled) return;
    const res = await dispatch(sendMobileOtp(data));
    setDisables(true);
    setTImer(90);
  };

  const app_setup = useSelector((state) => state.master.app_setup);

  // useEffect(() => {
  //   dispatch(appSetup());
  // }, [dispatch]);

  return (
    <Modal
      className="Reset_Password_Modal Login_Modal"
      size="md"
      {...props}
      centered
    >
      <div className="absolute_div">
        <div className="logo_holder">
          <img
            // src="/assets/images/logo/new_ekansi_logo.png"
            src={process.env.NEXT_PUBLIC_IMG_URL + app_setup?.logo}
            className="logo_img"
          />
        </div>
      </div>

      <Modal.Body>
        {!showOtpDiv && (
          <div className="reset_pass_main_form">
            <div className="close_img_div">
              <div className="title_div">
                <p className="title">Reset Your Password</p>
                <p className="sub_text">
                  Check your email for a password reset link
                </p>
              </div>
              <img
                src="/assets/images/modal/close.png"
                className="close_img"
                onClick={() => {
                  props?.onHide();
                }}
              />
            </div>

            <div className="reset_pass_div login_div">
              <div className="login_form_div">
                <Form>
                  <Form.Group className="gray_input_group input_group">
                    <Form.Label>Email / Mobile Number</Form.Label>
                    <Form.Control
                      type="text"
                      name="email"
                      placeholder="Enter your email or mobile number"
                      {...register("email", {
                        required: "Email is required",
                      })}
                    />
                    {/* {msg && <p >Email / number Not found</p>} */}
                    {errors.email && (
                      <div style={{ color: "red" }}>{errors.email.message}</div>
                    )}
                  </Form.Group>
                </Form>
              </div>

              <div className="btns_holder">
                
                <Black_Btn
                  btnText={"Submit"}
                  onClick={handleSubmit(onSubmit)}
                />

                <Gray_Btn
                  btnText={"Cancel"}
                  onClick={() => {
                    props?.onHide();
                  }}
                />
              </div>
            </div>
          </div>
        )}

        {showOtpDiv && (
          <div className="otp_main_div">
            <div className="close_img_div">
              <div className="title_div">
                <p className="title">OTP has been Sent </p>
                <p className="title">to the Email / Mobile Number</p>
              </div>
              <img
                src="/assets/images/modal/close.png"
                className="close_img"
                onClick={() => {
                  props?.onHide();
                }}
              />
            </div>

            <div className="Otp-field-holder">
              <>
                {/* {(disabled) ? */}
                {otp.map((value, index) => (
                  <Form.Control
                    name="otp"
                    key={index}
                    type="text"
                    className="otp-field"
                    maxLength="1"
                    value={value}
                    id={`otp-${index}`}
                    onChange={(e) => handleInputChange(e, index)}
                    onKeyDown={(e) => handleKeyDown(e, index)}
                  />
                ))}
              </>
              {errors.otp && (
                <div style={{ color: "red" }}>{errors.otp.message}</div>
              )}
            </div>

            <div className="btns_holder">
              {/* {disabled ? (
                <>
                  <Green_btn btnText="Submit" onClick={() => validateOTp()} />
                  Resend Code in {timer} seconds
                </>
              ) : (
                <Green_btn btnText="Resend" onClick={() => resendCode()} />
              )} */}
              {disabled ? (
                <p>Resend Code in {timer} seconds</p>
              ) : (
                <p
                  className="link_text"
                  onClick={() => {
                    resendCode();
                  }}
                >
                  Resend Code
                </p>
              )}
              <Black_Btn
                btnText={"Submit"}
                onClick={() => {
                  validateOTp();
                }}
              />
            </div>
          </div>
        )}
      </Modal.Body>
    </Modal>
  );
};

export default Reset_Password_Modal;
