import messaging from '@react-native-firebase/messaging';
import { Platform, PermissionsAndroid, Alert } from 'react-native';

// Handle background messages
messaging().setBackgroundMessageHandler(async remoteMessage => {
  console.log('FCM: Received message in Quit state/Background!', remoteMessage);
});

export const PushService = {
  async initNotifications() {
    try {
      if (Platform.OS === 'android') {
        const granted = await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS);
        if (granted !== PermissionsAndroid.RESULTS.GRANTED) {
          console.warn('FCM: Post notifications permission denied.');
        }
      }

      const authStatus = await messaging().requestPermission();
      const enabled =
        authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
        authStatus === messaging.AuthorizationStatus.PROVISIONAL;

      if (enabled) {
        console.log('FCM: Permission status:', authStatus);
        const fcmToken = await this.getFCMToken();
        if (fcmToken) {
          // This would be called to send the token to the backend
          // Example: await AuthApi.registerPushToken(fcmToken);
          console.log('FCM Token registered:', fcmToken);
        }
      }
    } catch (error) {
      console.error('FCM: Failed to initialize notifications:', error);
    }

    // Handle messages while the app is in focus
    const unsubscribeOnMessage = messaging().onMessage(async remoteMessage => {
      console.log('FCM: Received foreground message:', remoteMessage);
      // Optional: Display alert if user is in different screen or something
    });

    // Handle interaction when the app is in background but not quit
    const unsubscribeOnNotificationOpenedApp = messaging().onNotificationOpenedApp(remoteMessage => {
      console.log('FCM: Notification caused app to open from background state:', remoteMessage.data);
    });

    // Check if the app was opened by clicking a notification from a quit state
    messaging().getInitialNotification().then(remoteMessage => {
      if (remoteMessage) {
        console.log('FCM: Notification caused app to open from quit state:', remoteMessage.data);
      }
    });

    return () => {
      unsubscribeOnMessage();
      unsubscribeOnNotificationOpenedApp();
    };
  },

  async getFCMToken(): Promise<string | null> {
    try {
      const fcmToken = await messaging().getToken();
      if (fcmToken) return fcmToken;
    } catch (error) {
      console.error('FCM: Error getting token:', error);
    }
    return null;
  },

  async deleteFCMToken(): Promise<void> {
    try {
      await messaging().deleteToken();
    } catch (error) {
      console.error('FCM: Error deleting token:', error);
    }
  }
};
