import 'dart:async';
import 'dart:io';
import 'package:doctor_app_flutter/config/config.dart';
import 'package:doctor_app_flutter/core/service/authentication_service.dart';
import 'package:doctor_app_flutter/core/viewModel/authentication_view_model.dart';
import 'package:doctor_app_flutter/locator.dart';
import 'package:doctor_app_flutter/screens/auth/login_screen.dart';
import 'package:doctor_app_flutter/screens/auth/verification_methods_screen.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:safe_device/safe_device.dart';

import '../../core/service/NavigationService.dart';
import '../../unsafe_device.dart' show UnsafeDevice;
class SplashScreen extends StatefulWidget {
  @override
  _SplashScreenState createState() => _SplashScreenState();
}

class _SplashScreenState extends State<SplashScreen> {
  final FirebaseMessaging _firebaseMessaging = FirebaseMessaging.instance;
  late AuthenticationViewModel _authViewModel;
  bool isJailBroken = false;
  bool isRealDevice = true;
  bool isDevelopmentModeEnable = false;

  @override
  void initState() {
    super.initState();
    AppGlobal.CONTEX = context;
    if (!kReleaseMode) {
      checkDeviceSafety();
    }
    Timer(Duration(seconds: 2, milliseconds: 500), () async {
      if (isJailBroken || !isRealDevice || !isSafeDevice) {
        // Critical threat detected - navigate to unsafe device page
        Navigator.of(locator.get<NavigationService>().navigatorKey.currentContext!).pushAndRemoveUntil(
          MaterialPageRoute(builder: (_) => const UnsafeDevice()),
              (route) => false, // Remove all previous routes
        );
      }else {
        _initializeApp();
      }
    });

  }
  void checkDeviceSafety() {
    try {
      SafeDevice.isJailBroken.then((bool value) {
        isJailBroken = value;
      });
      SafeDevice.isJailBrokenCustom.then((bool value) {
        isJailBroken = value;
      });
      SafeDevice.isRealDevice.then((value) {
        isRealDevice = value;
      });
    } catch (error) {
      print(error);
    }
  }

  Future<void> _initializeApp() async {
    try {
      final String? token = await _getFirebaseToken();

      _authViewModel = Provider.of<AuthenticationViewModel>(context, listen: false);
      await _authViewModel.initializeApp(token: token);

      _navigateBasedOnAuthState();
    } catch (e) {
      // Handle error and fallback to login
      _navigateToLogin();
    }
  }

  Future<String?> _getFirebaseToken() async {
    try {
      await Firebase.initializeApp();
      await  Future.delayed(Duration(seconds: 1), () {
      });
      if (Platform.isIOS) {
        // Request permissions first
        final settings = await _firebaseMessaging.requestPermission(
          alert: true,
          announcement: false,
          badge: true,
          carPlay: false,
          criticalAlert: false,
          provisional: false,
          sound: true,
        );

        debugPrint('Notification permissions: ${settings.authorizationStatus}');

        // Get both FCM and APNS tokens
        final fcmToken = await _firebaseMessaging.getToken();
        debugPrint("FCM Token: $fcmToken");

      //   // APNS token might not be immediately available
      //   String? apnsToken;
      //   int retries = 0;
      //   while (apnsToken == null && retries < 3) {
      //     apnsToken = await _firebaseMessaging.getAPNSToken();
      //     if (apnsToken == null) {
      //       await Future.delayed(Duration(milliseconds: 500));
      //       retries++;
      //     }
      //   }
      // print(apnsToken);
        return fcmToken; // Fallback to FCM token if APNS is null
      } else {
        return await _firebaseMessaging.getToken();
      }
    } catch (e) {
      debugPrint("Failed to get FCM token: $e");
      return null;
    }
  }
  void _navigateBasedOnAuthState() {
    if (_authViewModel.status == APP_STATUS.UNVERIFIED) {
      Navigator.pushReplacement(
        context,
        MaterialPageRoute(builder: (_) => VerificationMethodsScreen()),
      );
    } else if (_authViewModel.status == APP_STATUS.UNAUTHENTICATED) {
      _navigateToLogin();
    } else {
      _navigateToLogin();
    }
  }

  void _navigateToLogin() {
    Navigator.pushReplacement(
      context,
      MaterialPageRoute(builder: (_) => LoginScreen()),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xffF8F8F8),
      body: Center(
        child: Image.asset('assets/images/dr_app_logo.png'),
      ),
    );
  }
}