import 'dart:convert';

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/comment.dart';

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

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

  //reset provider data
  void reset() {
    comments = [];
    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<Comment> comments = [];

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

  /// 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> getComments({required String callId}) async {
    if (isLoading == true) return -2;
    isLoading = true;
    notifyListeners();
    late Response response;
    try {
      response = await ApiManager.instance.get(URLs.getComments + "?callRequestId=$callId");

      stateCode = response.statusCode;
      if (response.statusCode >= 200 && response.statusCode < 300) {
        List requestsListJson = json.decode(response.body)["data"];
        List<Comment> commentsPage = requestsListJson.map((request) => Comment.fromJson(request)).toList();
        comments ??= [];
        comments.addAll(commentsPage);
        if (commentsPage.length == pageItemNumber) {
          nextPage = true;
        } else {
          nextPage = false;
        }
      }
      isLoading = false;
      notifyListeners();
      return response.statusCode;
    } catch (error) {
      print(error);
      isLoading = false;
      stateCode = -1;
      notifyListeners();
      return -1;
    }
  }

  /// 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> addComment(BuildContext context, {required Comment comment}) async {
    if (isLoading == true) return -2;
    isLoading = true;
    late Response response;
    try {
      comment.id = 0;
      showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());
      response = await ApiManager.instance.post(URLs.addComment, body: comment.toJson());

      stateCode = response.statusCode;
      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"]}");
      }
      isLoading = false;
      notifyListeners();
      Navigator.of(context).pop();
      return response.statusCode;
    } catch (error) {
      print(error);
      isLoading = false;
      stateCode = -1;
      notifyListeners();
      return -1;
    }
  }
}
