import React, { useState, useEffect } from 'react';
import { router, Stack } from 'expo-router';
import { AuthProvider, GlobalVariablesProvider, WebSocketProvider } from '@/contexts';
import { useNotifications, useWebSocketContext } from '@/hooks';
import { useAuth } from '@/contexts/AuthContext';

function AppTest() {
  const [ oldMessage, setOldMessage ] = useState(1);
  const { user } = useAuth();
  const { lastMessage } = useWebSocketContext();
  const { schedulePushNotification } = useNotifications();
  const [isReady, setIsReady] = useState(false);

  useEffect(() => {
    setIsReady(true);
  }, []);
  
  useEffect(() => {
    if (isReady) {
      if (user) {
        router.replace('./incidents');
      } else {
        router.replace('/login');
      }
    }
  }, [isReady, user]);

  const parseAddress = (data) => {
    const { Address }  = data;
    const { StreetAddress, AddressApartment, Town, State } = Address;
    const response = `${StreetAddress}${AddressApartment ? ` - ${AddressApartment}` : ''} ${Town}, ${State}`
    return response;
  }

  useEffect(() => {
    if (lastMessage) {
      const parsedMessage = JSON?.parse(lastMessage);
      if (parsedMessage?.data && new Date(oldMessage)?.getTime() < new Date(parsedMessage?.timestamp)?.getTime()) {
        setOldMessage(new Date(parsedMessage?.timestamp)?.getTime());
        schedulePushNotification(
          `${parsedMessage?.data?.Response?.ServiceName} - ${parsedMessage?.data?.Incident?.IncNatureCode}`,
          `${parsedMessage?.data?.Incident?.IncNature}\n${parseAddress(parsedMessage?.data)}`,
          parsedMessage?.data
        );
      }
    }
  }, [lastMessage]);

  return (
    <Stack
      screenOptions={{
        gestureEnabled: false,
        headerBackVisible: false,
        headerShown: false
      }}
    />
  )
}

export default function App() {
  return (
    <GlobalVariablesProvider>
      <WebSocketProvider>
        <AuthProvider>
          <AppTest />
        </AuthProvider>
      </WebSocketProvider>
    </GlobalVariablesProvider>
  );
}