import 'dart:io';

import 'package:firebase_remote_config/firebase_remote_config.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:injectable/injectable.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:url_launcher/url_launcher_string.dart';

@singleton
class AppUpdateService {
  Future<void> checkForUpdate(BuildContext context) async {
    final remoteConfig = FirebaseRemoteConfig.instance;

    await remoteConfig.setConfigSettings(RemoteConfigSettings(
      fetchTimeout: const Duration(seconds: 10),
      minimumFetchInterval: const Duration(seconds: 1),
    ));

    await remoteConfig.fetchAndActivate();

    final minBuildNumber = remoteConfig.getInt(Platform.isIOS?'min_build_number_staff_ios':'min_build_number_staff_android');
    final canSkip = remoteConfig.getBool('can_skip_staff');
    final canIgnore = remoteConfig.getBool('can_ignore_staff');
    final message = remoteConfig.getString('message_staff');

    final packageInfo = await PackageInfo.fromPlatform();
    final currentBuildNumber = int.parse(packageInfo.buildNumber);

    final prefs = await SharedPreferences.getInstance();
    final skippedVersion = prefs.getInt('skipped_version') ?? 0;

    if (minBuildNumber > currentBuildNumber &&
        minBuildNumber > skippedVersion) {
      await _showUpdateDialog(context, message, canSkip, canIgnore, minBuildNumber);
    }
  }

  _showUpdateDialog(
      BuildContext context, String message, bool canSkip, bool canIgnore, int minBuildNumber) {
    return showDialog(
      context: context,
      barrierDismissible: canIgnore,
      builder: (BuildContext context) {
        if (Theme.of(context).platform == TargetPlatform.iOS) {
          return WillPopScope(
            onWillPop: () async => canIgnore,
            child: CupertinoAlertDialog(
              title: const Text('Update Available'),
              content: Text(
                  message),
              actions: <Widget>[
                if (canSkip)
                  CupertinoDialogAction(
                    child: const Text('Skip this version'),
                    onPressed: () async {
                      final prefs = await SharedPreferences.getInstance();
                      await prefs.setInt('skipped_version', minBuildNumber);
                      Navigator.of(context).pop();
                    },
                  ),
                CupertinoDialogAction(
                  onPressed:
                      canIgnore ? () => Navigator.of(context).pop() : null,
                  child: const Text('Maybe later'),
                ),
                CupertinoDialogAction(
                  child: const Text('Update'),
                  onPressed: () async {
                    var url = dotenv.env['IOS_STORE_URL'] ??
                        '';
                    if (await canLaunchUrlString(url)) {
                      await launchUrlString(url);
                    } else {
                      throw 'Could not launch $url';
                    }
                  },
                ),
              ],
            ),
          );
        } else {
          return WillPopScope(
            onWillPop: () async => canIgnore,
            child: AlertDialog(
              title: const Text('Update Available'),
              content: Text(
                  message),
              actions: <Widget>[
                if (canSkip)
                  TextButton(
                    child: const Text('Skip this version'),
                    onPressed: () async {
                      final prefs = await SharedPreferences.getInstance();
                      await prefs.setInt('skipped_version', minBuildNumber);
                      Navigator.of(context).pop();
                    },
                  ),
                TextButton(
                  onPressed:
                      canIgnore ? () => Navigator.of(context).pop() : null,
                  child: const Text('Maybe later'),
                ),
                TextButton(
                  child: const Text('Update'),
                  onPressed: () async {
                    var url = dotenv.env['ANDROID_STORE_URL'] ??
                        '';
                    if (await canLaunchUrlString(url)) {
                      await launchUrlString(url);
                    } else {
                      throw 'Could not launch $url';
                    }

                  },
                ),
              ],
            ),
          );
        }
      },
    );
  }
}
