import React from 'react';
import {useMutation} from '@tanstack/react-query';
import {useNavigation} from '@react-navigation/native';
import {IconBell} from '@tabler/icons-react-native';
import {BadgeIconButton} from '@components';
import {queryClientV5} from '@config/queryClient';
import {useQuery} from '@hooks/queries-v5/useQuery';
import {NOTIFICATIONS_QUERY_KEYS} from '@modules/notificationsCenter/constants';
import {
  clearBubbleNotifications,
  getNotificationsUnreadCount,
} from '@modules/notificationsCenter/services';
import {useNotificationsCountListener} from '@modules/notificationsCenter/hooks';
import {useInstanceId, useUserId} from '@redux/selectors';
import {AMPLITUDE_EVENTS, Screens} from '@shared/constants';
import {logAmplitudeEvent} from '@shared/utils';

export function NotificationsButton() {
  const navigation = useNavigation();
  const userId = useUserId();
  const instanceId = useInstanceId();

  const {data: notificationsCount} = useQuery(
    NOTIFICATIONS_QUERY_KEYS.notificationsCount,
    getNotificationsUnreadCount,
  );
  const {mutate: clearBubble} = useMutation({
    mutationFn: clearBubbleNotifications,
    onSuccess: () => {
      queryClientV5.invalidateQueries({
        queryKey: NOTIFICATIONS_QUERY_KEYS.notificationsCount,
      });
    },
  });

  const onPressNotifications = () => {
    logAmplitudeEvent(AMPLITUDE_EVENTS.NC_LIST_OPEN, {userId, instanceId});
    clearBubble();
    navigation.navigate(Screens.NOTIFICATIONS_LIST);
  };

  useNotificationsCountListener();

  return (
    <BadgeIconButton
      Icon={IconBell}
      onIconPress={onPressNotifications}
      value={notificationsCount?.newSinceLastSeen ?? 0}
    />
  );
}
