﻿/* Copyright (C) Click & Push Accessibility, Inc - All Rights Reserved
 * Unauthorized copying of this file, via any medium is strictly prohibited
 * Proprietary and confidential
 * Written and maintained by the Click & Push Development team 
 * <dev@clicknpush.ca>, January 2022
 */

import { FontAwesome } from '@expo/vector-icons';
import { BottomTabBarOptions, BottomTabNavigationProp, createBottomTabNavigator } from "@react-navigation/bottom-tabs";
import { observer } from "mobx-react";
import React, { useEffect } from "react";
import { AppState, Platform, SafeAreaView, View, Text, Alert } from 'react-native';
import OutdoorMap from "../components/Map/MainMapComponent/OutdoorMap";
import Profile from "../components/Profile/Profile";
import { colors, SECURESTORE_NOTIFTOKEN } from "../utils/GlobalUtils";
import  {check, checkMultiple, PERMISSIONS, requestMultiple} from 'react-native-permissions'
import { Feed } from '../components/Feed/Feed';
import { getItemAsync } from 'expo-secure-store';
import Constants from 'expo-constants';
import * as Notifications from 'expo-notifications'
import { NavigationContainerRef, RouteProp } from '@react-navigation/native';
import { QueryClient, useQuery } from 'react-query';
import { useProfile } from '../hooks/useProfile';
import { NotifType } from '../types';
import Badge from '../components/Badge';
import MapNavigator from './MapNavigator';
import { useAuth } from '../lib/auth/AuthContext';

Notifications.setNotificationHandler({
    handleNotification: async () => ({
      shouldShowAlert: true,
      shouldPlaySound: false,
      shouldSetBadge: false,
    }),
});

const MainTabs = createBottomTabNavigator();

const tabBarOptions: BottomTabBarOptions = {
    //keyboardHidesTabBar: true,
    activeTintColor: 'white',
    activeBackgroundColor: '#e35555',
    inactiveTintColor: "lightgray",
    
    style: {backgroundColor: colors.red, height: 60, justifyContent: 'center'},
    labelStyle: {marginBottom: 7},
    iconStyle: {marginBottom: 7}
} 

/**
 * Permitted screens for the Auth tabs navigator. 
 * @category Navigation
 * @typedef
 */
 export type AuthTabsParamList = {
    Map: {selectedLandmark: string, selectedLandmarks: string[]},
    Profile: React.FC,
}

export type AuthTabsNavigationProp = BottomTabNavigationProp<AuthTabsParamList>

export const navigationRef = React.createRef<NavigationContainerRef>()

export const navigate = (name: string, params?) => {
    navigationRef.current.navigate(name, params)
}

/**
 * The root navigator for all authorized screens ({@link Map}, {@link Profile}). It uses a [React Navigation Bottom Tabs Navigator]{@link https://reactnavigation.org/docs/bottom-tab-navigator/} the main navigation mechanism.
 * @category Navigation
 * @component
 */
const AuthorizedNavigator: React.FC = () => {
    const { userId } = useAuth()
    const { profile, toggleTipsAsync, notifications, markNotificationAsRead, refetchNotifications } = useProfile(userId)

    /**
     * If the user has their preferences configured to show tips, show them on page load. Recheck every time show_tips changes
     */
    useEffect(() => {
        const showTip = () =>  {
            if (profile?.show_tips) {
                console.log('[Profile]: User has tips configured, showing tips.')
                Alert.alert(
                    'Welcome!', 
                    "There are 3 ways to add a landmark to the map: \n\n - Press and hold where you'd like to add it on the map \n\n - Press the add button to add a landmark at your current location \n\n - Press the mic button and use voice commands.", 
                    [{text: "Don't show this again", onPress: async () => await toggleTipsAsync()}, {text: 'Ok'}]
                )   
            }
            else {
                console.log('[Profile]: User does not have tips configured, not showing tips')
            }
        }
        showTip();
    }, [profile?.show_tips])

    const handleNotificationInteraction = async (notifData: any) => {
        await markNotificationAsRead(notifData.notif_id)
        await refetchNotifications()
        if (notifData?.notif_type as NotifType == 'landmark-like' || notifData?.notif_type as NotifType == 'near-landmark')
            navigate('Map', {selectedLandmark: notifData.landmark_id})
        if (notifData?.notif_type as NotifType == 'near-landmarks')
            navigate('Map', {selectedLandmarks: notifData.landmarks})
    }

    useEffect(() => {
        const notifReceivedSubscription = Notifications.addNotificationReceivedListener(async notification => { 
            await refetchNotifications()
        })

        const notifResponseReceivedSubscription = Notifications.addNotificationResponseReceivedListener(async response => {
            const notifData = response.notification.request.content.data
            handleNotificationInteraction(notifData)
        });

        return () => {
            notifReceivedSubscription.remove()
            notifResponseReceivedSubscription.remove()
        }; 
    }, [])

    const getIconSize = (focused: boolean): number => {
        if (focused) {
            return 20
        }
        else {
            return 17
        } 
    }

    const renderFeedBadge = () => {
        const newNotifAmount = notifications?.filter(notif => !notif.read).length

        return newNotifAmount > 0 ? <Badge positioning={{top: 8, left: 13,}} value={newNotifAmount}/> : null
    }

    return(
        <SafeAreaView style={{height: '100%'}}>
            {/* <AdMobBanner adUnitID="ca-app-pub-3940256099942544/6300978111" /> */}
            <MainTabs.Navigator 
                sceneContainerStyle={{flex:1}}     
                initialRouteName="Map"
                tabBarOptions={tabBarOptions}>
                <MainTabs.Screen name="Map" component={MapNavigator} options={{tabBarIcon: ({color, focused}) => (<FontAwesome name={focused ? 'map' : 'map-o'} size={getIconSize(focused)} color={color} style={{position: 'absolute', top: 10}}/>)}}/>
                <MainTabs.Screen name="Feed" options={{tabBarIcon: ({color, focused}) => (
                    <View style={{position: 'absolute', top: 10}}>
                        <FontAwesome name={focused ? 'bell' : 'bell-o'} size={getIconSize(focused)} color={color} />
                        {renderFeedBadge()}
                    </View>
                )}}>
                    {() => <Feed notifications={notifications} handleNotifInteraction={handleNotificationInteraction} />}
                </MainTabs.Screen>
                <MainTabs.Screen name="Profile" component={Profile} options={{tabBarIcon: ({color, focused}) => (<FontAwesome name={focused ? 'user' : 'user-o'} size={getIconSize(focused)} color={color} style={{position: 'absolute', top: 10}}/>)}} />
            </MainTabs.Navigator>
        </SafeAreaView>
        
    )
}

export default observer(AuthorizedNavigator);