import 'dart:convert';
import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.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/extensions/context_extension.dart';
import 'package:test_sa/models/ppm/ppm.dart';
import 'package:test_sa/models/ppm/ppm_search.dart';
import 'package:test_sa/models/user.dart';

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

class PpmProvider extends ChangeNotifier {
  // number of items call in each request
  final pageItemNumber = 12;

  //reset provider data
  void reset() {
    ppms = null;
    nextPage = true;
    stateCode = null;
  }

  // state code of current request to defied error message
  // like 400 customer request failed
  // 500 service not available
  int stateCode;

  // true if there is next page in product list and false if not
  bool nextPage = true;

  // list of user requests
  List<Ppm> ppms;

  // when requests in-process _loading = true
  // done _loading = true
  // failed _loading = false
  bool isLoading;

  PpmSearch visitsSearch = PpmSearch();

  /// 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> getVisits({
    @required String host,
    @required User user,
    // VisitsSearch visitsSearch,
  }) async {
    if (isLoading == true) return -2;
    isLoading = true;
    if (ppms?.isEmpty ?? true) notifyListeners();
    Response response;
    //userId = 397.toString(); // testing id to view data

    try {
      Map<String, dynamic> body = {};
      body.addAll(visitsSearch.toJson());
      body["pageNumber"] = (ppms?.length ?? 0) ~/ pageItemNumber + 1;
      body["pageSize"] = pageItemNumber;

      response = await ApiManager.instance.post(
        URLs.getRegularVisits,
        body: body,
      );
    } catch (error) {
      isLoading = false;
      stateCode = -1;
      notifyListeners();
      return -1;
    }
    stateCode = response.statusCode;
    if (response.statusCode >= 200 && response.statusCode < 300) {
      // client's request was successfully received
      try {
        List requestsListJson = json.decode(response.body)["data"];
        List<Ppm> visits = requestsListJson.map((request) => Ppm.fromJson(request)).toList();
        ppms ??= [];
        ppms.addAll(visits);
        notifyListeners();
        if (visits.length == pageItemNumber) {
          nextPage = true;
        } else {
          nextPage = false;
        }
      } catch (error) {
        log(error ?? "");
        isLoading = false;
        stateCode = -1;
        notifyListeners();
        return -1;
      }
    }
    isLoading = false;
    notifyListeners();
    return response.statusCode;
  }

  Future<Ppm> getPpmById(num id) async {
    try {
      visitsSearch.id = id;
      visitsSearch.pageNumber = 1;
      visitsSearch.pageSize = 3;
      Response response = await ApiManager.instance.post(URLs.getRegularVisits, body: visitsSearch.toJson());

      if (response.statusCode >= 200 && response.statusCode < 300) {
        List requestsListJson = json.decode(response.body)["data"];
        List<Ppm> visits = requestsListJson.map((request) => Ppm.fromJson(request)).toList();
        return visits?.firstWhere((element) => id == element.id, orElse: () => null);
      }
      return null;
    } catch (error) {
      return null;
    }
  }

  /// 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> updateGroupOfVisits({
    @required String host,
    @required User user,
    // VisitsGroup group,
  }) async {
    Response response;

    try {
      Map<String, dynamic> body = {} /*group.toJson()*/;

      response = await ApiManager.instance.post(
        URLs.getRegularVisits,
        body: body,
      );
      stateCode = response.statusCode;
      if (response.statusCode >= 200 && response.statusCode < 300) {
        // client's request was successfully received
        reset();
        notifyListeners();
      }

      return response.statusCode;
    } catch (error) {
      isLoading = false;
      stateCode = -1;
      notifyListeners();
      return -1;
    }
  }

  Future<Ppm> getPentry({String host, User user, int id}) async {
    Response response;
    response = await ApiManager.instance.get("${URLs.getPentry}/$id");
    Ppm pantry;
    if (response.statusCode >= 200 && response.statusCode < 300) {
      pantry = Ppm.fromJson(json.decode(utf8.decode(response.bodyBytes)));
    }
    return pantry;
  }

  Future<int> updatePentry(
    BuildContext context, {
    @required User user,
    @required Ppm ppm,
  }) async {
    try {
      showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());
      Response response;
      Map<String, dynamic> body = ppm.copyWith(assignedEmployeeId: user.userName, tbsTimer: ppm.tbsTimer).toJson();
      response = await ApiManager.instance.put(URLs.updatePentry, body: body);
      if (response.statusCode >= 200 && response.statusCode < 300) {
        reset(); //visit.status = pentry.ppmVisitStatus;
        notifyListeners();
        Fluttertoast.showToast(msg: context.translation.successfulRequestMessage);
        Navigator.of(context).pop();
      } else {
        Fluttertoast.showToast(msg: "${context.translation.failedToCompleteRequest} ${jsonDecode(response.body)["message"]}");
      }
      Navigator.of(context).pop();
      return response.statusCode;
    } catch (error) {
      return -1;
    }
  }
}
