import { FontAwesome } from "@expo/vector-icons"
import React from "react"
import { ListRenderItem, Text, View } from "react-native"
import { FlatList, TouchableOpacity } from "react-native-gesture-handler"
import { useProfile, UserNotification } from "../../hooks/useProfile"
import { authStore } from "../../stores/AuthStore"

/**
 * This component displays all the user's notifications sorted by most recent
 * @param 
 * @returns 
 */
export const Feed: React.FC<{notifications: UserNotification[], handleNotifInteraction}> = ({notifications, handleNotifInteraction}) => {
    // bring in the deleteNotification function from the useProfile hook
    const {deleteNotification} = useProfile(authStore.userId)

    /**
     * Flatlist item render function for notifcations. Displays the notification's title and a delete button. 
     * Renders the text bold if the notification hasn't been pressed yet 
    */
    const renderNotification: ListRenderItem<UserNotification> = ({item, index}) => {
        console.log(item.data.replace(/'/g, '"'))
        const notifData = JSON.parse(item.data.replace(/'/g, '"'))

        return (
            <View style={{flexDirection: 'row', alignItems: 'center', justifyContent: 'flex-start', borderBottomWidth: 1, borderColor: 'lightgray'}}>
                <TouchableOpacity style={{flex: 10, padding: 20}} onPress={() => handleNotifInteraction(notifData)}>
                    <Text style={{paddingRight: 110, fontWeight: item.read ? 'normal' : 'bold', color: item.read ? 'gray' : 'black'}} > 
                        {notifData?.notif_type == 'landmark-like' ? <FontAwesome name="thumbs-up" color={item.read ? "darkgray" : "black"} size={20} /> : null}
                        {"   -   "}
                        {item.title}
                    </Text>
                </TouchableOpacity>
                <TouchableOpacity onPress={async () => deleteNotification(item.id)}>
                    <FontAwesome style={{textAlign: 'center', padding: 15}} name="trash" color='red' size={20} />
                </TouchableOpacity>
            </View>
        );
    }

    return (
        <>
        {notifications?.length > 0 ?
        <FlatList
            nestedScrollEnabled={true}
            keyExtractor={i => i.id}
            data={notifications} 
            renderItem={renderNotification}
            getItemLayout={(data, index) => ({length: notifications.length, offset: notifications.length * index, index})}/> :
        <View style={{ alignItems: 'center', marginTop: 40}}>
            <Text style={{fontSize: 17}}>You have no notifications</Text>
        </View>}
        </>
    )
}