import { useEffect, useRef, useState, useContext } from "react";

import {
 IonContent,
 IonPage,
 IonCard,
 IonCardContent,
 IonItem,
 IonIcon,
 IonInput,
 IonButton,
 IonLabel,
 IonCardTitle,
 IonRouterLink,
 IonHeader,
 IonToolbar,
 IonTitle,
 IonButtons,
 IonBackButton,
 useIonRouter,
 IonCardSubtitle,
} from "@ionic/react";
import {
 lockClosed,
 arrowBackOutline,
 alertCircle,
 checkmarkCircle,
 eye,
 eyeOff,
} from "ionicons/icons";

import "../Login.css";
//import logo from "/assets/logo/vinpace.png";
import { Context } from "../../context/contex";

const SetPin: React.FC = () => {
 const [pin, setPin] = useState("");
 const [pin2, setPin2] = useState("");
 const [showPin, setShowPin] = useState(false);

 const [busy, setBusy] = useState(false);
 const router = useIonRouter();

 const context = useContext(Context);

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

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

 const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
  const { value } = e.target;

  // Ensure the value is numeric and has a maximum length of 4
  if (/^\d*$/.test(value) && value.length <= 4) {
   setPin(value);
  }
 };

 const handleChange2 = (e: React.ChangeEvent<HTMLInputElement>) => {
  const { value } = e.target;

  if (/^\d*$/.test(value) && value.length <= 4) {
   setPin2(value);
  }
 };

 const setNewPin = async () => {
  if (pin.trim() === "" || pin2.trim() === "") {
   presentToast(
    "top",
    "Please enter your new 4 digits pin.",
    () => null,
    "danger",
    alertCircle
   );
   return;
  }
  if (pin.trim() !== pin2.trim()) {
   presentToast(
    "top",
    "Both pins do not match.",
    () => null,
    "danger",
    alertCircle
   );
   return;
  }
 const email = await storage?.get(abr + "_email_address");

const token =
  email ??
  (await storage?.get(abr + "_auth_token"));


  if (!token) {
   presentToast(
    "top",
    "Your login session has expired. Please login again.",
    () => null,
    "danger",
    alertCircle
   );
   setTimeout(() => {
    router.push("/login", "forward", "replace");
   }, 2000);
  }

  try {
   setBusy(true);
   const response = await fetch(apiURL, {
    method: "POST",
    headers: {
     "Content-Type": "application/x-www-form-urlencoded",
    },
    body: new URLSearchParams({
     action: "set_pin",
     email: token,
     pin: pin,
    }),
   });

   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 {
    await storage?.set("vin_tx_pin", pin);
    // await storage?.set("vin_email_address", data.email);
    presentToast("top", data.message, () => null, "success", checkmarkCircle);
    setBusy(false);

    // console.log("Fetched data:", data);
    setTimeout(() => {
     context.logOut();
    }, 3000);
   }
  } catch (error: any) {
   setBusy(false);

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

 /*useEffect(() => {
    console.log("INFO", userInfo?.email);
  }, [userInfo]);
*/
 return (
  <IonPage>
   <IonHeader>
    <IonToolbar className="nobg ion-padding-horizontal">
     <IonButtons slot="start">
      <IonBackButton
       text=""
       icon={arrowBackOutline}
       defaultHref="/"
      ></IonBackButton>
     </IonButtons>
     <IonTitle>Set Pin</IonTitle>
    </IonToolbar>
   </IonHeader>
   <IonContent fullscreen className="ion-content-bg">
    <div className="ion-text-center">
     <img className="paynaire-logo" />

    </div>
    <div className="blue-background">
     <IonCard className="login-card">
      <IonCardTitle className="card-title">Set your PIN</IonCardTitle>
      <IonCardSubtitle className="ion-text-center">
       You will use this PIN to unlock the app and also approve transactions on
       your account.
      </IonCardSubtitle>
      <IonCardContent className="nobg">
       <IonItem lines="none" className="nobg">
        <IonIcon
         slot="start"
         icon={showPin ? eyeOff : eye}
         onClick={() => setShowPin(!showPin)}
         className="toggle-icon"
        />
        <input
         placeholder="Enter new pin"
         className="custom-input ion-padding"
         type={showPin ? "text" : "password"}
         value={pin}
         onChange={handleChange}
        />
       </IonItem>
       <IonItem lines="none" className="nobg">
        <IonIcon
         slot="start"
         icon={showPin ? eyeOff : eye}
         onClick={() => setShowPin(!showPin)}
         className="toggle-icon"
        />
        <input
         placeholder="Re-enter new pin"
         className="custom-input ion-padding"
         type={showPin ? "text" : "password"}
         value={pin2}
         onChange={handleChange2}
        />
       </IonItem>

       <IonButton
        expand="block"
        className="custom-login-btn"
        onClick={setNewPin}
       >
        SET PIN
       </IonButton>
       <div className="create-account">
        <p>
         Need some help?{" "}
         <IonRouterLink routerLink="/contact">Contact support</IonRouterLink>
        </p>
       </div>
      </IonCardContent>
     </IonCard>
    </div>
   </IonContent>
  </IonPage>
 );
};

export default SetPin;
