import { AuthProvider } from '@/components/auth/auth-provider';
import Header from '@/components/Header';
import AppSidebar from '@/components/sidebar/app-sidebar';
import { SidebarInset, SidebarProvider } from '@/components/ui/sidebar';
import { useSSE } from '@/hooks/use-sse';
import useNotificationStore from '@/store/useNotificationStore';
import { Locale, setLocale } from '@paraglide/runtime';
import { notificationQueries, settingQueries } from '@service/queries';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { createFileRoute, Outlet } from '@tanstack/react-router';
import { useEffect } from 'react';

export const Route = createFileRoute('/(app)')({
  component: RouteComponent,
});

function RouteComponent() {
  const setHasNew = useNotificationStore((state) => state.setHasNew);
  const { data: language } = useQuery(
    settingQueries.getCurrentUserLanguageSetting(),
  );
  const queryClient = useQueryClient();

  useSSE((data) => {
    if (data.type === 'NEW_NOTIFICATION') {
      setHasNew(true);
      queryClient.invalidateQueries(notificationQueries.topFive());
    }
  });

  useEffect(() => {
    if (language) {
      setLocale(language as Locale);
    }
  }, [language]);

  return (
    <AuthProvider>
      <SidebarProvider>
        <AppSidebar />
        <SidebarInset>
          <Header />
          <Outlet />
        </SidebarInset>
      </SidebarProvider>
    </AuthProvider>
  );
}
