import { useCallback, useEffect } from 'react';

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

import {
  VITE_WALLET_IFRAME_URL,
} from 'utils/constants';
import { REQUEST_WALLET_ACCOUNTS, WALLET_ACCOUNTS_DATA } from '../../../constants';
import { useAddNetwork } from '../../../hooks/useAddNetwork';

const ApproveTransactionModal = ({
  setAccount,
  setIsDataReceived,
  isVisible,
}: {
  setAccount: (account: string) => void;
  setIsDataReceived: (isReceived: boolean) => void;
  isVisible: boolean;
}) => {
  const { setIframe, isNetworkAvailable, networkData } = useAddNetwork();

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

      if (event.data.type === WALLET_ACCOUNTS_DATA) {
        setIsDataReceived(true);

        if (event.data.data.length === 0) {
          console.error(`Accounts not present for chainId: ${networkData?.chainId}`);
          return;
        }

        setAccount(event.data.data[0]);
      }

      if (event.data.type === 'ERROR') {
        console.error('Error from wallet:', event.data.message);
      }
    };

    window.addEventListener('message', handleMessage);

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

  const getDataFromWallet = useCallback(() => {
    if (!networkData) {
      console.error('networkData should not be empty');
      return;
    }

    const iframe = document.getElementById('walletIframe') as HTMLIFrameElement;

    if (!iframe.contentWindow) {
      console.error('Iframe not found or not loaded');
      return;
    }

    iframe.contentWindow.postMessage(
      {
        type: REQUEST_WALLET_ACCOUNTS,
        chainId: networkData.chainId,
      },
      VITE_WALLET_IFRAME_URL,
    );
  }, [networkData]);

  useEffect(() => {
    if (isNetworkAvailable) {
      getDataFromWallet();
    }
  }, [isNetworkAvailable, getDataFromWallet])

  return (
    <Modal open={isVisible} disableEscapeKeyDown keepMounted>
      <Box
        sx={{
          position: 'absolute',
          top: '50%',
          left: '50%',
          transform: 'translate(-50%, -50%)',
          width: '90%',
          maxWidth: '1200px',
          height: '600px',
          maxHeight: '80vh',
          overflow: 'auto',
          boxShadow: 24,
          borderRadius: '8px',
          outline: 'none',
          bgcolor: 'background.paper',
        }}
      >
        <iframe
          onLoad={(event) => setIframe(event.target as HTMLIFrameElement)}
          id="walletIframe"
          src={`${VITE_WALLET_IFRAME_URL}/wallet-embed`}
          width="100%"
          height="100%"
          sandbox="allow-scripts allow-same-origin"
          className="border rounded-md shadow-sm"
        ></iframe>
      </Box>
    </Modal>
  );
};

export default ApproveTransactionModal;
