import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart';
import 'package:local_auth/local_auth.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:test_sa/controllers/api_routes/api_manager.dart';
import 'package:test_sa/controllers/api_routes/urls.dart';
import 'package:test_sa/models/enums/user_types.dart';
import 'package:test_sa/models/user.dart';

import '../settings/app_settings.dart';

class SettingProvider extends ChangeNotifier {
  // Check if settings are loaded or not
  bool isLoaded = false;

  // Contain saved user data
  User? user;

  // AssetGroup
  AssetGroup? _assetGroup;
  String? _host;
  String? _language;
  String? _theme;
  String? _speechToText;

  // Other settings
  bool rememberMe = false;
  String username = "";
  String password = "";
  bool isLocalAuthEnable = false;

  bool get isUserFlowMedical => _assetGroup?.id == 1;

  bool get isUserFMS => _assetGroup?.id == 2;
  bool get engineerCanCreateCM => isUserFMS;
  bool get showPriority => !(isUserFMS && user?.type == UsersTypes.normal_user);

  // Local authentication instance
  final LocalAuthentication auth = LocalAuthentication();

  SettingProvider() {
    loadSharedPreferences();
  }

  Future<void> resetSettings() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    user = null;
    _assetGroup = null;
    prefs.remove(ASettings.user);
    prefs.remove(ASettings.localAuth);
    prefs.remove(ASettings.assetGroup);
    notifyListeners();
  }

  Future<void> setUser(User user) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setString(ASettings.user, json.encode(user.toJson()));
    this.user = user;
    notifyListeners();
    selectAssetGroup(user);
  }

  Future<void> setRememberMe(String username, String password, bool rememberMe) async {
    this.rememberMe = rememberMe;
    SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setBool(ASettings.rememberMe, rememberMe);
    await prefs.setString(ASettings.userName, username);
    await prefs.setString(ASettings.password, password);
  }

  void selectAssetGroup(User user) {
    if (user.assetGroups!.length == 1) {
      _assetGroup = user.assetGroups!.first;
    } else {
      int fmIndex = user.assetGroups!.indexWhere((element) => element.id == 1);
      if (fmIndex < 0) {
        _assetGroup = user.assetGroups!.first;
      } else {
        _assetGroup = user.assetGroups![fmIndex];
      }
    }
    setAssetGroup(_assetGroup);
  }

  Future<void> setAssetGroup(AssetGroup? assetGroup) async {
    _assetGroup = assetGroup;
    ApiManager.instance.assetGroup = _assetGroup!;
    notifyListeners();
  }

  String? get host => _host;

  Future<void> setHost(String host) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setString(ASettings.host, host);
    _host = host;
    notifyListeners();
  }

  String? get language => _language;

  AssetGroup? get assetGroup => _assetGroup;

  String? get theme => _theme;

  bool get localAuth => isLocalAuthEnable;

  Future<void> setLanguage(String currentLanguage) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setString(ASettings.language, currentLanguage);
    _language = currentLanguage;
    notifyListeners();
  }

  Future<void> setAuth(bool status) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    isLocalAuthEnable = status;
    prefs.setBool(ASettings.localAuth, isLocalAuthEnable);
    notifyListeners();
  }

  String? get speechToText => _speechToText;

  Future<void> setSpeechToText(String currentLanguage) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setString(ASettings.speechToText, currentLanguage);
    _speechToText = currentLanguage;
    notifyListeners();
  }

  Future<void> setDarkTheme(bool value) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    _theme = value ? "dark" : "light";
    prefs.setString(ASettings.theme, _theme!);
    notifyListeners();
  }

  // Get app setting
  Future<void> loadSharedPreferences() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();

    _language = prefs.getString(ASettings.language) ?? 'en';
    _theme = prefs.getString(ASettings.theme) ?? 'light';
    isLocalAuthEnable = prefs.getBool(ASettings.localAuth) ?? false;
    _speechToText = prefs.getString(ASettings.speechToText) ?? 'ar';

    if (prefs.containsKey(ASettings.user)) {
      String userJson = prefs.getString(ASettings.user)!;
      user = await User.fromJson(json.decode(userJson));
      selectAssetGroup(user!);
    }

    rememberMe = prefs.getBool(ASettings.rememberMe) ?? false;
    username = prefs.getString(ASettings.userName) ?? "";
    password = prefs.getString(ASettings.password) ?? "";

    _host = prefs.getString(ASettings.host) ?? URLs.host1;

    isLoaded = true;
    notifyListeners();
  }

  Future<bool> checkUserTokenValidation(String token) async {
    try {
      final response = await ApiManager.instance.post(
        "${URLs.checkLoginValidation}?token=$token",
        body: <String, dynamic>{},
      );
      return response.statusCode >= 200 && response.statusCode < 300;
    } catch (error) {
      return false;
    }
  }

  Future<bool> checkAppUpdate(String buildNumber, String osType) async {
    Response response;
    bool isValid = false;
    try {
      Map<String, dynamic> body = {"buildNumber": buildNumber, "osType": osType};
      response = await ApiManager.instance.post(URLs.checkAppVersion, body: body);
      if (response.statusCode >= 200 && response.statusCode < 300) {
        isValid = (jsonDecode(response.body)["data"]);
      }
      return isValid;
    } catch (error) {
      return isValid;
    }
  }
}
