import React, { useState, useEffect, useCallback } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import api from '@/services/api';
import { useAuthStore } from '@/store/authStore';
import { useFocusEffect } from 'expo-router';

interface NotificationBadgeProps {
  size?: number;
  style?: any;
}

export default function NotificationBadge({ size = 18, style }: NotificationBadgeProps) {
  const isAuthenticated = useAuthStore((state) => state.isAuthenticated);
  const { user_id, token } = useAuthStore();
  const [count, setCount] = useState(0);

  const fetchCount = async () => {
    if (!user_id || !isAuthenticated || !token) return;
    try {
      const response = await api.get(`/notification/getnotificationcount?authid=${user_id}`);
      if (response.data.code === '200') {
        setCount(response.data.data.unreadNotificationCount || 0);
      }
    } catch (error: any) {
      if (error.response?.status === 401) {
        setCount(0);
      }
      console.error('Error fetching notification count:', error);
    }
  };

  useFocusEffect(
    useCallback(() => {
      if (!isAuthenticated || !token) return;
      
      fetchCount();
      // Poll every 30 seconds for new notifications
      const interval = setInterval(fetchCount, 30000);
      return () => clearInterval(interval);
    }, [user_id, isAuthenticated, token])
  );

  if (count === 0) return null;

  return (
    <View style={[styles.badge, { width: size, height: size, borderRadius: size / 2 }, style]}>
      <Text style={[styles.text, { fontSize: size > 15 ? 10 : 8 }]}>
        {count > 9 ? '9+' : count}
      </Text>
    </View>
  );
}

const styles = StyleSheet.create({
  badge: {
    backgroundColor: '#FF3B30',
    justifyContent: 'center',
    alignItems: 'center',
    position: 'absolute',
    top: -4,
    right: -4,
    borderWidth: 1.5,
    borderColor: '#fff',
  },
  text: {
    color: '#fff',
    fontWeight: 'bold',
  },
});
