import { useState, useEffect, useCallback } from 'react';

import { useAddNetwork } from './useAddNetwork';

const useCheckBalance = (amount: string, iframeId: string) => {
  const [isBalanceSufficient, setIsBalanceSufficient] = useState<boolean>();

  const { networkData } = useAddNetwork()

  const checkBalance = useCallback(() => {
    if (!networkData) {
      return;
    }

    const iframe = document.getElementById(iframeId) as HTMLIFrameElement;

    if (!iframe || !iframe.contentWindow) {
      console.error(`Iframe with ID "${iframeId}" not found or not loaded`);
      return;
    }

    iframe.contentWindow.postMessage(
      {
        type: 'CHECK_BALANCE',
        chainId: networkData.chainId,
        amount,
      },
      import.meta.env.VITE_WALLET_IFRAME_URL
    );
  }, [iframeId, amount, networkData]);

  useEffect(() => {
    const handleMessage = (event: MessageEvent) => {
      if (event.origin !== import.meta.env.VITE_WALLET_IFRAME_URL) return;

      if (event.data.type !== 'IS_SUFFICIENT') return;

      setIsBalanceSufficient(event.data.data);
    };

    window.addEventListener('message', handleMessage);
    return () => {
      window.removeEventListener('message', handleMessage);
    };
  }, []);

  return { isBalanceSufficient, checkBalance };
};

export default useCheckBalance;
