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

export const unstable_settings = {
  initialRouteName: 'login',
};

function AppTest() {
  const [ oldMessage, setOldMessage ] = useState(1);
  const { lastMessage } = useWebSocketContext();
  const { schedulePushNotification } = useNotifications();
  
  useEffect(() => {
    router.replace('/login');
  }, []);

  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={{
        headerShown: false
      }}
    >
      <Stack.Screen name="login" />
    </Stack>
  )
}

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