import React, { createContext, useContext, useState, useEffect } from "react";

interface CryptoBalanceContextType {
  cryptoBalance: any;
  loading: boolean;
  setLoading: (loading: boolean) => void;
  refreshBalance: (showLoading?: boolean) => Promise<void>;
  showActivity: boolean;
  setShowActivity: (showActivity: boolean) => void;
  activity: any;
  setActivity: (activity: any) => void;
}

const CryptoBalanceContext = createContext<
  CryptoBalanceContextType | undefined
>(undefined);

export const CryptoBalanceProvider: React.FC<{
  children: React.ReactNode;
  walletSDKKey: string;
}> = ({ children, walletSDKKey }) => {
  const [cryptoBalance, setCryptoBalance] = useState<any>(null);
  const [loading, setLoading] = useState(false);
  const [showActivity, setShowActivity] = useState(false);
  const [activity, setActivity] = useState<any>(null);

  const refreshBalance = async (showLoading: boolean = false) => {
    console.log("show loading", showLoading);
    try {
      if (showLoading) {
        setLoading(true);
      }
      const sdkInstance = (window as any).__walletSDKInstance;
      if (sdkInstance) {
        const balance = await sdkInstance.getUserCryptoBalance();
        setCryptoBalance(balance);
      }
    } catch (error) {
      console.error("Error fetching balance:", error);
    } finally {
      setLoading(false);
    }
  };

  // Listen for storage changes to trigger balance refresh
  useEffect(() => {
    const handleStorageChange = (e: StorageEvent) => {
      if (e.key === "enclave_wallet_login") {
        if (e.newValue) {
          refreshBalance(true);
        } else {
          setCryptoBalance(null);
        }
      }
    };

    window.addEventListener("storage", handleStorageChange);
    return () => window.removeEventListener("storage", handleStorageChange);
  }, []);

  // Initial load
  useEffect(() => {
    const userSession = localStorage.getItem("enclave_wallet_login");
    if (userSession) {
      refreshBalance(true); // Show loading on initial load
    }
  }, [walletSDKKey]);

  // Polling effect
  useEffect(() => {
    const userSession = localStorage.getItem("enclave_wallet_login");
    if (!userSession) return;

    const pollInterval = setInterval(() => {
      refreshBalance(false); // Don't show loading during polling
    }, 5000);

    return () => clearInterval(pollInterval);
  }, [walletSDKKey]);

  return (
    <CryptoBalanceContext.Provider
      value={{
        cryptoBalance,
        loading,
        refreshBalance,
        showActivity,
        setShowActivity,
        activity,
        setActivity,
        setLoading,
      }}
    >
      {children}
    </CryptoBalanceContext.Provider>
  );
};

export const useCryptoBalance = () => {
  const context = useContext(CryptoBalanceContext);
  if (context === undefined) {
    throw new Error(
      "useCryptoBalance must be used within a CryptoBalanceProvider"
    );
  }
  return context;
};
