/* 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 { BottomTabNavigationOptions, BottomTabNavigationProp, createBottomTabNavigator } from "@react-navigation/bottom-tabs";
import * as Notifications from 'expo-notifications';
import { observer } from "mobx-react";
import React, { useEffect } from "react";
import { Alert, SafeAreaView, View } from 'react-native';
import Badge from '../components/Badge';
import { Feed } from '../components/Feed/Feed';
import ProfileTemplate from '../components/Profile/ProfileTemplate';
import { useAuth } from '../data/Auth/AuthContext';
import { useMarkNotificationRead, useNotifications, useRegisterNotifications } from '../data/notifications';
import { usePermissions } from '../data/PermissionsContext';
import { useOwnedProfile, useToggleTips } from '../data/profiles';
import { colors } from "../utils/GlobalUtils";
import MapNavigator from './MapNavigator';

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

const MainTabs = createBottomTabNavigator();

const tabBarOptions: BottomTabNavigationOptions = {
    //keyboardHidesTabBar: true,
    tabBarActiveTintColor: 'white',
    tabBarInactiveTintColor: "lightgray",
    headerShown: false,
    tabBarStyle: {backgroundColor: colors.red, justifyContent: 'center'},
    tabBarLabelStyle: {marginBottom: 7},
    tabBarIconStyle: {marginBottom: 7}
} 

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

export type MainTabsNavigationProp = BottomTabNavigationProp<MainTabsParamList>
/**
 * 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 MainTabsNavigator: React.FC<{navigation}> = ({navigation}) => {
    const {profile} = useOwnedProfile()
    const {userId} = useAuth()
    const {notificationPermissionsGranted} = usePermissions()
    const toggleTips = useToggleTips()
    const notificationsQuery = useNotifications()
    const {subscribeToNotifications, handleNotificationInteraction} = useRegisterNotifications()

    /**
     * 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 toggleTips.mutateAsync()}, {text: 'Ok'}]
                )   
            }
            else {
                console.log('[Profile]: User does not have tips configured, not showing tips')
            }
        }
        showTip();
    }, [profile?.show_tips])

    useEffect(() => {
        subscribeToNotifications()
    }, [userId, notificationPermissionsGranted]);

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

    const renderFeedBadge = () => {
        const newNotifAmount = notificationsQuery.data?.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"
                screenOptions={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: 8}}/>)}}/>
                <MainTabs.Screen name="Feed" options={{tabBarIcon: ({color, focused}) => (
                    <View style={{position: 'absolute', top: 8}}>
                        <FontAwesome name={focused ? 'bell' : 'bell-o'} size={getIconSize(focused)} color={color} />
                        {renderFeedBadge()}
                    </View>
                )}}>
                    {() => <Feed notifications={notificationsQuery.data} handleNotifInteraction={handleNotificationInteraction} />}
                </MainTabs.Screen>
                <MainTabs.Screen name="Account" options={{tabBarIcon: ({color, focused}) => (<FontAwesome name={focused ? 'user' : 'user-o'} size={getIconSize(focused)} color={color} style={{position: 'absolute', top: 8}}/>)}}>
                    {({navigation}) => <ProfileTemplate navigation={navigation}/>}
                </MainTabs.Screen>
            </MainTabs.Navigator>
        </SafeAreaView>
        
    )
}

export default observer(MainTabsNavigator);