import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:nearle/views/helpers/constants/Font_constant.dart';
import 'dart:io';
import 'package:url_launcher/url_launcher.dart';
import 'package:nearle/views/helpers/constants/Colorconstants.dart';
import 'package:new_version_plus/new_version_plus.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:nearle/views/introscreens/introscreen.dart';
import 'package:nearle/widget/Bottom_page.dart';
import 'package:nearle/views/onboardscreens/signin_banner.dart';

class UpdateScreen extends StatefulWidget {
  final bool mIsForceUpdate;
  final String mCurrentVersion;
  final String mUpdateVersion;

  const UpdateScreen({
    super.key,
    this.mIsForceUpdate = true,
    required this.mCurrentVersion,
    required this.mUpdateVersion,
  });

  @override
  State<UpdateScreen> createState() => _UpdateScreenState();
}

class _UpdateScreenState extends State<UpdateScreen>
    with WidgetsBindingObserver {
  bool _isCheckingVersion = false;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed && !_isCheckingVersion) {
      checkVersionAndNavigate();
    }
  }

  Future<void> checkVersionAndNavigate() async {
    if (_isCheckingVersion) return;
    _isCheckingVersion = true;

    try {
      await Future.delayed(const Duration(seconds: 1));

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

      final status = await newVersion.getVersionStatus();

      if (status != null) {
        if (!status.canUpdate) {
          if (mounted) {
            _navigateToNextScreen();
          }
        }
      }
    } catch (e) {
      print("Error checking version: $e");
    } finally {
      _isCheckingVersion = false;
    }
  }

  Future<void> _navigateToNextScreen() async {
    final prefs = await SharedPreferences.getInstance();
    final isLoggedOut = prefs.getBool('logged_out') == true;
    final savedUserId = prefs.getInt('userid');

    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 {
      Get.offAll(() => Introscreen());
    }
  }

  @override
  Widget build(BuildContext context) {
    double h = Get.height;
    double w = Get.width;

    return WillPopScope(
      onWillPop: () async {
        if (widget.mIsForceUpdate) {
          SystemNavigator.pop();
          return false;
        }
        return false;
      },
      child: Scaffold(
        backgroundColor: Colors.white,
        extendBodyBehindAppBar: true,
        appBar: AppBar(
          backgroundColor: Colors.transparent,
          elevation: 0,
          scrolledUnderElevation: 0,
          surfaceTintColor: Colors.transparent,
          systemOverlayStyle: const SystemUiOverlayStyle(
            statusBarColor: Colors.transparent,
            statusBarIconBrightness: Brightness.dark,
            statusBarBrightness: Brightness.light,
          ),
        ),

        body: SafeArea(
          top: true,
          bottom: false, // Bottom safe area handled in bottomNavigationBar
          child: LayoutBuilder(
            builder: (context, constraints) {
              return SingleChildScrollView(
                child: ConstrainedBox(
                  constraints: BoxConstraints(
                    minHeight: constraints.maxHeight,
                  ),
                  child: IntrinsicHeight(
                    child: Column(
                      children: [
                        /// top spacing (responsive)
                        SizedBox(height: h * 0.06),

                        /// 🚀 Image (auto scales)
                        Padding(
                          padding: EdgeInsets.symmetric(horizontal: w * 0.08),
                          child: Image.asset(
                            "assets/images/update.png",
                            height: h * 0.28,
                            fit: BoxFit.contain,
                          ),
                        ),

                        SizedBox(height: h * 0.03),

                        /// 🔥 Title
                        Text(
                          "A New Update is Available!",
                          style: TextStyle(
                            fontSize: h * 0.025,
                            fontWeight: FontWeight.bold,
                            fontFamily: FontConstants.fontFamily,
                            color: Colors.black87,
                          ),
                          textAlign: TextAlign.center,
                        ),

                        SizedBox(height: h * 0.015),

                        /// 📄 Subtitle
                        Padding(
                          padding: EdgeInsets.symmetric(horizontal: w * 0.08),
                          child: Text(
                            "New features are here to make your app experience even smoother and more user-friendly!",
                            textAlign: TextAlign.center,
                            style: TextStyle(
                              fontSize: h * 0.018,
                              color: Colors.grey,
                              height: 1.4,
                              fontFamily: FontConstants.fontFamily,
                            ),
                          ),
                        ),

                        SizedBox(height: h * 0.03),

                        /// Version Text
                        Text(
                          "Available version: ${widget.mUpdateVersion}",
                          style: TextStyle(
                            fontSize: h * 0.017,
                            color: Colors.grey,
                            fontFamily: FontConstants.fontFamily,
                          ),
                        ),

                        Spacer(), // pushes content for large screens
                      ],
                    ),
                  ),
                ),
              );
            },
          ),
        ),

        /// ⭐ Bottom Button (fixed, responsive) with bottom safe area
        bottomNavigationBar: SafeArea(
          top: false,
          bottom: true,
          child: Padding(
            padding: EdgeInsets.fromLTRB(
              w * 0.06,
              0,
              w * 0.06,
              h * 0.03,
            ),
            child: SizedBox(
              width: double.infinity,
              height: h * 0.065,
              child: ElevatedButton(
                style: ElevatedButton.styleFrom(
                  backgroundColor: ColorConstants.primaryColor,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10),
                  ),
                ),
                onPressed: () => downloadActions(),
                child: Text(
                  "Update Now",
                  style: TextStyle(
                    fontSize: h * 0.022,
                    fontFamily: FontConstants.fontFamily,
                    color: Colors.white,
                  ),
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }

  void downloadActions() async {
    String url;
    var s = Platform.isAndroid ? "Android" : "Ios";

    if (s == "Android") {
      url = 'https://play.google.com/store/apps/details?id=com.nearle.partner';
    } else {
      url = 'https://apps.apple.com/us/app/nearle/id1596895375ls=1';
    }

    final uri = Uri.parse(url);

    if (await canLaunchUrl(uri)) {
      await launchUrl(uri, mode: LaunchMode.externalApplication);
    } else {
      throw 'Could not launch App';
    }
  }
}
