import React, { useState, useContext, useEffect } from "react";
import {
 IonPage,
 IonCard,
 IonCardContent,
 IonIcon,
 IonButton,
 IonCardTitle,
 IonRouterLink,
 IonLoading,
 useIonRouter,

} from "@ionic/react";
import axios from "axios";

import {
alertCircle,
 checkmarkCircle,
} from "ionicons/icons";
import AppShell from "../../components/Header";

import "../Register.css";
import { Context } from "../../context/contex";
const states = [
 "Abuja",
 "Abia",
 "Adamawa",
 "Akwa Ibom",
 "Anambra",
 "Bauchi",
 "Bayelsa",
 "Benue",
 "Borno",
 "Cross River",
 "Delta",
 "Ebonyi",
 "Edo",
 "Ekiti",
 "Enugu",
 "Gombe",
 "Imo",
 "Jigawa",
 "Kaduna",
 "Kano",
 "Katsina",
 "Kebbi",
 "Kogi",
 "Kwara",
 "Lagos",
 "Nasarawa",
 "Niger",
 "Ogun",
 "Ondo",
 "Osun",
 "Oyo",
 "Plateau",
 "Rivers",
 "Sokoto",
 "Taraba",
 "Yobe",
 "Zamfara",
];
const KYC: React.FC = () => {
 const [country, setCountry] = useState<string | undefined>("Nigeria");
 const [address, setAddress] = useState<string>("");
 const [city, setCity] = useState<string>("");

 const [postalCode, setPostalCode] = useState<string>("");

 const [selectedState, setSelectedState] = useState<string | undefined>(
  undefined
 );

 const [bvn, setBvn] = useState<string>("");

 const [bvnDetails, setBvnDetails] = useState<any>({});
 const context = useContext(Context);
 const router = useIonRouter();

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

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


 const verifyBVN = async () => {
     if(!userInfo){
       presentToast(
    "top",
    "Session expired.",
    () => null,
    "danger",
    alertCircle
   );
      router.push("/login", "forward", "replace");

   return;
  }
  if (!bvn) {
   presentToast("top", `BVN  is empty.`, () => null, "danger", alertCircle);
   //  setAccount("");
   return;
  }
  if (bvn.length !== 11) {
   presentToast(
    "top",
    `BVN must be 11 digits`,
    () => null,
    "danger",
    alertCircle
   );
   // setAccount("");
   return;
  }
  setBusy(true);
  try {
   const response = await axios.post(
    apiURL,
    new URLSearchParams({ action: "validate_bvn", bvn }),
    {
     headers: {
      "Content-Type": "application/x-www-form-urlencoded",
     },
    }
   );

   if (!response.data.success) {
   // console.error("Error:", response.data.message);
     presentToast(
    "top",
    response.data.message,
    () => null,
    "danger",
    alertCircle
   );
   } else {
    setBvnDetails(response.data.data);
   // console.log("DATA:", response.data.data);
   }
  } catch (error: any) {
   console.error("Error:", error?.message || error);
  }
  setBusy(false);
 };

 const submitKYC = async () => {
    if(!userInfo){
       presentToast(
    "top",
    "Session expired.",
    () => null,
    "danger",
    alertCircle
   );
      router.push("/login", "forward", "replace");

   return;
  }
  if (
   selectedState?.trim() === "" ||
   bvn.trim() === "" ||
   address.trim() === "" ||
   city.trim() === "" ||
   postalCode.trim() === ""
  ) {
   presentToast(
    "top",
    "Please fill all required fields.",
    () => null,
    "danger",
    alertCircle
   );
   return;
  }

  if (Object.keys(bvnDetails).length === 0) {
   presentToast("top", `BVN is missing. `, () => null, "danger", alertCircle);
   return;
  }
       const token = await storage?.get(abr+"_auth_token");

  setBusy(true);
  const formData = new FormData();
  formData.append("country", String(country));
  formData.append("state", String(selectedState));
  formData.append("bvn", bvn);
  formData.append("address", address);
  formData.append("city", city);
  formData.append("postal_code", postalCode);
  formData.append("action", "submit_kyc");

  try {
   const response = await axios.post(apiURL, formData, {
    headers: {
     "Content-Type": "multipart/form-data",
     Authorization: `Bearer ${token}`
    },
   });
  // console.log("Form", response.data);
   if (response.data.success) {
    context.getUserInfo();
    presentToast(
     "top",
     `Thank you for submitting your KYC details.`,
     () => null,
     "success",
     checkmarkCircle
    );
    //   router.push("/home", "forward", "replace");

   } else {
    presentToast(
     "top",
     response.data.message,
     () => null,
     "danger",
     alertCircle
    );
   }
  } catch (error) {
   console.error("Error:", error);
  }
  setBusy(false);
 };


 return (
  <IonPage>
 <AppShell showBack={true} showLogo={false} title={'KYC Verification'}>

    <IonLoading
     isOpen={busy}
     message="Please wait..."
     spinner="circles"
     className="custom-loading"
     // onDidDismiss={() => setShowLoading(false)}
    />
   {userInfo?.id_verified === 0 && (
  <IonCard className="kyc-card">
    <IonCardTitle className="kyc-title">Complete your KYC</IonCardTitle>

    <IonCardContent>

      {/* BVN INPUT WITH SEND ICON */}
      <div className="input-with-icon">
        <input
          type="text"
          placeholder="Enter BVN"
          value={bvn}
          maxLength={11}
          disabled={Object.keys(bvnDetails).length !== 0}
          onChange={(e) => setBvn(e.target.value)}
        />
        <button
          className="send-btn"
          onClick={verifyBVN}
          disabled={!bvn || bvn.length !== 11 || Object.keys(bvnDetails).length !== 0}
        >
          ➤
        </button>
      </div>

      {Object.keys(bvnDetails).length > 0 && (
        <>
          {/* READONLY AUTO-FILLED */}
          <input className="kyc-input" value={bvnDetails.first_name} readOnly />
          <input className="kyc-input" value={bvnDetails.last_name} readOnly />
          <input className="kyc-input" value={bvnDetails.date_of_birth} readOnly />
          <input className="kyc-input" value={country} readOnly />

          {/* STATE */}
          <select
            className="kyc-input"
            value={selectedState}
            onChange={(e) => setSelectedState(e.target.value)}
          >
            <option value="">Select State</option>
            {states.map((s, i) => (
              <option key={i} value={s}>{s}</option>
            ))}
          </select>

          {/* ADDRESS */}
          <input
            className="kyc-input"
            placeholder="Street address"
            value={address}
            onChange={(e) => setAddress(e.target.value)}
          />
          <input
            className="kyc-input"
            placeholder="City"
            value={city}
            onChange={(e) => setCity(e.target.value)}
          />
          <input
            className="kyc-input"
            placeholder="Postal code"
            value={postalCode}
            onChange={(e) => setPostalCode(e.target.value)}
          />

          {/* TERMS */}
          <p className="terms-text">
            By submitting, you agree to our{" "}
            <a href="https://swapeki.com/terms-and-conditions/">
              Terms of Service
            </a>
          </p>

          {/* SUBMIT */}
          <IonButton expand="block" className="submit-btn" onClick={submitKYC}>
            Submit KYC
          </IonButton>
        </>
      )}
    </IonCardContent>
  </IonCard>
)}

    {userInfo?.id_verified === 1 && (
     <>
      <div className="ion-text-center ion-padding">
       <IonIcon
        style={{ fontSize: "100px" }}
        color="success"
        icon={checkmarkCircle}
       ></IonIcon>

       <p>
        {userInfo.first_name.toUpperCase()}, you are all done for now. We will
        let you know if we need any additional information from you.
       </p>
      </div>
     </>
    )}
    {userInfo?.id_verified === 2 && (
     <>
      <div className="ion-text-center ion-padding">
       <IonIcon
        style={{ fontSize: "100px" }}
        color="warning"
        icon={alertCircle}
       ></IonIcon>

       <p>
        {userInfo.first_name.toUpperCase()}, your ID documents are currently
        under review. We will let you know about the status as soon as the
        review is completed.
       </p>
      </div>
     </>
    )}
   </AppShell>
  </IonPage>
 );
};

export default KYC;
