import {useEffect} from 'react';
import notifee, {DisplayedNotification} from '@notifee/react-native';
import {isAndroid} from '@shared/utils';
import {NotificationType} from '@shared/notifications';

const CHATS_2_NOTIFICATION_TYPES: string[] = [
  NotificationType.Chats2_New_Message,
];

const clearNotificationAndroid = (notification: DisplayedNotification) => {
  if (
    notification.id &&
    (notification.notification.android?.tag?.startsWith('CHATS') ||
      notification.notification.data?.channel_ts) // Indicates it's a chat message notification ( in case when we received it when app is in foreground )
  ) {
    notifee.cancelNotification(
      notification.id,
      notification.notification.android?.tag,
    );
  }
};

const clearNotificationIOS = (notification: DisplayedNotification) => {
  if (
    notification.id &&
    notification.notification.data?.type &&
    CHATS_2_NOTIFICATION_TYPES.includes(
      notification.notification.data.type as string,
    )
  ) {
    notifee.cancelNotification(notification.id);
  }
};

const clearNotificationHandler = isAndroid
  ? clearNotificationAndroid
  : clearNotificationIOS;

export const cleanNotifications = async () => {
  try {
    const notifications = await notifee.getDisplayedNotifications();
    notifications.forEach(clearNotificationHandler);
  } catch (error) {
    // Do nothing
  }
};

/**
 * Clear Push Notifications related to Chats 2.0 on mount
 */
export const useClearNotifications = () => {
  useEffect(() => {
    cleanNotifications();
  }, []);
};
