import React, { useEffect, useState } from "react";
import { Button, CustomSpinner } from "..";
import { useLocation, useNavigate } from "react-router-dom";
import { RouteHandler } from "../../router/routes";
import { updateUserDetails } from "../../store/UserDetails";
import { useDispatch } from "react-redux";
import { verifyOTP } from "../../core/apiRequest";
import { RequestStatus } from "../../core/models";

type FormType = {
  [index: string] : string
};

type HandleChange = {
  name: string;
  value: string;
};

export default function Login() {
  const navigate = useNavigate()
  const { state } = useLocation();
  const dispatch = useDispatch()

  const [requestStatus, setRequestStatus] = useState<RequestStatus>({loading:false, status:null, message:'', data:{}})

  let [values, setValues] = useState<FormType>({
    otp1: "",
    otp2: "",
    otp3: "",
    otp4: "",
  });

  const handleChange = ({
    target: { name, value },
  }: {
    target: HandleChange;
  }): any => {
    setValues((prev:FormType) => ({ ...prev, [name]: value }));
  };

  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === "Backspace") {
      const { name } = e.target as HTMLInputElement;
      if(values[name]){
        setValues((prev: FormType) => ({ ...prev, [name]: "" }));
      }else{
        const keys = Object.keys(values)
        for(let i=keys.length-1; i>=0; i--){
          if(values[keys[i]]){
            setValues((prev: FormType) => ({ ...prev, [keys[i]]: "" }));
            break
          }
        }
      }
    }
  };

  const handleSubmit = () => {
    let reqData = {
      verify_uid: state?.verify_uid,
      otp: values.otp1+values.otp2+values.otp3+values.otp4
    }

    setRequestStatus((prev:RequestStatus) => ({...prev, loading:true}))
    verifyOTP(reqData).then(res => {
      if(!res?.data?.call_return){
        setRequestStatus({loading:false, status:false, message:'OTP is wrong', data:{}})
        return setTimeout(()=>{
          setRequestStatus({loading:false, status:null, message:'', data:{}})
        },4000)
      }
      setRequestStatus({loading:false, status:true, message:'OTP Verified', data:res?.data})
      localStorage.setItem('token', state?.verify_uid)
      let data = {firstname:'firstname', lastname:'lastname', uid:'28273737646466464'}
      dispatch(updateUserDetails(data));
      navigate(`/${state?.application_uid}`, {replace:true})
    }).catch(err =>{
      setRequestStatus({loading:false, status:false, message:'something went wrong', data:{}})
      console.log(err)
      return setTimeout(()=>{
        setRequestStatus({loading:false, status:null, message:'', data:{}})
      },4000)
    })
  }

  useEffect(() => {
    if (!state) {
      navigate(RouteHandler.loginpage, { replace: true });
      return;
    }
  }, []);

  useEffect(()=>{
    const formOTP = document.querySelectorAll('input')
    for (const i of formOTP) {
      if (i.value === '') {
        i.focus();
        break;
      }
    }
  },[values])

  return (
    <div className={`w-full overflow-y-auto bg-top bg-cover`}>
      <div className="w-full flex justify-center">
        <div className="w-full xs:max-w-[350px] md:max-w-[570px]">
          <div className="bg-white w-full rounded-2xl border-2 border-black">
            <div className="w-full p-5 sm:p-10 lg:p-20 flex flex-col justify-between items-center">
              <div className="mb-4">
                <h1 className="text-2xl text-center font-bold leading-3 tracking-wide text-black dark:text-black">
                    Enter OTP
                </h1>
                <p className="text-xl mt-4 text-center font-medium text-black dark:text-black">
                  Please enter verification code sent to you
                </p>
              </div>

              <div className="w-full sm:w-4/5">
                {/* INPUTS */}
                <div className="w-full flex justify-between gap-4">
                  <input
                      id='otp1'
                      name='otp1'
                      className={`custom-otp text-center w-12 h-12 outline-none border-b-2 border-b-[#5A2C82] placeholder:text-transparent transition-all duration-500`}
                      type='text'
                      placeholder=''
                      value={values.otp1}
                      onChange={handleChange}
                      maxLength={1}
                      onKeyDown={handleKeyDown}
                  />
                  <input
                      id='otp2'
                      name='otp2'
                      className={`custom-otp text-center w-12 h-12 outline-none border-b-2 border-b-[#5A2C82] placeholder:text-transparent transition-all duration-500`}
                      type='text'
                      placeholder=''
                      value={values.otp2}
                      onChange={handleChange}
                      maxLength={1}
                      onKeyDown={handleKeyDown}
                  />
                  <input
                      id='otp3'
                      name='otp3'
                      className={`custom-otp text-center w-12 h-12 outline-none border-b-2 border-b-[#5A2C82] placeholder:text-transparent transition-all duration-500`}
                      type='text'
                      placeholder=''
                      value={values.otp3}
                      onChange={handleChange}
                      maxLength={1}
                      onKeyDown={handleKeyDown}
                  />
                  <input
                      id='otp4'
                      name='otp4'
                      className={`custom-otp text-center w-12 h-12 outline-none border-b-2 border-b-[#5A2C82] placeholder:text-transparent transition-all duration-500`}
                      type='text'
                      placeholder=''
                      value={values.otp4}
                      onChange={handleChange}
                      maxLength={1}
                      onKeyDown={handleKeyDown}
                  />
                </div>

                <div className="mt-10 w-full">
                  {requestStatus.loading ?
                  <div className='w-full flex justify-center items-center'>
                    <CustomSpinner />
                  </div>
                  :
                  <Button
                    text="Enter"
                    className="rounded-md w-full text-xl capitalize font-bold"
                    onClick={handleSubmit}
                    disabled={!values.otp1 || !values.otp2 || !values.otp1 || !values.otp1}
                  />
                  }
                  {/* <Link to='#' className='text-black text-sm'>Forget your password?</Link> */}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
