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,
 IonButton,
 IonAlert,
} 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 logo from "/assets/logo/vinpace.png";
import Toast from "../../components/Toasts";
import ThemeToggle from "../../components/ThemeToggle"; // your toggle

const Unlock: React.FC = () => {
 const [correctCode, setCorrectCode] = useState<number[]>([]);
 const [stringCode, setStringCode] = useState<string>("");
 const router = useIonRouter();
 const [cancel, setCancel] = useState(false);
 const [pinModal, setPinModal] = useState(false);

 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 context = useContext(Context);

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

 const { logOut, presentToast, userInfo, setAuth, apiURL, busy, setBusy } =
  context;

 useEffect(() => {
  const setCode = async () => {
   if (!userInfo || !userInfo.tx_pin) return;
   const code = userInfo.tx_pin;

   if (code && code !== null && code !== undefined) {
    setCorrectCode([...String(code)].map(Number));
    setStringCode(String(code));
   } else {
    router.push("/set-pin", "forward", "replace");
    return;
   }
  };

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

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

 const getPin = async (pass: string) => {
  if (cancel) return;
  if (!userInfo || !userInfo.id) {
   presentToast(
    "top",
    "Invalid session. Restart app.",
    () => null,
    "danger",
    alertCircle
   );
   return;
  }

  if (!userInfo.tx_pin) {
   presentToast(
    "top",
    "You have no PIN. Set it now.",
    () => router.push("/set-pin"),
    "danger",
    alertCircle
   );
   return;
  }

  if (!pass) {
   presentToast(
    "top",
    "Password is required.",
    () => null,
    "danger",
    alertCircle
   );
   return;
  }

  setBusy(true);
  try {
   const response = await fetch(apiURL, {
    method: "POST",
    headers: {
     "Content-Type": "application/x-www-form-urlencoded",
    },
    body: new URLSearchParams({
     action: "get_user_pin",
     user_id: userInfo.id.toString(),
     password: pass,
    }),
   });

   const data = await response.json();
   setBusy(false);

   if (!data.success) {
    presentToast("top", data.message, () => null, "danger", alertCircle);
    return;
   }

   // Successfully retrieved PIN
   presentToast(
    "top",
    "PIN sent successfully.",
    () => null,
    "success",
    checkmarkCircle
   );
  } catch (error: any) {
   console.error("Error:", error.message);
   presentToast(
    "top",
    "Network error. Try again.",
    () => null,
    "danger",
    alertCircle
   );
  }
  setBusy(false);
 };

 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 (activeIndex === keypadValues.length) {
    let error = false;
    keypadValues.forEach((value, index) => {
     if (value !== correctCode[index]) {
      error = true;
      return false;
     }
    });
    if (error) {
     setIncorrect(true);
        presentToast(
    "top",
    "Incorrect PIN.",
    () => null,
    "danger",
    alertCircle
   );
    } else {
     setCorrect(true);
     setAuth(true);
  
    }
   }
  };

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

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

 return (
  <div>
  <IonHeader>
  <IonToolbar className="nobg ion-padding-horizontal">

    <IonTitle>Unlock</IonTitle>

    <IonButtons slot="end">
     <ThemeToggle iconOnly={true}/>
      <IonButton
        fill="outline"
        size="small"
        color="medium"
        onClick={logOut}
      >
        Logout
      </IonButton>
    </IonButtons>

  </IonToolbar>
</IonHeader>

    <IonLoading
     isOpen={busy}
     message="Please wait..."
     spinner="circles"
     className="custom-loading"
    />
    <IonGrid className="ion-text-center ion-padding-top">
     <IonRow className="">
      <IonCol size="12">
        <div>
        <img className="paynaire-logo logo" />
</div>
       <IonText>
        Welcome back {userInfo?.first_name.toUpperCase()}. Enter your 4 digits
        PIN to unlock the app.
       </IonText>
    
      </IonCol>
     </IonRow>

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

     <Keypad
      text="I Forgot"
      handleRemove={handleRemove}
      handleClick={handleClick}
      activeIndex={activeIndex}
      amount={keypadValues.length}
      correct={correct}
      handleResend={() => setPinModal(true)}
     />
    </IonGrid>

    <Toast
     isOpen={toastShow}
     message="Code has been resent!"
     duration={4000}
     messageType="success"
     icon={arrowForwardOutline}
     position="top"
    />
    <IonAlert
     isOpen={pinModal}
     header="Request PIN"
     subHeader={`Enter your password to receive your PIN by email.`}
     className="pin-alert"
     buttons={[
      {
       text: "Cancel",
       cssClass: "alert-button-cancel",
       handler: () => {
        setCancel(true);
       },
      },
      {
       text: "Get PIN",
       cssClass: "alert-button-confirm",

       handler: () => setCancel(false),
      },
     ]}
     inputs={[
      {
       type: "password",
       placeholder: "Enter Password",
      },
     ]}
     onDidDismiss={(e) => {
      setPinModal(false);
      getPin(e.detail.data.values[0]);
     }}
     backdropDismiss={false}
    ></IonAlert>
  </div>
 );
};

export default Unlock;
