import HeaderRightAnnouncementList from "@/components/announcement/headerAnnouncementList";
import AppHeader from "@/components/AppHeader";
import HeaderDiscussionGeneral from "@/components/discussion_general/headerDiscussionGeneral";
import HeaderRightDivisionList from "@/components/division/headerDivisionList";
import HeaderRightGroupList from "@/components/group/headerGroupList";
import HeaderMemberList from "@/components/member/headerMemberList";
import HeaderRightPositionList from "@/components/position/headerRightPositionList";
import HeaderRightProjectList from "@/components/project/headerProjectList";
import Text from "@/components/Text";
import ToastCustom from "@/components/toastCustom";
import { Headers } from "@/constants/Headers";
import { apiReadOneNotification } from "@/lib/api";
import { pushToPage } from "@/lib/pushToPage";
import store from "@/lib/store";
import { useAuthSession } from "@/providers/AuthProvider";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { getApp } from "@react-native-firebase/app";
import { getMessaging, onMessage } from "@react-native-firebase/messaging";
import { Redirect, router, Stack, usePathname } from "expo-router";
import { StatusBar } from 'expo-status-bar';
import { useEffect } from "react";
import { Easing, Notifier } from 'react-native-notifier';
import { Provider } from "react-redux";

export default function RootLayout() {
   const { token, decryptToken, isLoading } = useAuthSession()
   const pathname = usePathname()

   async function handleReadNotification(id: string, category: string, idContent: string, title: string) {
      try {
         if (title != "Komentar Baru") {
            const hasil = await decryptToken(String(token?.current))
            const response = await apiReadOneNotification({ user: hasil, id: id })
         }
         pushToPage(category, idContent)
      } catch (error) {
         console.error(error)
      }
   }

   useEffect(() => {
      const checkNavigation = async () => {
         const navData = await AsyncStorage.getItem('navigateOnOpen');
         if (navData) {
            const { screen, content } = JSON.parse(navData);
            await AsyncStorage.removeItem('navigateOnOpen'); // reset
            pushToPage(screen, content)
         }
      };

      checkNavigation();
   }, []);

   useEffect(() => {
      const mess = getMessaging(getApp());

      const unsubscribe = onMessage(mess, async remoteMessage => {
         const id = remoteMessage?.data?.id;
         const category = remoteMessage?.data?.category;
         const content = remoteMessage?.data?.content;
         const title = remoteMessage?.notification?.title;

         if (remoteMessage.notification?.title && remoteMessage.notification?.body) {
            if (category === 'discussion-general' && pathname === '/discussion/' + content) {
               return null;
            } else if (pathname !== `/${category}/${content}`) {
               Notifier.showNotification({
                  title: title,
                  description: remoteMessage.notification?.body,
                  duration: 3000,
                  animationDuration: 300,
                  showEasing: Easing.ease,
                  onPress: () => handleReadNotification(String(id), String(category), String(content), String(title)),
                  hideOnPress: true,
               });
            }
         }
      });

      return unsubscribe;
   }, [pathname]);


   if (isLoading) {
      return <Text>Loading...</Text>;
   }

   if (!token?.current) {
      return <Redirect href="/" />;
   }

   return (
      <Provider store={store}>
         <Stack screenOptions={Headers.shadow} >
            <Stack.Screen name="home" options={{ title: 'Home' }} />
            <Stack.Screen name="feature" options={{ title: 'Fitur' }} />
            <Stack.Screen name="search" options={{ title: 'Pencarian' }} />
            <Stack.Screen name="notification" options={{
               title: 'Notifikasi',
               // headerLeft: () => <ButtonBackHeader onPress={() => { router.back() }} />,
               headerTitle: 'Notifikasi',
               headerTitleAlign: 'center',
               header: () => (
                  <AppHeader title="Notifikasi" showBack={true} onPressLeft={() => router.back()} />
               )
            }} />
            <Stack.Screen name="profile" options={{ title: 'Profile' }} />
            <Stack.Screen name="member/index" options={{
               // headerLeft: () => <ButtonBackHeader onPress={() => { router.back() }} />,
               title: 'Anggota',
               headerTitleAlign: 'center',
               // headerRight: () => <HeaderMemberList />
               header: () => (
                  <AppHeader title="Anggota"
                     showBack={true}
                     onPressLeft={() => router.back()}
                     right={<HeaderMemberList />}
                  />
               )
            }} />
            <Stack.Screen name="discussion/index" options={{
               // headerLeft: () => <ButtonBackHeader onPress={() => { router.back() }} />,
               title: 'Diskusi Umum',
               headerTitleAlign: 'center',
               // headerRight: () => <HeaderDiscussionGeneral />
               header: () => (
                  <AppHeader
                     title="Diskusi Umum"
                     showBack={true}
                     onPressLeft={() => router.back()}
                     right={<HeaderDiscussionGeneral />}
                  />
               )
            }} />
            <Stack.Screen name="project/index" options={{
               // headerLeft: () => <ButtonBackHeader onPress={() => { router.back() }} />,
               title: 'Kegiatan',
               headerTitleAlign: 'center',
               // headerRight: () => <HeaderRightProjectList />
               header: () => (
                  <AppHeader title="Kegiatan"
                     showBack={true}
                     onPressLeft={() => router.back()}
                     right={<HeaderRightProjectList />}
                  />
               )
            }} />
            <Stack.Screen name="division/index" options={{
               // headerLeft: () => <ButtonBackHeader onPress={() => { router.back() }} />,
               title: 'Divisi',
               headerTitleAlign: 'center',
               // headerRight: () => <HeaderRightDivisionList />
               header: () => (
                  <AppHeader title="Divisi"
                     showBack={true}
                     onPressLeft={() => router.back()}
                     right={<HeaderRightDivisionList />}
                  />
               )
            }} />
            <Stack.Screen name="division/[id]/(fitur-division)" options={{ headerShown: false }} />
            <Stack.Screen name="group/index" options={{
               // headerLeft: () => <ButtonBackHeader onPress={() => { router.back() }} />,
               headerTitle: 'Lembaga Desa',
               headerTitleAlign: 'center',
               // headerRight: () => <HeaderRightGroupList />
               header: () => (
                  <AppHeader title="Lembaga Desa"
                     showBack={true}
                     onPressLeft={() => router.back()}
                     right={<HeaderRightGroupList />}
                  />
               )
            }} />
            <Stack.Screen name="position/index" options={{
               // headerLeft: () => <ButtonBackHeader onPress={() => { router.back() }} />,
               headerTitle: 'Jabatan',
               headerTitleAlign: 'center',
               // headerRight: () => <HeaderRightPositionList />
               header: () => (
                  <AppHeader title="Jabatan"
                     showBack={true}
                     onPressLeft={() => router.back()}
                     right={<HeaderRightPositionList />}
                  />
               )
            }} />
            <Stack.Screen name="announcement/index"
               options={{
                  // headerLeft: () => <ButtonBackHeader onPress={() => { router.back() }} />,
                  headerTitle: 'Pengumuman',
                  headerTitleAlign: 'center',
                  // headerRight: () => <HeaderRightAnnouncementList />
                  header: () => (
                     <AppHeader title="Pengumuman"
                        showBack={true}
                        onPressLeft={() => router.back()}
                        right={<HeaderRightAnnouncementList />}
                     />
                  )
               }}
            />
         </Stack>
         <StatusBar style={'light'} translucent={false} backgroundColor="black" />
         <ToastCustom />
      </Provider>
   )
}
