import { Platform } from 'react-native';
import * as Device from 'expo-device';
import * as Notifications from 'expo-notifications';
import { getPushNotificationToken, setPushNotificationToken } from 'utils/pushNotification';
import { COLOR_VALUES } from 'theme/color';
import { useEffect, useRef } from 'react';
import { doAlert } from 'utils/alert';
import { Item } from 'components/notification';
import { useAddPushTokenMutation } from 'expo-schema';

export const usePushNotification = (): PushNotificationProps => {
  const notificationListener = useRef<any>();
  const responseListener = useRef<any>();
  const [addPushToken] = useAddPushTokenMutation();
  const registerForPushNotificationsAsync = async () => {
    const isHandHeld = (Platform.OS === 'android' || Platform.OS === 'ios') && Device.isDevice;
    let token;
    if (isHandHeld) {
      const { status: existingStatus } = await Notifications.getPermissionsAsync();
      let finalStatus = existingStatus;
      if (existingStatus !== 'granted') {
        const { status } = await Notifications.requestPermissionsAsync();
        finalStatus = status;
      }
      if (finalStatus !== 'granted') {
        doAlert({ variant: 'error', message: 'Failed to get push token for push notification!' });
        return;
      }
      token = await getPushNotificationToken();
      if (!token) {
        token = (await Notifications.getExpoPushTokenAsync()).data;
        await setPushNotificationToken(token);
      }
      addPushToken({
        variables: {
          token,
        },
      });
    }

    if (Platform.OS === 'android') {
      Notifications.setNotificationChannelAsync('default', {
        name: 'default',
        importance: Notifications.AndroidImportance.MAX,
        vibrationPattern: [0, 250, 250, 250],
        lightColor: COLOR_VALUES.primary,
      });
    }

    return token;
  };

  useEffect(() => {
    notificationListener.current = Notifications.addNotificationReceivedListener(() => {
      doAlert({
        variant: 'info',
        left: <></>,
        marginTop: 50,
        content: <Item isAlertNotification />,
      });
    });

    responseListener.current = Notifications.addNotificationResponseReceivedListener(() => {});

    return () => {
      if (notificationListener.current) {
        Notifications.removeNotificationSubscription(notificationListener.current);
      }
      if (responseListener.current) {
        Notifications.removeNotificationSubscription(responseListener.current);
      }
    };
  }, []);

  return { registerForPushNotificationsAsync };
};

interface PushNotificationProps {
  registerForPushNotificationsAsync: () => Promise<string | undefined>;
}
