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

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/hospital.dart';
import 'package:test_sa/models/new_models/gas_refill_model.dart';
import 'package:test_sa/models/timer_model.dart';
import 'package:test_sa/models/user.dart';

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

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

  //reset provider data
  void reset() {
    items = null;
    nextPage = true;
    stateCode = null;
    hospital = null;
    building = null;
    floor = null;
    department = 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<GasRefillModel>? items;

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

  GasRefillModel? gasRefillModel;

  Future<GasRefillModel?> getGasRefillObjectById(num id, {bool refresh = false}) async {
    if (refresh) {
      return gasRefillModel;
    }
    try {
      gasRefillModel = null;
      Response response = await ApiManager.instance.get(URLs.getGasRefillById + "?gasRefillId=$id");
      if (response.statusCode >= 200 && response.statusCode < 300) {
        gasRefillModel = GasRefillModel.fromJson(json.decode(response.body)["data"]);
        notifyListeners();
        return gasRefillModel;
      } else {
        return null;
      }
    } catch (error) {
      return null;
    }
  }

  Future<GasRefillModel?> assignEngineerToHimself(num id) async {
    try {
      Response response = await ApiManager.instance.post(URLs.gasRefillAssignEngineerToHimself, body: {"gasRefillId": id});
      if (response.statusCode >= 200 && response.statusCode < 300) {
        gasRefillModel = GasRefillModel.fromJson(json.decode(response.body)["data"]);
        return gasRefillModel;
      } else {
        return null;
      }
    } catch (error) {
      return null;
    }
  }

  Future<GasRefillModel?> engineerReject(Map<String, dynamic> body) async {
    try {
      Response response = await ApiManager.instance.post(URLs.gasRefillEngineerReject, body: body);
      if (response.statusCode >= 200 && response.statusCode < 300) {
        gasRefillModel = GasRefillModel.fromJson(json.decode(response.body)["data"]);
        return gasRefillModel;
      } else {
        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> getRequests({
    required String host,
    required User user,
    required bool mostRecent,
  }) async {
    if (isLoading == true) return -2;
    isLoading = true;
    if (items?.isEmpty ?? true) notifyListeners();
    late Response response;

    Map<String, dynamic> body = {};
    body["pageNumber"] = (items?.length ?? 0) ~/ pageItemNumber + 1;
    body["pageSize"] = pageItemNumber;
    body["mostRecent"] = mostRecent;

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

  Future<void> addGasRefillRequest({
    required BuildContext context,
    required GasRefillModel model,
  }) async {
    late Response response;
    try {
      showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());
      response = await ApiManager.instance.post(URLs.requestGasRefill, body: model.toJson());
      stateCode = response.statusCode;
      if (response.statusCode >= 200 && response.statusCode < 300) {
        if (items != null) {
          reset();
          notifyListeners();
        }
        Fluttertoast.showToast(msg: context.translation.createdSuccessfully);
        Navigator.pop(context);
      } else {
        Fluttertoast.showToast(msg: "${context.translation.failedToCompleteRequest} :${json.decode(response.body)['message']}");
      }
      Navigator.pop(context);
    } catch (error) {
      stateCode = -1;
      notifyListeners();
      Navigator.pop(context);
      print(error);
    }
  }

  Future<void> updateGasRefillRequestByNurse({
    required BuildContext context,
    required GasRefillModel model,
  }) async {
    late Response response;
    try {
      showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());
      response = await ApiManager.instance.post(URLs.updateGasRefillByNurse, body: model.toJson());
      stateCode = response.statusCode;
      if (response.statusCode >= 200 && response.statusCode < 300) {
        if (items != null) {
          reset();
          notifyListeners();
        }
        Fluttertoast.showToast(msg: context.translation.createdSuccessfully);
        Navigator.pop(context);
      } else {
        Fluttertoast.showToast(msg: "${context.translation.failedToCompleteRequest} :${json.decode(response.body)['message']}");
      }
      Navigator.pop(context);
    } catch (error) {
      stateCode = -1;
      notifyListeners();
      Navigator.pop(context);
      print(error);
    }
  }

  Future<bool> updateGasRefill({required int status, required GasRefillModel model}) async {
    isLoading = true;
    Response response;
    try {
      response = await ApiManager.instance.post(URLs.updateGasRefillByEngineer, body: model.toUpdateEngineerPayload(status: status));
      stateCode = response.statusCode;
      isLoading = false;
      notifyListeners();
      if (stateCode == 200) {
        return true;
      }
      return false;
    } catch (error) {
      isLoading = false;
      stateCode = -1;
      notifyListeners();
      return false;
    }
  }

  Future<int> updateModel({
    required String host,
    required User user,
    required GasRefillModel oldModel,
    required GasRefillModel newModel,
  }) async {
    Map<String, dynamic> body = {
      "id": newModel.id,
      "gasRefillNo": newModel.gasRefillNo ?? "",
      "status": newModel.status?.toJson(),
      //"expectedDate": newModel.expectedDate?.toIso8601String(),
      "expectedTime": newModel.expectedDate,
      if (newModel.timer?.startAt != null) "startDate": newModel.timer!.startAt!.toIso8601String(),
      if (newModel.timer?.startAt != null) "startTime": newModel.timer!.startAt!.toIso8601String(),
      if (newModel.timer?.endAt != null) "endDate": newModel.timer!.endAt!.toIso8601String(), if (newModel.timer?.endAt != null) "endTime": newModel.timer!.endAt!.toIso8601String(),
      // "workingHours": ((endDate?.difference(startDate)?.inMinutes ?? 0) / 60),
      'workingHours': newModel.timer?.durationInSecond != null ? newModel.timer!.durationInSecond! / 60 / 60 : newModel.workingHours,
      "assignedEmployee": oldModel.assignedEmployee?.id == null ? null : oldModel.assignedEmployee?.toJson(),
      "site": hospital?.toMap(),
      "building": building?.toJson(includeFloors: false),
      "floor": floor?.toJson(includeDepartments: false),
      "department": department?.toJson(),
      "engSignature": newModel.engSignature,
      "nurseSignature": newModel.nurseSignature,
      "comment": newModel.comment,
    };

    body["gasRefillDetails"] = newModel.gasRefillDetails!
        .map((model) => {
              "gasType": model.gasType?.toJson(),
              "cylinderSize": model.cylinderSize?.toJson(),
              "cylinderType": model.cylinderType?.toJson(),
              "requestedQty": model.requestedQty,
              "deliverdQty": model.deliverdQty,
            })
        .toList();
    log(body.toString());
    late Response response;
    try {
      response = await ApiManager.instance.put(URLs.updateGasRefill, body: body);
      // response = await post(
      //   Uri.parse("$host${URLs.updateGasRefill}/${newModel.id}"),
      //   body: body,
      // );

      stateCode = response.statusCode;
      if (response.statusCode >= 200 && response.statusCode < 300) {
        oldModel.fromGasRefillModel(newModel);
        notifyListeners();
      }
      return response.statusCode;
    } catch (error) {
      return -1;
    }
  }

  Hospital? hospital;
  Buildings? building;
  Floors? floor;
  Departments? department;
  DateTime? expectedDateTime;
//TimerModel timer;
}
