import moment from 'moment';
import * as Notifications from 'expo-notifications';
import { Platform } from 'react-native';
import { NAVIGATION_PAGES } from 'src/types';
import { usePushNotification } from 'src/contexts/PushNotificationContext';
import { CommonActions } from '@react-navigation/native';

export const formatDate = (dateString: Date): string => {
  const inputDate = moment.utc(dateString).local();
  const today = moment().local();
  const yesterday = moment().local().subtract(1, 'days');

  if (inputDate.isSame(today, 'day')) {
    return inputDate.format('HH:mm');
  }
  if (inputDate.isSame(yesterday, 'day')) {
    return 'yesterday';
  }
  if (!inputDate.isSame(today, 'year')) {
    return inputDate.format('DD.MM.YYYY');
  }

  return inputDate.format('DD.MM');
};

export const dismissChatNotifications = async (
  chatWithUserId: number,
  isSubscribed: boolean,
  setModalInfo: (data: any) => void,
  navigation: any
) => {
  const { status } = await Notifications.getPermissionsAsync();
  if (status !== 'granted' || !isSubscribed) {
    setModalInfo({
      visible: true,
      type: 'success',
      message:
        'To use this feature we need your permission to access your notifications. You will be redirected to the notification settings screen where you need to enable them.',
      action: () => navigation.navigate(NAVIGATION_PAGES.NOTIFICATIONS)
    });
    return;
  }

  const getNotificationData = (notification: Notifications.Notification) => {
    if (Platform.OS === 'android') {
      const data = notification.request.content.data;
      if (data?.params) {
        try {
          return JSON.parse(data.params) ?? {};
        } catch (error) {
          console.error('Error parsing params:', error);
          return {};
        }
      } else {
        Notifications.dismissNotificationAsync(notification.request.identifier);
        return {};
      }
    } else {
      const data = (notification.request.trigger as Notifications.PushNotificationTrigger)?.payload;
      if (data?.params) {
        try {
          return JSON.parse(data.params as string) ?? {};
        } catch (error) {
          console.error('Error parsing params:', error);
          return {};
        }
      }
    }
  };

  const clearNotificationsFromUser = async (userId: number) => {
    const presentedNotifications = await Notifications.getPresentedNotificationsAsync();
    presentedNotifications.forEach((notification) => {
      const parsedParams = getNotificationData(notification);
      const conversation_with_user = parsedParams?.id;

      if (conversation_with_user === userId) {
        Notifications.dismissNotificationAsync(notification.request.identifier);
      }
    });
  };

  await clearNotificationsFromUser(chatWithUserId);

  Notifications.setNotificationHandler({
    handleNotification: async (notification) => {
      let conversation_with_user = 0;
      const parsedParams = getNotificationData(notification);
      conversation_with_user = parsedParams?.id;

      if (conversation_with_user === chatWithUserId) {
        return {
          shouldShowAlert: false,
          shouldPlaySound: false,
          shouldSetBadge: false
        };
      }

      return {
        shouldShowAlert: true,
        shouldPlaySound: false,
        shouldSetBadge: false
      };
    }
  });

  return () => {
    Notifications.setNotificationHandler({
      handleNotification: async () => ({
        shouldShowAlert: true,
        shouldPlaySound: false,
        shouldSetBadge: false
      })
    });
  };
};
