import { useEffect, useState } from 'react';

import { Modal } from '@mui/material';

import { VITE_WALLET_IFRAME_URL } from 'utils/constants';
import useCheckBalance from '../../../hooks/useCheckBalance';

const CHECK_BALANCE_INTERVAL = 5000;
const IFRAME_ID = 'checkBalanceIframe';

const CheckBalanceIframe = ({
  onBalanceChange,
  isPollingEnabled,
  amount,
}: {
  onBalanceChange: (value: boolean | undefined) => void;
  isPollingEnabled: boolean;
  amount: string;
}) => {
  const { isBalanceSufficient, checkBalance } = useCheckBalance(
    amount,
    IFRAME_ID,
  );

  const [isLoaded, setIsLoaded] = useState(false);

  useEffect(() => {
    if (!isLoaded) {
      return;
    }
    checkBalance();
  }, [amount, checkBalance, isLoaded]);

  useEffect(() => {
    if (!isPollingEnabled || !isLoaded || isBalanceSufficient) {
      return;
    }

    const interval = setInterval(() => {
      checkBalance();
    }, CHECK_BALANCE_INTERVAL);

    return () => {
      clearInterval(interval);
    };
  }, [isBalanceSufficient, isPollingEnabled, checkBalance, isLoaded]);

  useEffect(() => {
    onBalanceChange(isBalanceSufficient);
  }, [isBalanceSufficient]);

  return (
    <Modal open={false} disableEscapeKeyDown keepMounted>
      <iframe
        onLoad={() => setIsLoaded(true)}
        id={IFRAME_ID}
        src={VITE_WALLET_IFRAME_URL}
        width="100%"
        height="100%"
        sandbox="allow-scripts allow-same-origin"
        className="border rounded-md shadow-sm"
      />
    </Modal>
  );
};

export default CheckBalanceIframe;
