import { Stack, router } from 'expo-router';
import { useEffect } from 'react';
import { StatusBar } from 'expo-status-bar';
import { initOfflineQueue, flushQueue } from '../src/offlineQueue';
import { getSession } from '../src/session';
import { addNotificationListeners, registerForPushNotifications } from '../src/notifications';

export default function RootLayout() {
  useEffect(() => {
    let timer: ReturnType<typeof setInterval> | undefined;
    let disposed = false;

    initOfflineQueue().then(async () => {
      const session = await getSession();
      if (session && !disposed) {
        await flushQueue(session.accessToken);
        await registerForPushNotifications();
      }
      timer = setInterval(async () => {
        const current = await getSession();
        if (current) await flushQueue(current.accessToken);
      }, 30_000);
    });

    const removeNotificationListeners = addNotificationListeners({
      onResponse: response => {
        const ticketId = response.notification.request.content.data?.ticketId;
        if (typeof ticketId === 'string' && ticketId.length > 0) {
          router.push(`/ticket/${ticketId}`);
        }
      },
    });

    return () => {
      disposed = true;
      if (timer) clearInterval(timer);
      removeNotificationListeners();
    };
  }, []);

  return (
    <>
      <StatusBar style="dark" />
      <Stack screenOptions={{ headerStyle: { backgroundColor: '#fff' }, headerTintColor: '#12304A', headerTitleStyle: { fontWeight: '700' } }}>
        <Stack.Screen name="index" options={{ headerShown: false }} />
        <Stack.Screen name="login" options={{ headerShown: false }} />
        <Stack.Screen name="change-password" options={{ title: 'Password security' }} />
        <Stack.Screen name="(tabs)" options={{ headerShown: false }} />
        <Stack.Screen name="ticket/[id]" options={{ title: 'Service Ticket' }} />
        <Stack.Screen name="execute/[id]" options={{ title: 'Service Report' }} />
      </Stack>
    </>
  );
}
