import React, { useState, useRef, useNavigate, useCallback } from 'react';
import {
  CardContainer,
  CardBody,
  CardHeader,
  ModalCardContainer,
  CloseModalButton,
} from "./index.styled";
import { IoMdClose } from "react-icons/io";
import Modal from "react-modal";
import ButtonComponent from "../../button";
import useTranslation from "../../../hooks/useTranslation.jsx";
import wordStore from "../../../mc/wordStore.json";
const OTPSecurityModal = (props) => {
  const { findText } = useTranslation(wordStore);
  const modalCustomStyles = {
    overlay: {
      position: 'fixed',
      top: 0,
      left: 0,
      right: 0,
      bottom: 0,
      backgroundColor: 'rgba(0, 0, 0, 0.5)',
      zIndex: 9999999999,
      transition: 'opacity 2000ms ease-in-out',
    },
    content: {
      position: 'absolute',
      overflow: 'auto',
      WebkitOverflowScrolling: 'scroll',
      outline: 'none',
      top: '50%',
      left: '50%',
      right: 'auto',
      bottom: 'auto',
      marginRight: '-50%',
      transform: 'translate(-50%, -50%)',
      borderRadius: '30px',
      border: 'none',
      zIndex: 333333333,
      background: 'transparent',
      width: '450px',
    },
  };
  const [otpModal, setOtpModal] = useState(false);
  const [securityQuestionModal, setSecurityQuestionModal] = useState(false);
  const [otp, setOtp] = useState(['', '', '', '', '', '']);
  const inputRefs = useRef([]);
  const [selectedOption, setSelectedOption] = useState("");
  const handleInputChange = (event) => {
    const { name, value } = event.target;
    setFormData((prevState) => ({
      ...prevState,
      [name]: value,
    }));
  };
  const handleOtpChange = (event, index) => {
    const value = event.target.value;

    // Only allow numeric input and set max length to 1
    if (/^[0-9]{0,1}$/.test(value)) {
      const newOtp = [...otp];
      newOtp[index] = value;
      setOtp(newOtp);

      // Move focus to the next input if the current input is filled
      if (value !== '' && index < 5) {
        inputRefs.current[index + 1].focus();
      } else if (!value && index > 0) {
        inputRefs.current[index - 1].focus();
      }
    }
  };
  const handlePaste = (event, index) => {
    event.preventDefault();
    const pastedText = event.clipboardData.getData('text');
    //console.log(pastedText, "text");
    const sanitizedText = pastedText.replace(/[^0-9]/g, "").slice(0, 6);
    const textArray = [];
    for (let i = 0; i < sanitizedText.length; i++) {
      const digit = sanitizedText[i];
      textArray.push(digit);
      if (inputRefs.current[index + i]) {
        inputRefs.current[index + i].value = digit;
      }
    }
    setOtp(textArray);
  };
  return (
    <Modal
      isOpen={props.isOpen}
      onRequestClose={props.onRequestClose}
      style={modalCustomStyles}
      closeTimeoutMS={0}
      ariaHideApp={false}
      contentLabel={findText("Selected Option")}
    >
      <ModalCardContainer>
        <CloseModalButton onClick={props.onRequestClose}>
          <IoMdClose />
        </CloseModalButton>

        <CardContainer>
          <CardHeader></CardHeader>

          <CardBody>
            <p className="mdld-2fa-title">
              {findText("An OTP has been sent to your")}{" "}
              {props.OTPtype === "phone" ? (
                <>
                  Phone <br /> number that ends with
                </>
              ) : (
                'email address'
              )}{' '}
              {props.OTPvalue}
            </p>

            <div className="otp-container">
              {otp.map((value, index) => (
                <div className="otp-box">
                  <input
                    type="text"
                    id={`otp-${index}`}
                    name={`otp-${index}`}
                    key={`otp-${index}`}
                    value={value}
                    onChange={(event) => handleOtpChange(event, index)}
                    onPaste={(event) => handlePaste(event, index)}
                    maxLength={1}
                    ref={(el) => (inputRefs.current[index] = el)}
                  />{' '}
                </div>
              ))}
            </div>

            <p className="res_txt">
              {findText("Resend Code")}
              <span>00:00</span>
            </p>

            <div className="btn__footer">
              <ButtonComponent
                text={findText("Proceed")}
                type="submit"
                styles={{
                  width: "195px",
                  margin: 0,
                  height: 40,
                }}
                onClick={props.nextOpen}
                // disabled={otp.includes("")}
              />
            </div>
          </CardBody>
        </CardContainer>
      </ModalCardContainer>
    </Modal>
  );
};
export default OTPSecurityModal;
