import { ConstEnv } from '@/constants/ConstEnv';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { getApp, getApps, initializeApp } from '@react-native-firebase/app';
import {
   getMessaging,
   getToken as getMessagingToken,
   setAutoInitEnabled,
} from '@react-native-firebase/messaging';
import * as Notifications from 'expo-notifications';
import { useEffect } from 'react';
import { Linking, Platform } from 'react-native';

const RNfirebaseConfig = {
   apiKey: ConstEnv.firebase.apiKey,
   authDomain: ConstEnv.firebase.authDomain,
   projectId: ConstEnv.firebase.projectId,
   storageBucket: ConstEnv.firebase.storageBucket,
   messagingSenderId: ConstEnv.firebase.messagingSenderId,
   appId: ConstEnv.firebase.appId,
   databaseURL: ConstEnv.firebase.databaseURL
};

const initializeFirebase = async () => {
   try {
      let app;
      const apps = getApps();
      if (apps.length) {
         app = getApp() as any;
      } else {
         app = initializeApp(RNfirebaseConfig) as any;
      }
      const mess = getMessaging(app);
      await setAutoInitEnabled(mess, true);

      return mess;
   } catch (error) {
      console.error('Failed to initialize Firebase:', error);
   }
};

export const checkPermission = async () => {
   try {
      // Cek status permission sekarang
      const { status } = await Notifications.getPermissionsAsync();

      if (status === 'granted') {
         return true;
      }

      if (status === 'denied') {
         return false;
      }
   } catch (err) {
      console.warn('Error checking notification permissions:', err);
      return false;
   }
};

export const openSettings = () => {
   if (Platform.OS === 'ios') {
      Linking.openURL('app-settings:');
   } else {
      Linking.openSettings();
   }
};

export const requestPermission = async () => {
   try {
      const { status: currentStatus } = await Notifications.getPermissionsAsync();

      // Jika belum pernah ditentukan (undetermined), baru panggil request
      if (currentStatus === 'undetermined') {
         const { status: newStatus } = await Notifications.requestPermissionsAsync();
         await AsyncStorage.setItem('@notification_permission', newStatus === 'granted' ? 'true' : 'false');
         return newStatus === 'granted';
      }

      // Jika sudah pernah ditentukan (granted/denied), update storage sesuai OS
      // Tapi jika granted, kita cek storage dlu sapa tau user pernah matiin manual di app
      const osPermission = await checkPermission();
      const existing = await AsyncStorage.getItem('@notification_permission');

      if (osPermission === false) {
         await AsyncStorage.setItem('@notification_permission', 'false');
         return false;
      }

      if (osPermission === true) {
         // Jika OS ijinkan, tapi di storage belum ada, set true
         if (existing === null) {
            await AsyncStorage.setItem('@notification_permission', 'true');
            return true;
         }
         // Jika OS ijinkan dan di storage ada, ikuti storage (toggle manual user)
         return existing === 'true';
      }

      return false;
   } catch (err) {
      console.warn('Error requesting notification permissions:', err);
      return false;
   }
};

export const getToken = async () => {
   try {
      const mess = await initializeFirebase();
      if (!mess) return null;

      // pakai modular API
      const token = await getMessagingToken(mess);
      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();
   }, []);
};
