import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'dart:async';

import 'package:nearle/views/helpers/constants/Colorconstants.dart';
import 'package:nearle/views/introscreens/introscreen.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:nearle/widget/Bottom_page.dart';
import 'package:nearle/views/onboardscreens/Sign_in.dart';
import 'package:nearle/views/onboardscreens/signin_banner.dart';
import 'package:nearle/views/updatescreen/UpdateScreen.dart';
import 'package:new_version_plus/new_version_plus.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:nearle/views/onboardscreens/Mpin.dart';
import 'package:nearle/controllers/auth.dart';

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

  @override
  State<Splashscreen> createState() => _SplashscreenState();
}

class _SplashscreenState extends State<Splashscreen> {
  late final ImageProvider _logoProvider;
  bool _imagePrecached = false;
  bool _hasCheckedUpdate = false;

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

    _logoProvider = const AssetImage("assets/images/nearlesplash2.png");

    WidgetsBinding.instance.addPostFrameCallback((_) async {
      try {
        await precacheImage(_logoProvider, context);
        if (mounted) {
          setState(() {
            _imagePrecached = true;
          });
        }
      } catch (e) {
        if (mounted) {
          setState(() {
            _imagePrecached = true;
          });
        }
      }
    });

    // FAST splash: 1 second
    Timer(const Duration(seconds: 1), () {
      if (mounted) {
        _startNextStep();
      }
    });
  }

  // FAST second step: 0.2 sec
  void _startNextStep() {
    Timer(const Duration(milliseconds: 200), () {
      if (mounted && !_hasCheckedUpdate) {
        _checkForUpdateAndNavigate();
      }
    });
  }

  Future<void> _checkForUpdateAndNavigate() async {
    if (_hasCheckedUpdate) return;
    _hasCheckedUpdate = true;

    try {
      final newVersion = NewVersionPlus(
        iOSId: '284882215',
        androidId: "com.nearle.partner",
      );

      final status = await newVersion.getVersionStatus();

      if (status != null && status.canUpdate) {
        if (mounted) {
          Get.offAll(
            () => UpdateScreen(
              mCurrentVersion: status.localVersion,
              mUpdateVersion: status.storeVersion,
              mIsForceUpdate: true,
            ),
            transition: Transition.fadeIn,
          );
        }
        return;
      }
    } catch (e) {}

    _navigateToNextScreen();
  }

  Future<void> _navigateToNextScreen() async {
    final prefs = await SharedPreferences.getInstance();
    final bool isLoggedOut = prefs.getBool('logged_out') ?? false;
    final bool hasSeenIntro = prefs.getBool('has_seen_intro') ?? false;
    final int? savedUserId = prefs.getInt('userid');

    // 🚀 Check for App Update (Force Login if version changed)
    try {
      final packageInfo = await PackageInfo.fromPlatform();
      final currentVersion = packageInfo.version;
      final lastRunVersion = prefs.getString('last_run_version');

      if (lastRunVersion != null && lastRunVersion != currentVersion) {
        debugPrint(
          '[SPLASH] App update detected: $lastRunVersion -> $currentVersion. Forcing re-verification.',
        );

        final String? savedPhone = prefs.getString('contactno');
        final int? savedUserId = prefs.getInt('userid');

        // Update stored version
        await prefs.setString('last_run_version', currentVersion);

        if (savedUserId != null && savedPhone != null && savedPhone.isNotEmpty) {
          debugPrint('[SPLASH] User was logged in. Redirecting to MPIN page.');

          // Initialize AuthController and set the phone for MPIN verification
          final auth = Get.put(AuthController());
          auth.currentPhone = savedPhone;

          // Clear sensitive session data to force re-verification
          await prefs.remove('userid');
          await prefs.remove('partnerid');
          await prefs.remove('onduty');
          await prefs.setBool('logged_out', true);

          if (mounted) {
            Get.offAll(() => Mpin());
          }
          return;
        } else {
          debugPrint('[SPLASH] User was not logged in. Redirecting to Sign In.');
          if (mounted) {
            Get.offAll(() => const SignIn());
          }
          return;
        }
      }
      // Save current version for next run
      await prefs.setString('last_run_version', currentVersion);
    } catch (e) {
      debugPrint('[SPLASH] Version check error: $e');
    }

    if (!mounted) return;

    if (!isLoggedOut && savedUserId != null && savedUserId > 0) {
      final onduty = prefs.getInt('onduty') ?? 0;

      if (onduty == 0) {
        Get.offAll(() => const SigninBanner());
      } else {
        Get.offAll(() => const BottomPage());
      }
    } else {
      if (hasSeenIntro) {
        Get.offAll(() => const SignIn());
      } else {
        Get.offAll(() => Introscreen());
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ColorConstants.secondaryColor,
      body: SafeArea(
        child: Center(
          child: _imagePrecached
              ? Image(
                  image: _logoProvider,
                  fit: BoxFit.contain,
                )
              : const SizedBox(),
        ),
      ),
    );
  }
}
