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,
 IonLoading
} 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 ChangePassword: React.FC = () => {
 const [pin, setPin] = useState("");
 const [pin2, setPin2] = useState("");
 const router = useIonRouter();
 const [showPin, setShowPin] = useState(false);
 const [showPin2, setShowPin2] = useState(false);
 const context = useContext(Context);

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

 const { storage, presentToast, userInfo, validUser, busy, setBusy, abr, apiRequest } =
  context;

 const setNewPin = async () => {
  const stored = await storage?.get(abr+"_email_address");
  const code = await storage?.get(abr+"_reset_code");

  if (!pin || !pin2) {
   presentToast(
    "top",
    "Please enter your new password.",
    () => null,
    "danger",
    alertCircle
   );
   return;
  }
  if (pin !== pin2) {
   presentToast(
    "top",
    "Both passwords do not match.",
    () => null,
    "danger",
    alertCircle
   );
   return;
  }

  if (!userInfo && !stored) {
   presentToast(
    "top",
    "User details not found. Please login again.",
    () => null,
    "danger",
    alertCircle
   );
   setTimeout(() => {
    router.push("/login", "forward", "replace");
   }, 2000);
   return;
  }
    const data = await apiRequest(
  "POST",
  "", //url
  {
action: "change_password",
     email: userInfo?.email || stored,
     pin: pin,
     code: code || null,
  },
  false,       // require auth
  true      // show success or error messages
) as any;
 if (!data.success) {

    return;
    // console.error("Error:", data.error);
   } else {
    await storage?.clear();

    // console.log("Fetched data:", data);
    setTimeout(() => {
     window.location.replace("login");
    }, 1000);
   }

 };


 return (
  <IonPage>
   <IonHeader>
    <IonToolbar className="nobg ion-padding-horizontal">
     <IonButtons slot="start">
      <IonBackButton
       text=""
       icon={arrowBackOutline}
       defaultHref="/"
      ></IonBackButton>
     </IonButtons>
     <IonTitle>Set New Password</IonTitle>
    </IonToolbar>
   </IonHeader>
   <IonContent fullscreen className="ion-content-bg">
      <IonLoading
             isOpen={busy}
             message="Please wait..."
             spinner="circles"
             className="custom-loading"
            />
    <div className="ion-text-center">
     <img className="paynaire-logo" />

    </div>
    <div className="blue-background">
     <IonCard className="login-card">
      <IonCardTitle className="card-title">Change Password</IonCardTitle>

      <IonCardContent className="nobg">
       <IonItem lines="none" className="nobg password-field">
        <input
         placeholder="New password"
         className="custom-input ion-padding"
         type={showPin ? "text" : "password"}
         value={pin}
         onChange={(e) => setPin(e.target.value || "")}
        />
        <IonIcon
         slot="end"
         icon={showPin ? eyeOff : eye}
         onClick={() => setShowPin(!showPin)}
         className="toggle-icon"
        />
       </IonItem>

       <IonItem lines="none" className="nobg password-field">
        <input
         placeholder="Confirm password"
         className="custom-input ion-padding"
         type={showPin2 ? "text" : "password"}
         value={pin2}
         onChange={(e) => setPin2(e.target.value || "")}
        />
        <IonIcon
         slot="end"
         icon={showPin2 ? eyeOff : eye}
         onClick={() => setShowPin2(!showPin2)}
         className="toggle-icon"
        />
       </IonItem>
       <IonButton
        expand="block"
        className="custom-login-btn"
        onClick={setNewPin}
       >
        Set New Password
       </IonButton>
       <div className="create-account">
        <p>
         Need some help?{" "}
         <IonRouterLink routerLink="/contact">Contact support</IonRouterLink>
        </p>
       </div>
      </IonCardContent>
     </IonCard>
    </div>
   </IonContent>
  </IonPage>
 );
};

export default ChangePassword;
