/* eslint-disable no-case-declarations */
import {FirebaseMessagingTypes} from '@react-native-firebase/messaging';
import {IconUser, IconUsersGroup} from '@tabler/icons-react-native';
import {AvatarProps} from '@components/_HuGo/Avatar';
import {useGroups} from '@modules/chats/store/zustand/useGroups';
import {NotificationType} from '@shared/notifications';
import {getUlid} from '@shared/utils';

import {InAppNotificationBody} from './interfaces';
import {
  getVisibleNotification,
  pushNotification,
  updateNotification,
} from './store';

/**
 * Get the payload for the notification
 * @param remoteMessage - The remote message from Firebase Messaging
 * @returns The payload for the notification
 */
export const getNotificationPayload = (
  remoteMessage: FirebaseMessagingTypes.RemoteMessage,
) => {
  const data = remoteMessage?.data;
  const defaultPayload: InAppNotificationBody = {
    id: getUlid(),
    title: remoteMessage.notification?.title || '',
    subtitle: '',
    body: remoteMessage.notification?.body || '',
    avatar: remoteMessage.notification?.image
      ? {url: remoteMessage.notification?.image}
      : undefined,
    data: remoteMessage.data,
  };

  switch (data?.type) {
    case NotificationType.Chats2_New_Message:
      const conversation = data.channel_ts
        ? useGroups.getState().groups?.[data.channel_ts as string]?.groupInfo
        : null;
      const avatar: AvatarProps | undefined = conversation
        ? {
            url:
              conversation.picture_url ||
              conversation.other_user?.picture_asset_url,
            name: conversation.is_im
              ? `${conversation.other_user?.first_name} ${conversation.other_user?.last_name}`
              : undefined,
            Icon: conversation.is_channel ? IconUsersGroup : IconUser,
            withAuthHeader: true,
          }
        : undefined;

      return {
        ...defaultPayload,
        avatar,
        collapsedId: conversation?.id,
      };
    default:
      return defaultPayload;
  }
};

/**
 * Get the collapsed id for the notification
 * @param remoteMessage - The remote message from Firebase Messaging
 * @returns The collapsed id for the notification
 */
export const getNotificationCollapsedId = (
  remoteMessage: FirebaseMessagingTypes.RemoteMessage,
) => {
  const data = remoteMessage?.data;
  switch (data?.type) {
    case NotificationType.Chats2_New_Message:
      return data.channel_ts;
    default:
      return null;
  }
};

export const displayInAppNotification = (
  remoteMessage: FirebaseMessagingTypes.RemoteMessage,
) => {
  const payload = getNotificationPayload(remoteMessage);
  const collapsedId = getNotificationCollapsedId(remoteMessage);
  const visibleNotification = getVisibleNotification();

  if (collapsedId && collapsedId === visibleNotification?.collapsedId) {
    updateNotification({...payload, updatedAt: Date.now()});
  } else {
    pushNotification(payload);
  }
};
