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/device/asset.dart';
import 'package:test_sa/models/device/asset_transfer.dart';
import 'package:test_sa/models/user.dart';

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

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

  AssetTransfer transferModel = AssetTransfer();

  //reset provider data
  void reset() {
    items = null;
    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<AssetTransfer>? 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<AssetTransfer> itemsPage = listJson.map((request) => AssetTransfer.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<AssetTransfer?> 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 AssetTransfer.fromJson(json.decode(response.body)["data"]);
      }
      return null;
    } catch (error) {
      print(error);
      return null;
    }
  }

  Future<void> createRequest({
    required BuildContext context,
    required AssetTransfer assetDestination,
    required Asset asset,
  }) async {
    Response response;
    try {
      showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());
      response = await ApiManager.instance.post(URLs.requestDeviceTransfer, body: assetDestination.transferBody(asset: asset));
      stateCode = response.statusCode;
      if (response.statusCode >= 200 && response.statusCode < 300) {
        if (items != null) {
          items!.insert(0, AssetTransfer.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);
      print(error);
    }
  }

  Future<int> updateRequest(BuildContext context, {required AssetTransfer assetTransfer, required bool isSender}) async {
    Response response;
    try {
      showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());
      response = await ApiManager.instance.put(URLs.updateDeviceTransfer, body: assetTransfer.toJson());

      //print(response.body);
      // print("${newModel.engSignature}.png");
      // response = await post(
      //   Uri.parse("$host${URLs.updateDeviceTransfer}/$requestId"),
      //   body: body,
      // );

      stateCode = response.statusCode;
      if (response.statusCode >= 200 && response.statusCode < 300) {
        reset();
        // Fluttertoast.showToast(msg: context.translation.successfulRequestMessage);
        Navigator.of(context).pop();
        // oldModel.fromDeviceTransfer(
        //   DeviceTransfer.fromJson(
        //       json.decode(utf8.decode(response.bodyBytes))[0]
        //   )
        // );
        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);
      print(error);
      return -1;
    }
  }

  bool _isLocalUrl(String? url) {
    if (url?.isEmpty ?? true) return false;
    return url!.startsWith("/") || url.startsWith("file://") || url.substring(1).startsWith(':\\');
  }
}
