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/extensions/string_extensions.dart';
import 'package:test_sa/models/device/asset.dart';
import 'package:test_sa/models/device/device_transfer.dart';
import 'package:test_sa/models/new_models/site.dart';
import 'package:test_sa/models/service_request/pending_service_request_model.dart';
import 'package:test_sa/models/user.dart';

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

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

  DeviceTransfer transferModel = DeviceTransfer();
  bool isSiteLoading = false;
  Asset? _internalAssetDestination = Asset();

  Asset? get internalAssetDestination => _internalAssetDestination;

  set internalAssetDestination(Asset? value) {
    _internalAssetDestination = value;
    notifyListeners();
  } //reset provider data

  void reset() {
    items = null;
    isSiteLoading = false;
    nextPage = true;
    stateCode = null;
    hospital = null;
    building = null;
    floor = null;
    department = null;
    room = "";
    startDate = null;
    endDate = 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<DeviceTransfer>? items;

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

  Hospital? hospital;
  Buildings? building;
  Floors? floor;
  Departments? department;
  String room = "";
  DateTime? startDate;
  DateTime? endDate;

  /// return -2 if request in progress
  /// return -1if 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,
  }) async {
    if (isLoading == true) return -2;
    isLoading = true;
    if (items?.isEmpty ?? true) notifyListeners();
    late Response response;
    try {
      Map<String, dynamic> body = {};
      body["pageNumber"] = (items?.length ?? 0) ~/ pageItemNumber + 1;
      body["pageSize"] = pageItemNumber;
      body.addAll(transferModel.toJson());

      response = await ApiManager.instance.post(URLs.getDeviceTransfer, body: body);

      stateCode = response.statusCode;
      if (stateCode! >= 200 && stateCode! < 300) {
        // client's request was successfully received
        List listJson = json.decode(response.body)["data"];
        List<DeviceTransfer> itemsPage = listJson.map((request) => DeviceTransfer.fromJson(request)).toList();
        items ??= [];
        items!.addAll(itemsPage.toSet().toList());
        notifyListeners();
        if (itemsPage.length == pageItemNumber) {
          nextPage = true;
        } else {
          nextPage = false;
        }
      }
      isLoading = false;
      notifyListeners();
      return response.statusCode;
    } catch (error) {
      isLoading = false;
      stateCode = -1;
      notifyListeners();
      return -1;
    }
  }

  Future<DeviceTransfer?> getRequestById({int? assetTransferId}) async {
    Response response;
    try {
      response = await ApiManager.instance.get(
        URLs.getAssetTransferById + "?assetTransferId=$assetTransferId",
        enableToastMessage: false,
      );
      if (response.statusCode >= 200 && response.statusCode < 300) {
        return DeviceTransfer.fromJson(json.decode(response.body)["data"]);
      }
      return null;
    } catch (error) {
      print(error);
      return null;
    }
  }

  Future<PendingAssetServiceRequest?> checkAssetPendingRequest(int assetId) async {
    Response response;
    try {
      response = await ApiManager.instance.post(URLs.CheckIfAssetHasAnotherServiceRequest + "?assetId=$assetId", body: {});
      stateCode = response.statusCode;
      if (response.statusCode >= 200 && response.statusCode < 300) {}
      return PendingAssetServiceRequest.fromJson(json.decode(response.body)["data"]);
    } catch (error) {
      "Please Try Again\n$error".addTranslation.showToast;
      return null;
    }
  }

  Future<void> createRequest({
    required BuildContext context,
    required DeviceTransfer model,
  }) async {
    Response response;
    try {
      showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());
      response = await ApiManager.instance.post(URLs.createAssetTransferRequest, body: model.toCreateAssetTransferJson());
      stateCode = response.statusCode;
      if (response.statusCode >= 200 && response.statusCode < 300) {
        if (items != null) {
          items!.insert(0, DeviceTransfer.fromJson(json.decode(utf8.decode(response.bodyBytes))[0]));
          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) {
      Navigator.pop(context);
      stateCode = -1;
      notifyListeners();
      print(error);
    }
  }

  Future<int> updateRequest(BuildContext context, {required DeviceTransfer model}) async {
    Response response;
    try {
      showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());
      response = await ApiManager.instance.post(URLs.updateDeviceTransfer, body: model.toEngineerUpdateJson());
      stateCode = response.statusCode;
      if (response.statusCode >= 200 && response.statusCode < 300) {
        reset();
        Navigator.of(context).pop();
        notifyListeners();
      } else {
        Fluttertoast.showToast(msg: "${context.translation.failedToCompleteRequest} :${json.decode(response.body)['message']}");
      }
      Navigator.pop(context, true);
      return response.statusCode;
    } catch (error) {
      Navigator.pop(context);
      log('error $error');
      return -1;
    }
  }

  Future getSiteData({required int? siteId}) async {
    isSiteLoading = true;
    notifyListeners();
    try {
      Response response = await ApiManager.instance.get(URLs.getSiteAutoCompleteWithoutConditionSites + "?id=$siteId");
      stateCode = response.statusCode;
      if (response.statusCode >= 200 && response.statusCode < 300) {
        List? siteData = json.decode(response.body)["data"];
        if (siteData != null && siteData.isNotEmpty) {
          internalAssetDestination?.site = Site.fromJson(siteData.first);
        }
        // internalAssetDestination?.building = internalAssetDestination?.site?.buildings?.firstWhere((element) => element.value == internalAssetDestination?.installationBuilding?.value, orElse: () => Building());
        // taskRequestModel?.floor = taskRequestModel?.building?.floors?.firstWhere((element) => element.value == taskRequestModel?.installationFloor?.value, orElse: () => Floor());
        // taskRequestModel?.department = taskRequestModel?.floor?.departments?.firstWhere((element) => element.name == taskRequestModel?.installationDepartment?.name, orElse: () => Department());
      }
      isSiteLoading = false;
      notifyListeners();
      return response.statusCode;
    } catch (error) {
      isSiteLoading = false;
      stateCode = -1;
      notifyListeners();
      return -1;
    }
  }
}
