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,
} from "@ionic/react";
import { arrowForwardOutline, arrowBackOutline } 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 Otp: React.FC = () => {
 const correctCode = [2, 5, 2, 0];
 const [keypadValues, setKeypadValues] = useState<number[]>([0, 0, 0, 0]);
 const [activeIndex, setActiveIndex] = useState<number>(0);
 const [toastShow, setToastShow] = useState<boolean>(false);
 const successRef = useRef<HTMLIonRowElement>(null);

 const [incorrect, setIncorrect] = useState<boolean>(false);
 const [correct, setCorrect] = useState<boolean>(false);
 const context = useContext(Context);

 if (!context) {
  // Handle the case when context is null (for example, return a loading state or throw an error)
  return <div>Loading...</div>;
 }

 const { apiURL, storage } = context;

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

 const Resend = () => {
  setToastShow(false);
  setToastShow(true);
  console.log(toastShow);
 };

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

 useEffect(() => {
  if (activeIndex === keypadValues.length) {
   let error = false;
   keypadValues.forEach((value, index) => {
    if (value !== correctCode[index]) {
     error = true;
     return false;
    }
   });
   if (error) {
    setIncorrect(true);
   } else {
    setCorrect(true);
    setTimeout(() => {
     if (successRef.current) {
      successRef.current.classList.remove("hidden");
      successRef.current.classList.add("success");
     }
    }, 900);
   }
  }
 }, [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 Email</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 your 4 digit verification code</IonText>
       {incorrect && <p className={"incorrect"}>Wrong code entered</p>}
      </IonCol>
     </IonRow>

     <IonRow ref={successRef} className="ion-justify-content-center hidden">
      <IonCol size="12" className={"successContainer"}>
       <p className={"successText"}>
        Awesome! You may continue.
        <br />
        <span className={"successContinue"}>
         Continue&nbsp;&nbsp;
         <IonIcon icon={arrowForwardOutline} />
        </span>
       </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 Otp;
