import React, { createContext, useEffect, useState, ReactNode } from "react";
import { Storage } from "@ionic/storage";
import { useIonToast, useIonRouter } from "@ionic/react";
import { alertCircle, checkmarkCircle } from "ionicons/icons";
import axios from "axios";

interface ContextProps {
 validUser: boolean;
 userInfo: userInfoProps | null;
 getUserInfo: () => void;
 getSettings: () => void;
 setValidUser: (val: boolean) => void;
 copy: (text: any) => void;
 apiURL: string;
 settings: settingsProps | null;
 storage: Storage | null;
 presentToast: any;
 vtpassBase: string;
 vtpassApiKey: string;
 vtpassPubKey: string;
 vtpBalance: string;
 transactions: any[];
 getTransactions: () => void;
 busy: boolean;
 setBusy: (val: boolean) => void;
 reportLowBalance: (amount: number, platform: string, balance: number) => void;
 userWallets: any[];
 userWalletsGroup: any[];
 quidaxBalance: number;
 getUserWallets: (id: number) => void;
 getUserWalletsGroup: (id: number) => void;
 logOut: () => void;
 auth: boolean;
 setAuth: (val: boolean) => void;
 unreadAlerts: number;
 abr: string;
  apiRequest: (
  method: "GET" | "POST",
  url: string,
  data: any,
  requireAuth: boolean,
  showMsg: boolean,
load?: boolean
) => void;
}

interface userInfoProps {
 id: number;
 email: string;
 phone: string;
 username: string | null;
 first_name: string;
 last_name: string;
 // "password": "$2y$10$vC7h5uoENSqc.P/5JMSYNeOIvvE0fpAfJceQ/iqjqsI9rw1mdAREO",
 ngn_balance: string;
 usd_balance: string;
 eur_balance: string;
 is_admin: number;
 is_banned: number;
 email_verified: number;
 id_verified: number;
 withdrawal_bank_name: string | null;
 withdrawal_bank_code: string | null;
 withdrawal_bank_account: string | null;
 withdrawal_bank: string | null;
 photo: string | null;
 nin: string | null;
 bvn: string | null;
 tx_pin: string | null;
 card_holder_id: string | null;
 reg_date: number;
 country: string;
 state: string;
 city: string;
 dob: string;
 address: string;
 id_photo: string;
 postal_code: string;
 id_type: string;
 id_number: string;
 [key: string]: any;
 login_token: string | null;
 login_expiry: number | string;
 show_bal: number;
kyc: number;
}

interface settingsProps {
 quidax_sell_rate: number;
 quidax_buy_rate: number;
 //card_deposit_pcnt: number;
 //card_deposit_cap: number;
 ngn_bank_deposit_fee: number;
 //ngn_bank_deposit_cap: number;
 admin_email: string;
 smtp_host: string;
 smtp_email: string;
 smtp_password: string;
 app_name: string;
 //local_transfer_fee: number;
 //withdrawal_fee: number;
 //usd_buy_rate: number | 0;
 //usd_sell_rate: number | 0;
 //visa_card_creation_fee: number;
 domain: string;
 //card_withdrawal_fee: string;
 //card_funding_fee: string;
 vtp_base: string;
 vtp_api: string;
 vtp_pub: string;
 api_url: string;
 contact_email: string;
 contact_phone: string | number;
 contact_address: string;
 facebook: string | null;
 x: string | null;
 instagram: string | null;
 youtube: string | null;
 whatsapp: string | null;
  enable_topup: number;
 enable_bills: number;
 enable_giftcard: number;
 enable_crypto: number;
 //enable_banking: number;
 ref_bonus: number;
 ref_spend: number;
 cashback_rules: any
}

interface ContextProviderProps {
 children: ReactNode;
}

export const Context = createContext<ContextProps | null>(null);

export const ContextProvider: React.FC<ContextProviderProps> = ({
 children,
}) => {
 const [settings, setSettings] = useState<settingsProps | null>(null);
 const [auth, setAuth] = useState<boolean>(false);
 const [unreadAlerts, setUnreadAlerts] = useState<number>(0);

 const [vtpBalance, setVtpBalance] = useState<string>("");
 const router = useIonRouter();

 const [validUser, setValidUser] = useState<boolean>(true);
 const [userInfo, setUserInfo] = useState<userInfoProps | null>(null);
 const [transactions, setTransactions] = useState<any[]>([]);
 const [busy, setBusy] = useState(false);
 const [userWallets, setUserWallets] = useState([]);
 const [userWalletsGroup, setUserWalletsGroup] = useState([]);
 const [quidaxBalance, setQuidaxBalance] = useState(0);
 const [storageReady, setStorageReady] = useState(false);
const abr = 'swpk';
 const [vtpassBase, setVtpassBase] = useState("https://vtpass.com/api/");
 const [vtpassApiKey, setVtpassApiKey] = useState(
  "09e3f274b5553a71d0c043323747880a"
 );
 const [vtpassPubKey, setVtpassPubKey] = useState(
  "PK_4866d69c3755685c57a31970f5653936abee7176bf7"
 );
 const [apiURL, setApiURL] = useState("https://app.swapeki.com/api.php");
 const [storage, setStorage] = useState<Storage | null>(null);
 const [present] = useIonToast();

 //const vtpassBase = "https://api-service.vtpass.com/api/";

useEffect(() => {
  const initStorage = async () => {
    const storageInstance = new Storage();
    await storageInstance.create();
    setStorage(storageInstance);
    setStorageReady(true);
  };

  initStorage();
}, []);

 useEffect(() => {
  if (!settings) return;
  setVtpassApiKey(settings?.vtp_api);
  setVtpassBase(settings?.vtp_base);
  setVtpassPubKey(settings?.vtp_pub);
  setApiURL(settings?.api_url);
 }, [settings]);

 async function apiRequest(
  method: "GET" | "POST",
  url: string = '',
  data: any = null,
  requireAuth: boolean = true,
  showMsg: boolean = true,
  load: boolean = true
) {
if(load){
 setBusy(true);
}
  try {

    let token: string | null = null;

    // -------------------------------
    // Load token only if required
    // -------------------------------
    if (requireAuth) {
      if ((!storage || !storageReady)) {
  console.log("Storage not ready");
  setBusy(false);

  return null;
}
      token = await storage?.get(abr+"_auth_token");
//console.log("TOKEN:", token);

      if (!token) {
        if (showMsg) {
          presentToast(
            "top",
            "Invalid user or login session expired.",
            () => null,
            "danger",
            alertCircle
          );
        }

  setBusy(false);
setValidUser(false);
setUserInfo(null);
        return null;
      }
    }

    // -------------------------------
    // Axios request config
    // -------------------------------
    const config: any = {
      method,
      url,
      baseURL: apiURL,
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
        ...(token && { Authorization: `Bearer ${token}` }),
      },
    };

    // Attach body for POST requests
    if (method === "POST") {
      config.data = new URLSearchParams(data);
    }

    // Execute API call
    const response = await axios(config);
    const res = response.data;

    // -------------------------------
    // HANDLE RESPONSE
    // -------------------------------
  //console.log("ERROR", res);
    if (!res?.success || res?.error) {
      if (showMsg) {
        presentToast(
          "top",
          res.message || res.error || "An unknown error occurred.",
          () => null,
          "danger",
          alertCircle
        );
      }
    
  setBusy(false);

      return null;
    }

    // SUCCESS
    if (showMsg && res?.message) {
      presentToast(
        "top",
        res?.message,
        () => null,
        "success",
        checkmarkCircle
      );
    }
  setBusy(false);

    return res;

  } catch (err: any) {
    // -------------------------------
    // Handle unauthorized response
    // -------------------------------
    if (requireAuth && err?.response?.status === 401) {
      if (userInfo){ 
        setUserInfo(null);
        setValidUser(false);
    }
  setBusy(false);

      return null;
    }

    const msg = err?.response?.data?.message || "Network error";

    if (showMsg) {
      presentToast("top", msg, () => null, "danger", alertCircle);
    }

   // console.log("API ERROR:", msg);
  setBusy(false);

    return { success: false, error: msg };
  }
}


  const getUreadAlerts = async () => {
  if (!userInfo || !storage) return;
const res = await apiRequest(
  "POST",
  "", //url
  {
    action: "get_unread_notifications",
     email: userInfo.email,
  },
  false,       // require auth
  false,       // show success or error messages
  false //Loading
);

if(res?.success) {
    setUnreadAlerts(res.unread);
   // console.log("Fetched stat:", res);
   }

 };

 useEffect(() => {
  if (!userInfo) return;
  let isRunning = false;

  const fetchAlerts = async () => {
   if (isRunning) return; // skip if still fetching
   isRunning = true;
   await getUreadAlerts();
   isRunning = false;
  };

  fetchAlerts();
  const interval = setInterval(fetchAlerts, 30000);
  return () => clearInterval(interval);
 }, [userInfo, storage]);

 const getQuidaxBalance = async () => {
  if(!storage || !userInfo) return;
  const res = await apiRequest(
  "POST",
  "", //url
  {
    action: "get_quidax_admin_wallet",
   
  },
  true,       // require auth
  false,     // show success or error messages
  false //Loading

);
//console.log("RES", res);
  if (!res?.success) {
    console.error("Error:", res?.message);
   } else {
    setQuidaxBalance(res?.message.balance);
   }

 };

 useEffect(() => {
  getQuidaxBalance();
 }, [storage, userInfo]);

 const getUserWallets = async () => {
  if(!storage || !userInfo) return;
    const res = await apiRequest(
  "POST",
  "", //url
  {
    action: "get_user_wallets",
   
  },
  true,       // require auth
  false,       // show success or error messages
  false //Loading

);
  if (!res?.success) {
    console.error("Error:", res?.message);
   } else {
    setUserWallets(res?.message);
   // console.log("UWA", res.message)
   }

 };

 const getUserWalletsGroup = async () => {
  if(!storage || !userInfo) return;
    const data = await apiRequest(
  "POST",
  "", //url
  {
    action: "get_grouped_user_wallets",
   
  },
  true,       // require auth
  false,      // show success or error messages
  false //Loading

);
 if (!data?.success) {
    console.error("Error:", data?.message);
   } else {
   // console.log("WALLET", data.message)
    setUserWalletsGroup(data?.message);
   }

 };

 useEffect(() => {
  if (!userInfo || userInfo?.quidax_id === null) return;
  getUserWalletsGroup();
 }, [userInfo, storage]);

 useEffect(() => {
  if (!userInfo || userInfo?.quidax_id === null) return;
  getUserWallets();
 }, [userInfo, storage]);


 const getVtpBalance = async () => {
    const response = await apiRequest(
  "POST",
  "", //url
  {
    action: "get_vtp_balance",
   
  },
  false,       // require auth
  false,      // show success or error messages
  false //Loading

);
   if (!response?.success) {
    console.error("Error:", response?.message);
   } else {
    setVtpBalance(response?.data);
   }

 };

 useEffect(() => {
  getVtpBalance();
 }, []);



 const getSettings = async () => {
    const data = await apiRequest(
  "POST",
  "", //url
  {
    action: "get_settings",
   
  },
  false,       // require auth
  false       // show success or error messages
);
 //console.log('SE',data);

    setSettings(data?.data);
   

 };

 const getUserInfo = async () => {
  const token = await storage?.get(abr+"_auth_token");

  if (!token) {
   setValidUser(false);
   setUserInfo(null);
   return false;
  }

  try {
   const response = await fetch(apiURL, {
    method: "POST",
    headers: {
     "Content-Type": "application/x-www-form-urlencoded",
     Authorization: `Bearer ${token}`,
    },
    body: new URLSearchParams({
     action: "get_user_info",
    }),
   });

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

   const data = await response.json();

   if (data.error) {
    console.warn("Session invalid:", data.error);
    //await logOut();
    return false;
   } else {
    setUserInfo(data[0]);
    setValidUser(true);
   }
  } catch (error: any) {
   console.error("Error:", error?.message);
  }
 };


 useEffect(() => {
  const checkExpiry = async () => {
   const expiry = await storage?.get(abr+"_token_expiry");
   if (expiry && Date.now() / 1000 > expiry) {
    // await logOut();
   } else {
    getUserInfo();
   }
  };

  checkExpiry();
 }, [storage]);

 const getTransactions = async () => {
  if (userInfo === null) return;
  try {
   const response = await fetch(apiURL, {
    method: "POST",
    headers: {
     "Content-Type": "application/x-www-form-urlencoded",
    },
    body: new URLSearchParams({
     action: "get_transactions",
     email: userInfo?.email,
    }),
   });

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

   const data = await response.json();
   if (data.error) {
    console.error("Error:", data.error);
   } else {
    setTransactions(data);

   }
  } catch (error: any) {
   console.error("Error:", error?.message);
  }
 };

 useEffect(() => {
  getTransactions();
 }, [userInfo, storage]);

 const presentToast = (
  position: "top" | "middle" | "bottom",
  message: string,
  func: () => void, // Change React.FC to () => void
  color: string,
  icon: string,
  duration: number = 6000
 ) => {
  present({
   message: message,
   position: position,
   onDidDismiss: func, // Pass func directly without calling it
   color: color, // Changed className to cssClass
   icon: icon,
   duration: duration,
  });
 };

 useEffect(() => {
  getSettings();
 }, []);

 const logOut = async () => {
  await storage?.clear();
  setValidUser(false);
setUserInfo(null);
  window.location.replace("login");
 };
//logOut();
 const copy = (text: any) => {
  if (text) {
   if (navigator.clipboard && navigator.clipboard.writeText) {
    navigator.clipboard.writeText(text).then(
     () => {
      presentToast(
       "top",
       `Copied to clipboard`,
       () => null,
       "success",
       checkmarkCircle
      );
     },
     (err) => {
      presentToast(
       "top",
       `Could not copy text: ${err}`,
       () => null,
       "danger",
       alertCircle
      );
     }
    );
   } else {
    // Fallback method for older browsers
    const textArea = document.createElement("textarea");
    textArea.value = text;
    document.body.appendChild(textArea);
    textArea.focus();
    textArea.select();
    try {
     document.execCommand("copy");
     presentToast(
      "top",
      `Copied to clipboard`,
      () => null,
      "success",
      checkmarkCircle
     );
    } catch (err) {
     presentToast(
      "top",
      `Could not copy text: ${err}`,
      () => null,
      "danger",
      alertCircle
     );
    }
    document.body.removeChild(textArea);
   }
  }
 };

 const reportLowBalance = async (
  amount: number,
  platform: string,
  balance: number = 0
 ) => {
  if (!userInfo) {
   return;
  }
   const data = await apiRequest(
  "POST",
  "", //url
  {
   action: "report_low_balance",
     balance: balance.toString(),
     amount: amount.toString(),
     platform,
     userEmail: userInfo?.email,
  },
  false,       // require auth
  false       // show success or error messages
);
 
  return true;
 };

 return (
  <Context.Provider
   value={{
    validUser,
    userInfo,
    apiURL,
    settings,
    storage,
    presentToast,
    vtpassApiKey,
    vtpassBase,
    vtpassPubKey,
    vtpBalance,
    getUserInfo,
    getTransactions,
    transactions,
    copy,
    busy,
    setBusy,
    reportLowBalance,
    userWallets,
    userWalletsGroup,
    quidaxBalance,
    getUserWallets,
    getUserWalletsGroup,
    logOut,
    auth,
    setAuth,
    getSettings,
    setValidUser,
    unreadAlerts,
    apiRequest,
    abr
   }}
  >
   {children}
  </Context.Provider>
 );
};
