import { useCallback, useEffect } from 'react';

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

import {
  BASE_URL,
  VITE_WALLET_IFRAME_URL,
} from 'utils/constants';
import { generateNonce, SiweMessage } from 'siwe';
import axios from 'axios';
import { useNavigate } from 'react-router-dom';

const axiosInstance = axios.create({
  baseURL: BASE_URL,
  headers: {
    'Content-Type': 'application/json',
    'Access-Control-Allow-Origin': '*',
  },
  withCredentials: true,
});

const AutoSignInIFrameModal = (
//   {
//   setAccounts,
//   setIsDataReceived,
//   isVisible,
// }: {
//   setAccounts: (accounts: string[]) => void;
//   setIsDataReceived: (isReceived: boolean) => void;
//   isVisible: boolean;
// }
) => {
  const navigate = useNavigate();
  useEffect(() => {
    const handleMessage = async (event: MessageEvent) => {
      if (event.origin !== VITE_WALLET_IFRAME_URL) return;

      // setIsDataReceived(true);
      if (event.data.type === 'SIGN_IN_RESPONSE') {
        try {
          const { success } = (
            await axiosInstance.post('/auth/validate', {
              message: event.data.data.message,
              signature: event.data.data.signature,
            })
          ).data;

          if(success) {
            navigate("/")
          }
          return success;
        } catch (error) {
          return false;
        }
        // setAccounts(event.data.data);
      } else if (event.data.type === 'ERROR') {
        console.error('Error from wallet:', event.data.message);
      }
    };

    window.addEventListener('message', handleMessage);

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

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

      if (event.data.type === 'ACCOUNT_ADDRESS_RESPONSE') {
        const iframe = document.getElementById('autoSignInFrame') as HTMLIFrameElement;

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

        const message = new SiweMessage({
          version: '1',
          domain: window.location.host,
          uri: window.location.origin,
          chainId: 1,
          address: event.data.data,
          nonce: generateNonce(),
          // Human-readable ASCII assertion that the user will sign, and it must not contain `\n`.
          statement: 'Sign in With Ethereum.',
        }).prepareMessage()

        iframe.contentWindow.postMessage(
          {
            type: 'AUTO_SIGN_IN',
            chainId: '1',
            message,
          },
          VITE_WALLET_IFRAME_URL,
        );

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

    window.addEventListener('message', handleInitiateAutoSignIn);

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

  // /////////////////////////////////////////////////
  const getAddressFromWallet = useCallback(() => {
    const iframe = document.getElementById('autoSignInFrame') as HTMLIFrameElement;

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

    iframe.contentWindow.postMessage(
      {
        type: 'GET_ACCOUNT_ADDRESS',
        chainId: '1',
      },
      VITE_WALLET_IFRAME_URL,
    );
  }, []);

  return (
    <Modal open={true} 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={getAddressFromWallet}
          id="autoSignInFrame"
          src={`${VITE_WALLET_IFRAME_URL}/auto-sign-in`}
          width="100%"
          height="100%"
          sandbox="allow-scripts allow-same-origin"
          className="border rounded-md shadow-sm"
        ></iframe>
      </Box>
    </Modal>
  );
};

export default AutoSignInIFrameModal;
