import {
  createContext,
  useContext,
  useEffect,
  useGlobal,
  setGlobal,
} from "reactn";
import messaging from "@react-native-firebase/messaging";
import notifee, { EventType } from "@notifee/react-native";
import { CommonActions } from "@react-navigation/core";
import { useAppState } from "@react-native-community/hooks";
import { Linking } from "react-native";

import { dispatch } from "../navigation/NavigationService";
import { Routes } from "../navigation";
import firebase, { usersRef } from "../config/firebase";
import alert from "../components/Alert";

export const NotificationContext = createContext();

export async function displayNotification(data) {
  const { title, message, picture = null, video = null } = data || {};

  let ios = {
    categoryId: "default",
  };

  if (picture) {
    ios.attachments = [{ url: picture }];
  }

  if (video) {
    ios.attachments = [
      {
        url: video,
        thumbnailTime: data?.thumbnailTime
          ? parseInt(data?.thumbnailTime, 10)
          : 0,
      },
    ];
  }

  await notifee.displayNotification({
    title,
    body: message,
    ios,
    android: {
      channelId: "default",
    },
    data,
  });

  await notifee.incrementBadgeCount();
}

export async function triggerEvent({ type, detail }) {
  const { notification } = detail;

  if (type === EventType.PRESS) {
    const { data = {} } = notification || {};
    const { projectID = null, taskID = null, messageID = null } = data || {};

    if (projectID) {
      setGlobal({ currentProjectID: projectID });

      if (taskID) {
        dispatch(
          CommonActions.navigate({
            name: Routes.TaskDetails,
            params: { taskID, messageID },
          })
        );
      }
    }
  }
}

export default ({ children }) => {
  const [currentUID] = useGlobal("currentUID");

  const currentAppState = useAppState();

  useEffect(() => {
    if (currentUID) {
      updateFCMToken({ uid: currentUID });
    }
  }, [currentUID]);

  useEffect(() => {
    const unsubscribe = messaging().onMessage(async (remoteMessage) => {
      console.log("Message handled in the foreground!", remoteMessage);
      const { data } = remoteMessage;

      await displayNotification(data);
    });
    const foregroundSubscription = notifee.onForegroundEvent(triggerEvent);

    return () => {
      unsubscribe();
      foregroundSubscription();
    };
  }, []);

  useEffect(() => {
    if (currentAppState === "active") {
      notifee.setBadgeCount(0);
    }
  }, [currentAppState]);

  const updateFCMToken = async ({ uid }) => {
    try {
      const authResponse = await messaging().requestPermission();
      const enabled = authResponse === messaging.AuthorizationStatus.AUTHORIZED;
      if (enabled) {
        const fcmToken = await messaging().getToken();
        if (fcmToken) {
          await usersRef.doc(uid).update({
            fcmTokens: firebase.firestore.FieldValue.arrayUnion(fcmToken),
          });
        }
      } else {
        alert(
          "Activez les notifications",
          "Afin de rester informé de l'avancée de votre projet, il est important d'activer les notifications.",
          [
            {
              text: "Annuler",
              onPress: () => {},
              style: "cancel",
            },
            {
              text: "Paramètres",
              onPress: async () => {
                Linking.openSettings();
              },
              style: "confirm",
            },
          ]
        );
      }
    } catch (error) {
      console.log("error", error);
    }
  };

  return (
    <NotificationContext.Provider value={{}}>
      {children}
    </NotificationContext.Provider>
  );
};

export const useNotification = () => {
  return useContext(NotificationContext);
};
