import { useEffect, useRef, useState, useContext } from "react";
import { Context } from "../context/contex";

import {
 IonCol,
 IonContent,
 IonGrid,
 IonHeader,
 IonIcon,

 IonPage,
 IonRow,
 IonText,
 IonToolbar,
 IonButtons,
 IonBackButton,
 IonTitle,
 useIonRouter,
} from "@ionic/react";
import {
 arrowForwardOutline,
 arrowBackOutline,
 alertCircle,
} from "ionicons/icons";
import "./Otp.css";
import KeypadInputs from "../components/Keypad/KeypadInputs";
import Keypad from "../components/Keypad/Keypad";
//import logo from "/assets/logo/vinpace.png";
import Toast from "../components/Toasts";

const VerifyPassResetCode: React.FC = () => {
 const [correctCode, setCorrectCode] = useState<number[]>([]);

 const [email, setEmail] = useState<string>("");

 const [keypadValues, setKeypadValues] = useState<number[]>([0, 0, 0, 0]);
 const [activeIndex, setActiveIndex] = useState<number>(0);
 const [toastShow, setToastShow] = useState<boolean>(false);

 const [incorrect, setIncorrect] = useState<boolean>(false);
 const [correct, setCorrect] = useState<boolean>(false);
 const router = useIonRouter();

 const context = useContext(Context);

 if (!context) {
  return <div>Loading...</div>;
 }

 const { storage, presentToast, abr, apiRequest } = context;


 useEffect(() => {
  const setCode = async () => {
   const mail = await storage?.get(abr+"_email_address");

   if (
    mail !== null &&
    mail !== undefined
   ) {
    setEmail(mail);
   } else {
    router.push("/intro", "forward", "replace");
   }
  };

  if (storage) {
   setCode();
  }
 }, [storage]);

 const handleClick = (index: number, value: number) => {
  const tempValues = [...keypadValues];
  tempValues[index] = value;
  setKeypadValues(tempValues);
  setActiveIndex((activeIndex) => activeIndex + 1);
 };

 const Resend = async () => {
  if (!email) {
   presentToast(
    "top",
    "For some reason we could not find your email address..",
    () => null,
    "danger",
    alertCircle
   );
   return;
  }
   const data = await apiRequest(
  "POST",
  "", //url
  {
 action: "resend_v_email",
     email: email,
  },
  false,       // require auth
  true      // show success or error messages
) as any;

 };

 const handleRemove = () => {
  const tempValues = [...keypadValues];
  tempValues[activeIndex - 1] = 0;
  setKeypadValues(tempValues);
  activeIndex > 0 && setActiveIndex((activeIndex) => activeIndex - 1);
  setIncorrect(false);
  setCorrect(false);
 };

 useEffect(() => {
  const checkCode = async () => {
    //if(keypadValues.length !== 4) return;
    if(activeIndex === keypadValues.length && email){
    const code = keypadValues.join("");
 const data = await apiRequest(
  "POST",
  "", //url
  {
 action: "verify_code",
     code: String(code),
     email: email,
   
  },
  false,       // require auth
  true      // show success or error messages
) as any;

 if(data.success){
  setCorrect(true);
  await storage?.set(abr+"_reset_code", code);
  await storage?.set(abr+"_email_address", email);
   
     setTimeout(async () => {
     router.push("/change-password", "forward", "replace");
     }, 900);
   }
   else {
     setIncorrect(true);
     return false;
   }
   

    }
else {
  return;
}
  };

  checkCode();
 }, [activeIndex, keypadValues, correctCode]);

 const stringValues: string[] = keypadValues.map((value) => value.toString());

 return (
  <IonPage>
   <IonHeader>
    <IonToolbar className="nobg ion-padding-horizontal">
     <IonButtons slot="start">
      <IonBackButton
       text=""
       icon={arrowBackOutline}
       defaultHref="/"
      ></IonBackButton>
     </IonButtons>
     <IonTitle>VERIFY</IonTitle>
    </IonToolbar>
   </IonHeader>
   <IonContent fullscreen className="ion-content-bg">
    <IonGrid className="ion-text-center ion-padding-top">
     <IonRow>
      <IonCol size="12">
        <div>
         <img className="paynaire-logo logo" />
</div>
       <IonText>Enter the 4 digit code we sent to {email}</IonText>
       {incorrect && <p className={"incorrect"}>Wrong code entered</p>}
      </IonCol>
     </IonRow>

    
     <KeypadInputs
      incorrect={incorrect}
      correct={correct}
      values={stringValues}
      activeIndex={activeIndex}
     />

     <Keypad
      text="Resend"
      handleRemove={handleRemove}
      handleClick={handleClick}
      activeIndex={activeIndex}
      amount={keypadValues.length}
      correct={correct}
      handleResend={Resend}
     />
    </IonGrid>

    <Toast
     isOpen={toastShow}
     message="Code has been resent!"
     duration={4000}
     messageType="success"
     icon={arrowForwardOutline}
     position="top"
    />
   </IonContent>
  </IonPage>
 );
};

export default VerifyPassResetCode;
