import { getApp, getApps, initializeApp } from '@react-native-firebase/app';
import { getMessaging, registerDeviceForRemoteMessages, setAutoInitEnabled } from '@react-native-firebase/messaging';
import * as Notifications from 'expo-notifications';
import { useEffect } from 'react';
import { PermissionsAndroid, Platform } from 'react-native';

// Your Firebase project configuration
const RNfirebaseConfig = {
   apiKey: "AIzaSyB2hbsW91J3oRQx4_jgrCCNY0tNt5-21e8",
   authDomain: "googleapis.com",
   projectId: "mobile-darmasaba",
   storageBucket: "mobile-darmasaba.appspot.com",
   messagingSenderId: "867439221179",
   appId: "1:867439221179:android:4509f77478c8dce99b0c9e",
   databaseURL: "https://mobile-darmasaba-default-rtdb.asia-southeast1.firebasedatabase.app/"
};


const initializeFirebase = async () => {
   try {
      const app = getApps().length ? getApp() : initializeApp(RNfirebaseConfig);
      const mess = getMessaging(app);
      await registerDeviceForRemoteMessages(mess);
      setAutoInitEnabled(mess, true);
      return mess
   } catch (error) {
      console.error('Failed to initialize Firebase:', error);
   }
};

export const requestPermission = async () => {
   try {
      if (Platform.OS === 'android') {
         const cek = await PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS)
         if (!cek) {
            const granted = await PermissionsAndroid.request(
               PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS
            );
            if (granted === PermissionsAndroid.RESULTS.GRANTED) {
               return true
            }
            return false
         }
         return true
      } else if (Platform.OS === 'ios') {
         const { status } = await Notifications.requestPermissionsAsync();
         return status === 'granted';
      }
   } catch (err) {
      console.warn('Error requesting notification permissions:', err);
   }
};

export const getToken = async () => {
   try {
      const mess = await initializeFirebase();
      const token = await mess?.getToken();
      return token;
   } catch (error) {
      console.error("Error getting token:", error);
   }
};

export const useNotification = () => {
   useEffect(() => {
      const initializeAndSetup = async () => {
         try {
            await getToken();
         } catch (error) {
            console.error('Failed to setup notifications:', error);
         }
      };

      initializeAndSetup();
   }, []);
};