import React, { useEffect, useState, useCallback } from 'react';
import { 
  View, 
  Text, 
  StyleSheet, 
  FlatList, 
  ActivityIndicator, 
  RefreshControl, 
  useColorScheme, 
  TouchableOpacity,
  Dimensions
} from 'react-native';
import { Colors } from '@/constants/theme';
import api from '@/services/api';
import { useAuthStore } from '@/store/authStore';
import { useFocusEffect } from 'expo-router';
import Animated, { FadeInDown, FadeIn } from 'react-native-reanimated';
import { Ionicons } from '@expo/vector-icons';
import { LinearGradient } from 'expo-linear-gradient';
import { Image } from 'expo-image';
import { UnifiedBottomNav } from '@/components/home/UnifiedBottomNav';

const { width } = Dimensions.get('window');

export default function NotificationsScreen() {
  const colorScheme = useColorScheme() ?? 'light';
  const theme = Colors[colorScheme as 'light' | 'dark'];
  const { user_id } = useAuthStore();

  const [notifications, setNotifications] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [unreadCount, setUnreadCount] = useState(0);

  const fetchNotifications = async () => {
    try {
      const response = await api.post('/notification/notificationlist', { authid: user_id });
      if (response.data.code === '200') {
        const data = response.data.data;
        setNotifications(data.notifications || []);
        setUnreadCount(data.count || 0);
      }
    } catch (error) {
      console.error('Error fetching notifications:', error);
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

  const markAllAsRead = async () => {
    try {
      await api.post('/notification/updatereadstatus', { authid: user_id });
      fetchNotifications();
    } catch (error) {
      console.error('Error updating read status:', error);
    }
  };

  useFocusEffect(
    useCallback(() => {
      fetchNotifications();
      // Optionally mark as read automatically when opening the screen
      // markAllAsRead(); 
    }, [])
  );

  const onRefresh = () => {
    setRefreshing(true);
    fetchNotifications();
  };

  const renderItem = ({ item, index }: { item: any; index: number }) => {
    // Logic from web: if current user is sender, see from_description, else to_description
    const isSender = user_id === item.from_user_id;
    const description = isSender ? item.from_description : item.to_description;
    const profileImg = isSender ? item.from_profileimg : item.to_profileimg;
    const isUnread = isSender ? item.from_read_type === 0 : item.to_read_type === 0;

    return (
      <Animated.View entering={FadeInDown.duration(400).delay(index * 50)}>
        <TouchableOpacity activeOpacity={0.8} style={styles.notificationItem}>
          <View style={[styles.card, { backgroundColor: theme.secondary, borderColor: isUnread ? theme.primary : theme.border }]}>
            <Image 
              source={{ uri: profileImg || 'https://ui-avatars.com/api/?name=' + (item.from_name || 'User') }} 
              style={styles.avatar}
              contentFit="cover"
            />
            <View style={styles.textContainer}>
              <View style={styles.headerRow}>
                <Text style={[styles.sourceText, { color: theme.primary }]}>{item.source}</Text>
                <Text style={[styles.dateText, { color: theme.textMuted }]}>{item.notificationdate}</Text>
              </View>
              <Text style={[styles.description, { color: theme.text, fontWeight: isUnread ? '700' : '500' }]} numberOfLines={2}>
                {description}
              </Text>
              {isUnread && <View style={[styles.unreadDot, { backgroundColor: theme.primary }]} />}
            </View>
          </View>
        </TouchableOpacity>
      </Animated.View>
    );
  };

  return (
    <View style={[styles.container, { backgroundColor: theme.background }]}>
      {/* Immersive Decorative Header */}
      <LinearGradient
        colors={theme.gradients.primary as [string, string]}
        start={{ x: 0, y: 0 }}
        end={{ x: 1, y: 1 }}
        style={styles.header}
      >
        <View style={styles.headerContent}>
          <View /> 
          {unreadCount > 0 && (
            <TouchableOpacity onPress={markAllAsRead} style={styles.readAllButton}>
              <Ionicons name="checkmark-done" size={16} color="#fff" />
              <Text style={styles.readAllText}>Lidas</Text>
            </TouchableOpacity>
          )}
        </View>
      </LinearGradient>

      {loading && !refreshing ? (
        <View style={styles.centerContainer}>
          <ActivityIndicator size="large" color={theme.primary} />
        </View>
      ) : (
        <FlatList
          data={notifications}
          keyExtractor={(item) => item.notification_id.toString()}
          renderItem={renderItem}
          contentContainerStyle={styles.listContent}
          showsVerticalScrollIndicator={false}
          refreshControl={<RefreshControl refreshing={refreshing} onRefresh={onRefresh} tintColor={theme.primary} />}
          ListEmptyComponent={
            <View style={styles.emptyContainer}>
              <View style={[styles.emptyIconCircle, { backgroundColor: theme.secondary }]}>
                <Ionicons name="notifications-off-outline" size={48} color={theme.border} />
              </View>
              <Text style={[styles.emptyText, { color: theme.textMuted }]}>Nenhuma notificação encontrada.</Text>
            </View>
          }
        />
      )}
      <UnifiedBottomNav />
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1 },
  header: {
    height: 80,
    justifyContent: 'flex-end',
    paddingBottom: 15,
    paddingHorizontal: 20,
    borderBottomLeftRadius: 30,
    borderBottomRightRadius: 30,
  },
  headerContent: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  headerTitle: {
    fontSize: 28,
    fontWeight: '800',
    color: '#fff',
    letterSpacing: -0.5,
  },
  readAllButton: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: 'rgba(255,255,255,0.2)',
    paddingHorizontal: 12,
    paddingVertical: 6,
    borderRadius: 20,
  },
  readAllText: {
    color: '#fff',
    fontSize: 12,
    fontWeight: '700',
    marginLeft: 4,
  },
  centerContainer: { flex: 1, justifyContent: 'center', alignItems: 'center' },
  listContent: { padding: 20, paddingBottom: 100 },
  notificationItem: {
    marginBottom: 12,
  },
  card: {
    flexDirection: 'row',
    padding: 12,
    borderRadius: 20,
    borderWidth: 1,
    alignItems: 'center',
  },
  avatar: {
    width: 50,
    height: 50,
    borderRadius: 25,
    marginRight: 12,
  },
  textContainer: { flex: 1, position: 'relative' },
  headerRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 4,
  },
  sourceText: {
    fontSize: 12,
    fontWeight: '700',
    textTransform: 'uppercase',
  },
  dateText: {
    fontSize: 11,
    fontWeight: '500',
  },
  description: {
    fontSize: 14,
    lineHeight: 18,
  },
  unreadDot: {
    position: 'absolute',
    top: 0,
    right: -5,
    width: 6,
    height: 6,
    borderRadius: 3,
  },
  emptyContainer: { 
    flex: 1, 
    alignItems: 'center', 
    justifyContent: 'center', 
    marginTop: 100 
  },
  emptyIconCircle: {
    width: 100,
    height: 100,
    borderRadius: 50,
    justifyContent: 'center',
    alignItems: 'center',
    marginBottom: 20,
  },
  emptyText: { 
    fontSize: 16, 
    fontWeight: '600',
    textAlign: 'center'
  }
});
