import React, { useState, useEffect } from 'react';
import { useNavigation } from '@react-navigation/native';
import { NativeStackNavigationProp } from '@react-navigation/native-stack';
import { useAccounts } from '../context/AccountsContext';
import { useNetworks } from '../context/NetworksContext';
import { StackParamsList } from '../types';
import useGetOrCreateAccounts from '../hooks/useGetOrCreateAccounts';

declare global {
    interface Window {
        receiveSignRequestFromAndroid?: (message: string) => void;
    }
}

export const SignRequestHandler: React.FC = () => {
  const navigation = useNavigation<NativeStackNavigationProp<StackParamsList>>();
  const { accounts, currentIndex } = useAccounts();
  const { selectedNetwork } = useNetworks();
  const [pendingMessage, setPendingMessage] = useState<string | null>(null);

  useGetOrCreateAccounts();

  useEffect(() => {
    if (pendingMessage && selectedNetwork && accounts && accounts.length > 0) {
      navigation.reset({
        index: 0,
        routes: [
          {
            name: 'SignRequest',
            params: {
              address: accounts[currentIndex].address,
              message: pendingMessage,
              requestEvent: null, 
              path: `/sign/${selectedNetwork.namespace}/${selectedNetwork.chainId}/${accounts[currentIndex].address}/${encodeURIComponent(pendingMessage)}`
            }
          }
        ]
      });
      setPendingMessage(null);
    }
  }, [pendingMessage, selectedNetwork, accounts, currentIndex, navigation]);

  useEffect(() => {        
    window.receiveSignRequestFromAndroid = (message: string) => {
      if (!selectedNetwork || !accounts || accounts.length === 0) {
        // Store the message and wait for wallet creation
        setPendingMessage(message);
        return;
      }

      navigation.reset({
        index: 0,
        routes: [
          {
            name: 'SignRequest',
            params: {
              address: accounts[currentIndex].address,
              message: message,
              requestEvent: null,
              path: `/sign/${selectedNetwork.namespace}/${selectedNetwork.chainId}/${accounts[currentIndex].address}/${encodeURIComponent(message)}`
            }
          }
        ]
      });
    };

    return () => {
      if ('receiveSignRequestFromAndroid' in window) {
        window.receiveSignRequestFromAndroid = undefined;
      }
    };
  }, [navigation, accounts, currentIndex, selectedNetwork]);

  return null;
};