/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 * @flow
 */

import React, { Component } from 'react'
import { StatusBar, StyleSheet, Text, TouchableOpacity, Platform } from 'react-native'
import MainNav from './src/navigation/MainNav'
import messaging from "@react-native-firebase/messaging"
import notifee from '@notifee/react-native';
import { persistor, store } from './src/redux/store'
import { Provider } from 'react-redux'
import { registerDevice } from './src/api/UserApi'
import { appSetDevice, appSetPushToken } from './src/redux/app/action'
import { setLanguage, setToken } from 'src/api/api'
import { PersistGate } from 'redux-persist/integration/react'
import Toast from 'react-native-toast-message'

import SplashScreen from 'react-native-splash-screen'
import { setBaseUrlByServerMode } from './src/api/api'
import { Settings } from 'react-native-fbsdk-next';

Text.defaultProps = Text.defaultProps || {}
Text.defaultProps.allowFontScaling = false

if (TouchableOpacity.defaultProps == null) TouchableOpacity.defaultProps = {}
TouchableOpacity.defaultProps.activeOpacity = 0.7

// setApiStore(store)
class App extends Component {

  constructor(props) {
    super(props)
    this._setDataFromInitState = this._setDataFromInitState.bind(this)
  }

  componentDidMount = async () => {
    SplashScreen.hide()
    Settings.initializeSDK();

    // Test FCM token
    try {
      const token = await messaging().getToken();
      console.log('Current FCM Token:', token);
      console.log('Token length:', token ? token.length : 0);

      // ตรวจสอบ permission status
      const authStatus = await messaging().requestPermission();
      console.log('Permission status:', authStatus);

    } catch (error) {
      console.log('Error getting FCM token:', error);
    }
  }

  // เพิ่ม method ใหม่สำหรับ setup listeners
  setupNotificationListeners = () => {
    // Foreground message handler
    messaging().onMessage(async remoteMessage => {
      console.log('Foreground notification:', remoteMessage);
      
      // Create a channel (required for Android)
      const channelId = await notifee.createChannel({
        id: 'default',
        name: 'Default Channel',
      });

      // Display a notification
      await notifee.displayNotification({
        title: remoteMessage.notification?.title || 'New Notification',
        body: remoteMessage.notification?.body || '',
        android: {
          channelId,
          pressAction: {
            id: 'default',
          },
        },
        ios: {
          foregroundPresentationOptions: {
            banner: true,
            badge: true,
            sound: true,
          },
        },
      });
    });

    // Background/Quit message handler
    messaging().setBackgroundMessageHandler(async remoteMessage => {
      console.log('Background notification:', remoteMessage);
    });

    // Notification opened app handler
    messaging().onNotificationOpenedApp(remoteMessage => {
      console.log('Notification opened app:', remoteMessage);
    });

    // Check if app was opened from notification
    messaging()
      .getInitialNotification()
      .then(remoteMessage => {
        if (remoteMessage) {
          console.log('App opened from notification:', remoteMessage);
        }
      });
  }

  initNotification = async () => {
    try {
      await this.setPermission()

      if (Platform.OS === 'ios') {
        let apnsToken = await messaging().getAPNSToken();
        let retry = 0;
        while (!apnsToken && retry < 10) {
          console.log('Waiting for APNs token...');
          await new Promise(resolve => setTimeout(resolve, 1000));
          apnsToken = await messaging().getAPNSToken();
          retry++;
        }
        console.log('APNs Token:', apnsToken);

        if (!apnsToken) {
          console.log('Failed to get APNs token after retries');
          // Decide if we want to return here or try anyway. 
          // Usually if APNs is missing, getToken will fail.
        }
      }

      // ใช้ getToken() แทน getAPNSToken()
      const fcmToken = await messaging().getToken();
      console.log('FCM Token:', fcmToken);

      if (fcmToken) {
        store.dispatch(appSetPushToken(fcmToken))
        const resultSendDevice = await registerDevice(fcmToken)
        console.log('register_device result =>', resultSendDevice)
        if (resultSendDevice.ok && resultSendDevice.data.success) {
          store.dispatch(appSetDevice(resultSendDevice.data.device))
        }
      }

      // เพิ่ม notification listeners
      this.setupNotificationListeners();

    } catch (error) {
      console.log('initNotification error:', error);
    }
  }

  setPermission = async () => {
    try {
      await messaging().registerDeviceForRemoteMessages();
      const authStatus = await messaging().requestPermission();
      const enabled = authStatus === messaging.AuthorizationStatus.AUTHORIZED || authStatus === messaging.AuthorizationStatus.PROVISIONAL;
      if (!enabled) {
        await messaging().requestPermission()
      }
    } catch (error) {
      console.log('error', error)
    }
  }

  _setDataFromInitState() {
    const appState = store.getState().app
    let device = appState.device

    setBaseUrlByServerMode(appState.server_mode)

    if (appState.token) {
      setToken(appState.token)
    }
    if (appState.lang) {
      setLanguage(appState.lang)
    }

    if (!device) {
      this.initNotification()
    } else {
      this.setPermission()
      this.setupNotificationListeners()
    }

    console.log('app state', appState, device)

  }

  render() {

    return (
      <Provider store={store}>
        <PersistGate persistor={persistor} loading={null} onBeforeLift={this._setDataFromInitState}>
          <StatusBar barStyle="light-content" />
          <MainNav />
        </PersistGate>
        <Toast />
      </Provider>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
})

export default App

