import React, { useEffect } from 'react'

export const WalletEmbed = () => {
  useEffect(() => {
    const handleGetAccounts = (event: MessageEvent) => {
      if (event.data.type === 'REQUEST_WALLET_ACCOUNTS') {
        try {
          let accountsData = '';
          const indices = localStorage.getItem(`addAccountCounter/cosmos:${event.data.chainId}`);
          for (let i = 0; i < Number(indices); i++) {
            const account = localStorage.getItem(`accounts/cosmos:${event.data.chainId}/${i}`);
            if (account) {
              accountsData += `${account},`;
            }
          }

          // Remove trailing comma
          accountsData = accountsData.slice(0, -1);

          if (!accountsData) {
            event.source?.postMessage({
              type: 'ERROR',
              message: 'Wallet accounts not found in local storage',
            });
            return;
          }

          const elements = accountsData.split(',');
          const addresses = elements.filter((_, index) => (index + 1) % 4 === 0);

          (event.source as Window)?.postMessage(
            {
              type: 'WALLET_ACCOUNTS_DATA',
              data: addresses,
            },
            event.origin
          );

        } catch (error) {
          (event.source as Window)?.postMessage({
            type: 'ERROR',
            message: 'Error accessing wallet accounts data'
          }, event.origin);
        }
      }
    };

    window.addEventListener('message', handleGetAccounts);

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

  useEffect(() => {
    const handleCreateAccounts = (event: MessageEvent) => {
      if (event.data.type === 'REQUEST_CREATE_OR_GET_ACCOUNTS') {
        try {
          console.log("Create Accounts request received:", event.data);
          let accountsData = '';
          console.log("chainId", event.data.chainId);
          console.log("ls: \n", localStorage);
          const indices = localStorage.getItem(`addAccountCounter/cosmos:laconic-testnet-2`);
          if (indices) {
            for (let i = 0; i < Number(indices); i++) {
              const account = localStorage.getItem(`accounts/cosmos:${event.data.chainId}/${i}`);
              console.log("Account found", account);
              if (account) {
                accountsData += `${account},`;
              }
            }
          }
          // Remove trailing comma
          accountsData = accountsData.slice(0, -1);

          if (!accountsData) {
            event.source?.postMessage({
              type: 'ERROR',
              message: 'Wallet accounts not found in local storage',
            });
            return;
          }

          const elements = accountsData.split(',');
          const addresses = elements.filter((_, index) => (index + 1) % 4 === 0);  // Process the accounts as required

          console.log('Accounts Data:', addresses);  // Log processed accounts data

          // Send the accounts data back to the origin
          (event.source as Window)?.postMessage(
            {
              type: 'WALLET_ACCOUNTS_DATA',
              data: addresses,
            },
            event.origin
          );

        } catch (error) {
          console.error('Error handling account creation:', error);  // Log error
          (event.source as Window)?.postMessage({
            type: 'ERROR',
            message: 'Error accessing or creating wallet accounts data'
          }, event.origin);
        }
      }
    };

    window.addEventListener('message', handleCreateAccounts);

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

  return (
    <div>
      <p style={{ color: 'white' }}>Text</p>
    </div>
  );
};
