import React, { useEffect, useState } from 'react';
import { FlatList, View, Text, Image, TouchableOpacity, ActivityIndicator } from 'react-native';
import axios from 'axios';
import { useNavigation } from '@react-navigation/native';
import { useTailwind } from 'tailwind-rn';
import AsyncStorage from '@react-native-async-storage/async-storage';

const Notifications = () => {
  const [notifications, setNotifications] = useState([]);
  const [page, setPage] = useState(1);
  const navigation = useNavigation();


  const tailwind = useTailwind();

  // Fetch notifications from the server
  const fetchNotifications = async () => {
    try {
        const token = await AsyncStorage.getItem('token');
        console.log(token)
        const apiUrl = await AsyncStorage.getItem('apiEndpoint')


      const res = await axios.get(`${apiUrl}/api/v1/app/notify/notifications?page=${page}`, {
        headers: {'Authorization': token,    } // replace token with your JWT token
      });
      setNotifications([...notifications, ...res.data]);
      setPage(page + 1);
    } catch (err) {
      console.error("fetch: ", err);
    }
  };

  // Fetch notifications when the component mounts
  useEffect(() => {
    fetchNotifications();
  }, []);

  // Mark a notification as read and navigate to the relevant screen
  const handlePress = async (notification) => {
    try {
        const token = AsyncStorage.getItem('token');
        const apiUrl = await AsyncStorage.getItem('apiEndpoint')


      await axios.put(`${apiUrl}/api/v1/app/notify/notifications/${notification._id}`, {}, {
        headers: { 'Authorization': token } // replace token with your JWT token
      });
      if (notification.type === 'like') {
        navigation.navigate('Likes', { switId: notification.switId });
      } else if (notification.type === 'comment') {
        navigation.navigate('Comments', { postId: notification.postId });
      } else if (notification.type === 'follow') {
        navigation.navigate('Profile', { userId: notification.fromUser });
      }
    } catch (err) {
      console.error("press: ", err);

    }
  };

  // Render a single notification
  const renderNotification = ({ item }) => (
    <View style={tailwind('border-b border-gray-200 p-2 flex-row items-center')}>
      <Image source={{ uri: item.fromUser.profilePicture }} style={tailwind('w-12 h-12 rounded-full')} />
      <TouchableOpacity style={tailwind('ml-2 flex-grow')} onPress={() => handlePress(item)}>
        <Text style={tailwind('text-lg')}>{item.text}</Text>
        <Text style={tailwind('text-sm text-gray-500')}>{new Date(item.createdAt).toLocaleString()}</Text>
      </TouchableOpacity>
      <View style={tailwind('pr-2')}>
        <ActivityIndicator size="small" color="#0000ff" />
      </View>
    </View>
  );

  return (
    <View style={tailwind('flex-1')}>
      <FlatList
        data={notifications}
        renderItem={renderNotification}
        keyExtractor={item => item._id}
        onEndReached={fetchNotifications}
        onEndReachedThreshold={0.5}
      />
    </View>
  );
};

export default Notifications;
