import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:generp/Models/VersionsResponse.dart';

import 'package:generp/Notifiers/loginNotifier.dart';
import 'package:generp/Utils/SharedpreferencesService.dart';
import 'package:generp/screens/HomeScreen.dart';
import 'package:generp/screens/LoginScreen.dart';
import 'package:generp/screens/UpdatePasswordScreen.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:provider/provider.dart';
import 'package:url_launcher/url_launcher.dart';

import '../services/api_calling.dart';

class SplashVersionNotifier extends ChangeNotifier {
  VersionsResponse? versionsResponse;
  Map<String, String> _packagedetails = {};

  VersionsResponse? get versionDetails => versionsResponse;

  Map<String, String> get packageDetails => _packagedetails;

  Future<void> initPackageInfo() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    _packagedetails = {
      "Version": packageInfo.version,
      "App Name": packageInfo.appName,
      "Package Name": packageInfo.packageName,
      "Build Number": packageInfo.buildNumber,
    };
    if (kDebugMode) {
      print("Package Info: $_packagedetails");
    }
    notifyListeners();
  }

  Future<void> handleVersionCheck(context) async {
    if (_packagedetails.isEmpty) {
      await initPackageInfo();
    }
    var loginProvider = Provider.of<Loginnotifier>(context, listen: false);

    var loginStatus = await SharedpreferencesService().getInt("loginStatus");
    // print("login status: ${loginStatus}");
    // print("login status provider: ${loginProvider.loginStatus}");
    final int currentBuild =
        int.parse(_packagedetails["Build Number"] ?? "0") ?? 0;
    try {
      final data = await ApiCalling.checkAppVersionApi();

      if (data != null) {
        if (kDebugMode) {
          print("Current Build: $currentBuild");
          print("Server Response: ${data.latestVersionCode}");
        }
        if (Platform.isAndroid &&
            currentBuild < (data.latestVersionCode ?? 0)) {
          // print("Update");
          AppUpdateDialouge(context, data.url!, data.releaseNotes!);
        } else if (Platform.isIOS &&
            currentBuild < (data.iosLatestVersionCode ?? 0)) {
          // print("Update");
          AppUpdateDialouge(context, data.iosUrl!, data.iosReleaseNotes!);
        } else {
          // Version is up to date
          if (loginStatus == 0) {
            Navigator.of(
              context,
            ).push(MaterialPageRoute(builder: (context) => LoginScreen()));
          } else {
            getSessiondetailsApiFunction(
              context,
            ); // make sure this is accessible
          }
        }

        notifyListeners();
      } else {
        debugPrint("Version check returned null data.");
      }
    } catch (e) {
      debugPrint("Version check failed: $e");
    }
  }

  Future<void> getSessiondetailsApiFunction(context) async {
    var session = await SharedpreferencesService().getString("Session_id");
    var empId = await SharedpreferencesService().getString("UserId");
    try {
      final data = await ApiCalling.CheckSessionExistsApi(empId, session);
      if (data != null) {
        if (data.sessionExists == 1) {
          // print("geos session");
          if (data.updatePasswordRequired == 0) {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => MyHomePage(),
                settings: RouteSettings(name: "MyHomePage"),
              ),
            );
          } else if (data.updatePasswordRequired == 1) {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => UpdatePassword(),
                settings: RouteSettings(name: "UpdatePassword"),
              ),
            );
          }
        } else {
          // print("goes here");
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => LoginScreen(),
              settings: RouteSettings(name: "LoginScreen"),
            ),
          );
          // toast(context,
          //     "Your Session has been expired, Please Login Again");
        }
        notifyListeners();
      } else {
        //toast(context,"Something went wrong, Please try again later!")
      }
    } on Error catch (e) {
      print(e.toString());
    }
  }

  Future AppUpdateDialouge(context, String apkurl, String note) async {
    return await showDialog<bool>(
          context: context,
          builder:
              (context) => AlertDialog(
                title: Text(
                  'App Update Available!',
                  style: TextStyle(fontWeight: FontWeight.w500),
                ),
                content: Text(note),
                actions: [
                  const SizedBox(height: 16),
                  TextButton(
                    style: ButtonStyle(
                      backgroundColor: WidgetStateProperty.all(Colors.white),
                      overlayColor: WidgetStateProperty.all(Colors.white70),
                    ),
                    onPressed: () async {
                      if (await canLaunchUrl(Uri.parse(apkurl))) {
                        await launchUrl(
                          Uri.parse(apkurl),
                          mode: LaunchMode.externalApplication,
                        );
                      }
                    },
                    child: Text(
                      "UPDATE",
                      style: TextStyle(fontWeight: FontWeight.w500),
                    ),
                  ),
                ],
                elevation: 30.0,
              ),
          barrierDismissible: false,
        ) ??
        false;
  }
}
