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

import {
 IonCol,
 IonContent,
 IonGrid,
 IonHeader,
 IonIcon,
 IonImg,
 IonItem,
 IonList,
 IonPage,
 IonRow,
 IonText,
 IonToolbar,
 IonButtons,
 IonBackButton,
 IonTitle,
 IonLoading,
 useIonRouter,
} from "@ionic/react";
import {
 arrowForwardOutline,
 arrowBackOutline,
 alertCircle,
 checkmarkCircle,
} from "ionicons/icons";
import "../Otp.css";
import KeypadInputs from "../../components/Keypad/KeypadInputs";
import Keypad from "../../components/Keypad/Keypad";
import Toast from "../../components/Toasts";

const VerifyEmail: React.FC = () => {
 const [correctCode, setCorrectCode] = useState<number[]>([]);
 const [stringCode, setStringCode] = useState<string>("");
 const router = useIonRouter();

 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 [busy, setBusy] = useState(false);

 const context = useContext(Context);

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

 const { apiURL, storage, presentToast, validUser, abr } = context;

 useEffect(() => {
  if (!validUser) {
   //router.push("/login", "forward", "replace");
  }
 }, [validUser]);

 useEffect(() => {
  const setCode = async () => {
   const code = await storage?.get(abr+"_email_code");
   const mail = await storage?.get(abr+"_email_address");
   // console.log("CODE:", code);

   if (
    code &&
    code !== null &&
    code !== undefined &&
    mail !== null &&
    mail !== undefined
   ) {
    setCorrectCode([...String(code)].map(Number));
    setEmail(mail);
    setStringCode(String(code));
   } else {
    // Handle the case where code is not available
    // For example, redirect to another page
    router.push("/intro", "forward", "replace");
    return;
   }
  };

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

 useEffect(() => {
  //  console.log("CCODE:", correctCode);
  //  console.log("EMAIL:", email);
 }, [correctCode, email]);

 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;
  }
  try {
   setBusy(true);
   const response = await fetch(apiURL, {
    method: "POST",
    headers: {
     "Content-Type": "application/x-www-form-urlencoded",
    },
    body: new URLSearchParams({
     action: "resend_v_email",
    /// code: stringCode,
     email: email,
    }),
   });

   if (!response.ok) {
    throw new Error(`HTTP error! Status: ${response.status}`);
   }

   const data = await response.json();
   if (!data.success) {
    presentToast("top", data.message, () => null, "danger", alertCircle);
    setBusy(false);
    return;
    // console.error("Error:", data.error);
   } else {
    presentToast("top", data.message, () => null, "success", checkmarkCircle);
    setBusy(false);
   }
  } catch (error: any) {
   setBusy(false);

   console.error("Error:", error);
  }
 };

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

   const verify = async () => {
  if (!stringCode) {
   presentToast(
    "top",
    "For some reason we could not find your code..",
    () => null,
    "danger",
    alertCircle
   );
   return;
  }
  try {
   setBusy(true);
   const response = await fetch(`${apiURL}`, {
    method: "POST",
    headers: {
     "Content-Type": "application/x-www-form-urlencoded",
    },
    body: new URLSearchParams({
     code: stringCode,
     action: 'verify_email'
    }),
   });

   if (!response.ok) {
    throw new Error(`HTTP error! Status: ${response.status}`);
   }

   const data = await response.json();
   if (!data.success) {
    presentToast("top", data.message, () => null, "danger", alertCircle);
    setBusy(false);
    return false;
    // console.error("Error:", data.error);
   } else {
    presentToast("top", data.message, () => null, "success", checkmarkCircle);
    setBusy(false);
    return true;
   }
  } catch (error: any) {
   setBusy(false);

   console.error("Error:", error);
   return false;
  }
 };

 useEffect(() => {
  const checkCode = async () => {
   if (activeIndex === keypadValues.length) {
    let error = false;
    keypadValues.forEach((value, index) => {
     if (value !== correctCode[index]) {
      error = true;
      return false;
     }
    });
    if (error) {
     setIncorrect(true);
      presentToast("top", 'Invalid code', () => null, "danger", alertCircle);
    } else {
     const v = await verify();
     setTimeout(async () => {
      if (v) {
      setCorrect(true);
       await storage?.remove(abr+"_email_code");
       router.push("/set-pin", "forward", "replace");
      }
     }, 900);
    }
   }
  };

  checkCode();
 }, [activeIndex, keypadValues, correctCode, storage]);
 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">
    <IonLoading
     isOpen={busy}
     message="Please wait..."
     spinner="circles"
     className="custom-loading"
     // onDidDismiss={() => setShowLoading(false)}
    />
    <IonGrid className="ion-text-center ion-padding-top">
     <IonRow>
      <IonCol size="12">
        <img className="paynaire-logo" />

       <IonText>Enter the 4 digit code we sent to {email}</IonText>
    
      </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 VerifyEmail;
