import 'dart:developer';
import 'dart:async';
import 'dart:convert';

import 'package:appsflyer_sdk/appsflyer_sdk.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_config/flutter_config.dart';
import 'package:go_router/go_router.dart';
import 'package:mo_app/core/widgets/scaffold/main_scaffold.dart';
import 'package:mo_app/features/auth/bloc/auth_bloc.dart';

import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:mo_app/firebase_options.dart';

import 'package:location/location.dart';
import 'package:mo_app/features/chat/bloc/chat_bloc.dart';
import 'package:mo_app/routes.dart';

import 'package:rxdart/rxdart.dart';

class SplashScreen extends StatefulWidget {
  const SplashScreen({super.key});

  @override
  State<SplashScreen> createState() => _SplashScreenState();
}

class _SplashScreenState extends State<SplashScreen> {
  void initAppsFlyerOptions() async {
    try {
      final appFlyerKey = FlutterConfig.get('APPFLYER_DEV_KEY');
      final afAppId = FlutterConfig.get('AF_APP_ID');

      Map appsFlyerOptions = {
        "afDevKey": appFlyerKey,
        "afAppId": afAppId, // iOS only
        "isDebug": false, // Set to false in production
      };
      AppsflyerSdk appsflyerSdk = AppsflyerSdk(appsFlyerOptions);

      appsflyerSdk.initSdk(
        registerConversionDataCallback: false,
        registerOnAppOpenAttributionCallback: false,
        registerOnDeepLinkingCallback: true,
      );
      print('coming jere');
      appsflyerSdk.onAppOpenAttribution((message) {
        print("onAppOpenAttribution: $message");
        // Handle deep link logic here
      });

      appsflyerSdk.onInstallConversionData((conversionData) {
        print("onInstallConversionData: $conversionData");
        // Handle deep link logic here, especially for deferred deep links
      });

      appsflyerSdk.onDeepLinking((DeepLinkResult deepLinkResult) {
        print("onDeepLinking: $deepLinkResult");
        switch (deepLinkResult.status) {
          case Status.FOUND:
            print(deepLinkResult.deepLink?.toString());
            print("deep link value: ${deepLinkResult.deepLink?.deepLinkValue}");
            break;
          case Status.NOT_FOUND:
            print("deep link not found");
            break;
          case Status.ERROR:
            print("deep link error: ${deepLinkResult.error}");
            break;
          case Status.PARSE_ERROR:
            print("deep link status parsing error");
            break;
        }
      });
    } catch (e) {
      print('appsflyer error ${e.toString()}');
    }
  }

  @override
  void initState() {
    super.initState();
    _onAppStart();

    initAppsFlyerOptions();
  }

  Future<void> _firebaseMessagingBackgroundHandler(
    RemoteMessage message,
  ) async {
    await Firebase.initializeApp();
    print("Handling a background message: ${message.messageId}");
  }

  Future<void> _onAppStart() async {
    await _initializeFirebase();
    // Simulate some initial app load tasks
    // Trigger the initial load event
    BlocProvider.of<AuthBloc>(context).add(OnAppInitialLoadEvent());
  }

  Future<void> _initializeFirebase() async {
    await Firebase.initializeApp(
      options: DefaultFirebaseOptions.currentPlatform,
    );

    FirebaseMessaging messaging = FirebaseMessaging.instance;

    NotificationSettings settings = await messaging.requestPermission(
      alert: true,
      announcement: false,
      badge: true,
      carPlay: false,
      criticalAlert: false,
      provisional: false,
      sound: true,
    );

    await Location().requestPermission();

    String? token = await messaging.getToken();

    _setupFirebaseMessagingListeners();

    await Future.delayed(const Duration(microseconds: 500));

    globalRouter.go('/home');
  }

  void _setupFirebaseMessagingListeners() {
    final messageStreamController = BehaviorSubject<RemoteMessage>();

    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      messageStreamController.sink.add(message);

      if (message.data.containsKey('stringifiedData')) {
        final String stringifiedData = message.data['stringifiedData'];
        final notificationData = jsonDecode(stringifiedData);
        if (notificationData.containsKey('route')) {
          ChatBloc.instance.handleReceivedNotification();
        }
      }
    });

    FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
      try {
        final String? stringifiedData = message.data["stringifiedData"];

        if (stringifiedData != null) {
          final actionData = jsonDecode(stringifiedData);

          if (actionData.containsKey('route')) {
            final String routeName = actionData['route'];
            // Use GoRouter to navigate
            globalRouter.go('/messageList');
          }
        } else {
          log('Notification data does not contain "stringifiedData".');
        }
      } catch (e) {
        print(e);
      }
    });

    FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
  }

  @override
  Widget build(BuildContext context) {
    return BlocListener<AuthBloc, AuthState>(
      listener: (authContent, state) {
        // Navigate based on authentication status
        if (state.authStatus == AuthenticationStatus.authenticated ||
            state.authStatus == AuthenticationStatus.unauthenticated) {
          // Obtain the GoRouter instance from the context and navigate to the root
          GoRouter.of(context).go('/home');
        }
      },
      child: MainScaffold(
        body: Column(
          children: [
            const Expanded(
              flex: 2,
              child: SizedBox(),
            ),
            Expanded(
              flex: 3,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Image.asset(
                    "assets/images/app-images/mo_logo.png",
                    width: MediaQuery.of(context).size.width * 0.5,
                  ),
                  const SizedBox(
                    height: 12,
                  ),
                  const Text(
                    "That's More like it",
                    style: TextStyle(
                      fontWeight: FontWeight.w300,
                      fontSize: 14,
                      color: Color(0xFF555555),
                    ),
                  ),
                ],
              ),
            ),
            const Expanded(
              flex: 2,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    "MO Unleashed",
                    style: TextStyle(
                      fontWeight: FontWeight.w300,
                      fontSize: 20,
                    ),
                  ),
                  Text(
                    "Version 1.0.0",
                    style: TextStyle(
                      fontWeight: FontWeight.w300,
                      fontSize: 10,
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}