import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:http/http.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/new_models/general_response_model.dart';
import 'package:test_sa/models/new_models/update_password.dart';
import 'package:test_sa/models/new_models/verify_otp_model.dart';
import 'package:test_sa/models/user.dart';
import 'package:test_sa/new_views/swipe_module/models/swipe_model.dart';
import 'package:test_sa/new_views/swipe_module/models/swipe_transaction_history.dart';
import 'package:test_sa/new_views/swipe_module/models/swipe_transaction_model.dart';

import '../../../new_views/common_widgets/app_lazy_loading.dart';

class UserProvider extends ChangeNotifier {
  //reset provider data
  void reset() {
    _user = null;
    ApiManager.instance.user = user;
    _loading = false;
  }

  // contain user data
  // when user not login or register _user = null
  User? _user;

  User? get user => _user;

  File? profileImage;

  VerifyOtpModel _verifyOtpModel= VerifyOtpModel();
  SwipeTransaction _swipeTransactionModel = SwipeTransaction();
  List<SwipeHistory> _swipeHistory = [];

  SwipeTransaction get swipeTransactionModel => _swipeTransactionModel;

  List<SwipeHistory> get swipeHistory => _swipeHistory;

  set swipeHistory(List<SwipeHistory> value) {
    _swipeHistory = value;
    notifyListeners();
  }

  set swipeTransactionModel(SwipeTransaction value) {
    _swipeTransactionModel = value;
    notifyListeners();
  }

  VerifyOtpModel get verifyOtpModel => _verifyOtpModel;

  set verifyOtpModel(VerifyOtpModel value) {
    _verifyOtpModel = value;
    notifyListeners();
  }

  void setUser(User user) {
    _user = user;
    ApiManager.instance.user = user;
    notifyListeners();
  }

  // when login or register in-process _login = true
  // when login or register is done or not start = false
  bool _loading = false;

  bool get isLoading => _loading;

  bool isUserConfirmSwipe = false;

  set isLoading(bool isLoading) {
    _loading = isLoading;
    notifyListeners();
  }

  /// sign in with user - need (email or phone) and password;
  /// return -2 if request in progress
  /// return -1 if error happen when sending request
  /// return state code if request complete may be 200, 404 or 403
  /// for more details check http state manager
  /// lib\controllers\http_status_manger\http_status_manger.dart
  Future<int> login({required BuildContext context, required User user}) async {
    if (_loading == true) return -2;
    _loading = true;
    notifyListeners();
    Response response;
    try {
      showDialog(context: context, barrierDismissible: false, builder: (context) =>  const AppLazyLoading());
      response = await ApiManager.instance.post(URLs.login, body: await user.toLoginJson());
      _loading = false;
      if (response.statusCode >= 200 && response.statusCode < 300) {
        // client's request was successfully received
        _user = User.fromJson(jsonDecode(response.body));
        _user!.profilePhotoName = URLs.getFileUrl(_user!.profilePhotoName);
        ApiManager.instance.user = _user;
        notifyListeners();
        Navigator.pop(context);
        return response.statusCode;
      }
      notifyListeners();
      Navigator.pop(context);
      return response.statusCode;
    } catch (error) {
      //  debugPrint(error);
      Navigator.pop(context);
      _loading = false;
      notifyListeners();
      return -1;
    }
  }

  /// sign up with User object;
  /// return -2 if request in progress
  /// return -1 if error happen when sending request
  /// return state code if request complete may be 200, 404 or 403
  /// for more details about state codes check http state manager
  /// lib\controllers\http_status_manger\http_status_manger.dart
  // Future<int> register({
  //   required String host,
  //   required User user,
  // }) async {
  //   if (_loading == true) return -2;
  //   _loading = true;
  //   notifyListeners();
  //   Response response;
  //   try {
  //     response = await ApiManager.instance.post(
  //       URLs.register,
  //       body: await user.toLoginJson(),
  //     );
  //   } catch (error) {
  //     _loading = false;
  //     notifyListeners();
  //     return -1;
  //   }
  //   _loading = false;
  //   notifyListeners();
  //   if (response.statusCode >= 200 && response.statusCode < 300) {
  //     // client's request was successfully received
  //     _user = User.fromJson(jsonDecode(utf8.decode(response.bodyBytes))[0]);
  //     _user!.clientId = user.clientId;
  //     _user!.clientName = user.clientName;
  //     notifyListeners();
  //     return response.statusCode;
  //   }
  //   return response.statusCode;
  // }
  Future<GeneralResponseModel> sendForgetPasswordOtp({required BuildContext context, required String employeeId}) async {
    GeneralResponseModel generalResponseModel = GeneralResponseModel(responseCode: -1);
    if (_loading == true) return generalResponseModel;
    _loading = true;
    notifyListeners();
    Response response;
    try {
      showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());
      response = await ApiManager.instance.postWithOutBody(URLs.sendForgetPasswordOtp + '?employeeId=$employeeId', showLoading: false);
      generalResponseModel = GeneralResponseModel.fromJson(json.decode(response.body));
      _loading = false;
      if (response.statusCode >= 200 && response.statusCode < 300) {
        notifyListeners();
        Navigator.pop(context);
        return generalResponseModel;
      }
      notifyListeners();
      Navigator.pop(context);
      return generalResponseModel;
    } catch (error) {
      //  debugPrint(error);
      Navigator.pop(context);
      _loading = false;
      notifyListeners();
      return generalResponseModel;
    }
  }

  Future<GeneralResponseModel> forgetPasswordValidateOtp({required BuildContext context, required String employeeId, required String otp}) async {
    GeneralResponseModel generalResponseModel = GeneralResponseModel(responseCode: -1);
    // if (_loading == true) return generalResponseModel;
    _loading = true;
    notifyListeners();
    Response response;
    try {
      showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());
      response = await ApiManager.instance.postWithOutBody(
        URLs.sendForgetPasswordValidateOtp + '?employeeId=$employeeId&otp=$otp',
      );
      generalResponseModel = GeneralResponseModel.fromJson(json.decode(response.body));
      _loading = false;
      if (response.statusCode >= 200 && response.statusCode < 300) {
        if (generalResponseModel.data != null) {
          verifyOtpModel = VerifyOtpModel.fromJson(generalResponseModel.data);
        }
        notifyListeners();
        Navigator.pop(context);
        return generalResponseModel;
      }
      notifyListeners();
      Navigator.pop(context);
      return generalResponseModel;
    } catch (error) {
      //  debugPrint(error);
      Navigator.pop(context);
      _loading = false;
      notifyListeners();
      return generalResponseModel;
    }
  }

  Future<GeneralResponseModel> updateNewPassword({required BuildContext context, required  UpdatePasswordModel updatePasswordModel}) async {
    GeneralResponseModel generalResponseModel = GeneralResponseModel(responseCode: -1);
    if (_loading == true) return generalResponseModel;
    _loading = true;
    notifyListeners();
    Response response;
    try {
      showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());
      response = await ApiManager.instance.post(URLs.updateNewPassword, body: updatePasswordModel.toJson());
      generalResponseModel = GeneralResponseModel.fromJson(json.decode(response.body));
      _loading = false;
      if (response.statusCode >= 200 && response.statusCode < 300) {
        notifyListeners();
        Navigator.pop(context);
        return generalResponseModel;
      }
      notifyListeners();
      Navigator.pop(context);
      return generalResponseModel;
    } catch (error) {
      //  debugPrint(error);
      Navigator.pop(context);
      _loading = false;
      notifyListeners();
      return generalResponseModel;
    }
  }
  Future<int> uploadProfileImage(String userId, File image) async {
    if (_loading == true) return -2;
    _loading = true;
    notifyListeners();
    Response response;
    try {
      Map<String, dynamic> body = {
        "userId": userId,
        "imageEmployee": "${image.path.split("/").last}|${base64Encode(image.readAsBytesSync())}",
      };
      response = await ApiManager.instance.post(URLs.updateProfileImage, body: body);
      if (response.statusCode >= 200 && response.statusCode < 300) {
        profileImage = image;
        String imageId = jsonDecode(response.body)["data"];
        _user!.profilePhotoName = URLs.getFileUrl(imageId);
        ApiManager.instance.user = _user;
      }
      _loading = false;
      notifyListeners();
      return response.statusCode;
    } catch (error) {
      _loading = false;
      notifyListeners();
      return -1;
    }
  }
  Future<SwipeModel> makeSwipe({required Swipe model}) async {
    isLoading = true;
    SwipeModel swipeResponse = SwipeModel(data: false, message: '', responseCode: 0, isSuccess: false);
    notifyListeners();
    Response response;
    // try {
      response = await ApiManager.instance.post(URLs.swipeUrl, body: model.toJson(), showToast: false);
      swipeResponse = SwipeModel.fromJson(json.decode(response.body));

      if (response.statusCode >= 200 && response.statusCode < 300) {
        isUserConfirmSwipe = true;
        await getSwipeLastTransaction(userId: user!.userID!);
        notifyListeners();
      }

      notifyListeners();
      return swipeResponse;
    // } catch (error) {
    //   notifyListeners();
    //   return swipeResponse;
    // }
  }

  Future<int> getSwipeLastTransaction({required String userId}) async {
    isLoading = true;
    notifyListeners();
    Response response;
    var body = {
      "userId": userId,
    };
    try {
      response = await ApiManager.instance.post(URLs.getSwipeLastTransactionUrl, body: body);

      if (response.statusCode >= 200 && response.statusCode < 300) {
        swipeTransactionModel = SwipeTransaction.fromJson(json.decode(response.body)['data']);
      }
      notifyListeners();
      return response.statusCode;
    } catch (error) {
      notifyListeners();
      return -1;
    }
  }

  Future<int> getSwipeTransactionHistory({required String userId, required DateTime  dateFrom,required  DateTime dateTo}) async {
    isLoading = true;
    notifyListeners();
    Response response;
    var body = {
      "userId": userId,
      "dateFrom": dateFrom.toIso8601String(),
      "dateTo": dateTo.toIso8601String(),
      "IsSucces":true,
    };
    try {
      response = await ApiManager.instance.post(URLs.getSwipeTransactionHistoryUrl, body: body);

      if (response.statusCode >= 200 && response.statusCode < 300) {
        List dataList = GeneralResponseModel.fromJson(json.decode(response.body)).data;
        swipeHistory = List.generate(dataList.length, (index) => SwipeHistory.fromJson(dataList[index]));
      }
      isLoading = false;
      notifyListeners();
      return response.statusCode;
    } catch (error) {
      isLoading = false;
      notifyListeners();
      return -1;
    }
  }

// Future<int> updateProfile({
//   required String host,
//   required User user,
// }) async {
//   if (_loading == true) return -2;
//   _loading = true;
//   notifyListeners();
//   Response response;
//
//   Map<String, dynamic> jsonObject = {};
//   jsonObject["uid"] = user.id;
//   jsonObject["token"] = user.token;
//   if (user.departmentId != _user.departmentId) jsonObject["department"] = user.departmentId;
//   // if (user.whatsApp != _user.whatsApp) jsonObject["whatsapp"] = user.whatsApp;
//   if (user.phoneNumber != _user.phoneNumber) jsonObject["phone"] = user.phoneNumber;
//   try {
//     response = response = await ApiManager.instance.post(
//       URLs.login,
//       body: jsonObject,
//     );
//   } catch (error) {
//     _loading = false;
//     notifyListeners();
//     return -1;
//   }
//
//   _loading = false;
//   notifyListeners();
//
//   if (response.statusCode >= 200 && response.statusCode < 300) {
//     // client's request was successfully received
//     _user = User.fromJson(jsonDecode(utf8.decode(response.bodyBytes))[0]);
//     _user.clientId = user.clientId;
//     _user.clientName = user.clientName;
//     _user.departmentName = user.departmentName;
//     _user.departmentId = user.departmentId;
//     notifyListeners();
//     return response.statusCode;
//   }
//   return response.statusCode;
// }
}
