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

import 'package:flutter/material.dart';
import 'package:http/src/response.dart';
import 'package:test_sa/controllers/api_routes/api_manager.dart';
import 'package:test_sa/controllers/api_routes/urls.dart';
import 'package:test_sa/models/generic_attachment_model.dart';
import 'package:test_sa/models/helper_data_models/asset_retired/asset_retired_model.dart';
import 'package:test_sa/models/helper_data_models/maintenance_request/activity_maintenance_model.dart';
import 'package:test_sa/models/helper_data_models/spare_part/activity_spare_part_model.dart';
import 'package:test_sa/models/helper_data_models/workorder/work_order_helper_models.dart';
import 'package:test_sa/models/new_models/arrival_verification_type_model.dart';
import 'package:test_sa/models/new_models/dashboard_detail.dart';
import 'package:test_sa/models/new_models/work_order_detail_model.dart';
import 'package:test_sa/models/service_request/spare_parts.dart';
import 'package:test_sa/models/service_request/supplier_details.dart';
import 'package:test_sa/models/wo_by_asset_id_model.dart';

import 'cm_request_utils.dart';

class CMDetailProvider extends ChangeNotifier {
  final pageItemNumber = 10;

  int lastVisitedRequestActivityId = -1;

  void reset() {
    nextPage = true;
    stateCode = null;
  }

  DateTime timerStartTime = DateTime(0, 0, 0, 0, 0, 0); // Start from 00:00:00
  Timer? timer;
  bool isTimerRunning = false;
  bool _isNurseVerifiedEngineerArrival = false;

  bool get isNurseVerifiedEngineerArrival => _isNurseVerifiedEngineerArrival;

  set isNurseVerifiedEngineerArrival(bool value) {
    _isNurseVerifiedEngineerArrival = value;
    notifyListeners();
  }

  bool refreshTimer = true;

  void startTimer() {
    if (isTimerRunning) return;
    resetTimer();
    markedAsFixed = false;
    timer = Timer.periodic(const Duration(seconds: 1), (Timer t) {
      timerStartTime = timerStartTime.add(const Duration(seconds: 1));
      if (refreshTimer) {
        notifyListeners();
      }
      // Notify UI when time is updated
    });
    isTimerRunning = true;
    notifyListeners(); // Notify UI when timer starts
  }

  void stopTimer() {
    resetTimer();
    timer?.cancel();
    isTimerRunning = false;
    if (!markedAsFixed) {
      engineerStopTimer();
    }
    notifyListeners(); // Notify UI when timer stops
  }

  void resetTimer() {
    timerStartTime = DateTime(0, 0, 0, 0, 0, 0); // Reset to 00:00:00
    notifyListeners();
  }

  // Getter to get the current time
  DateTime get currentTime => timerStartTime;

  bool _isLoading = false;
  bool _isArrivalLoading = false;
  bool _isVerifyArrivalBottomSheetOpen = false;

  bool get isVerifyArrivalBottomSheetOpen => _isVerifyArrivalBottomSheetOpen;

  set isVerifyArrivalBottomSheetOpen(bool value) {
    _isVerifyArrivalBottomSheetOpen = value;
    notifyListeners();
  }

  bool get isArrivalLoading => _isArrivalLoading;

  set isArrivalLoading(bool value) {
    _isArrivalLoading = value;
    notifyListeners();
  }

  bool get isLoading => _isLoading;

  set isLoading(bool value) {
    _isLoading = value;
    notifyListeners();
  }

  //UI models
  WorkOrderDetail? currentWorkOrder;
  AssetRetiredHelperModel? assetRetiredHelperModel = AssetRetiredHelperModel();
  ActivityMaintenanceHelperModel? activityMaintenanceHelperModel = ActivityMaintenanceHelperModel();
  SparePartHelperModel? sparePartHelperModel;
  List<StoreAvailability> _storeAvailability = [];

  List<StoreAvailability> get storeAvailability => _storeAvailability;

  set storeAvailability(List<StoreAvailability> value) {
    _storeAvailability = value;
    notifyListeners();
  }

  FixRemotelyHelperModel? fixRemotelyHelperModel = FixRemotelyHelperModel();
  NeedVisitHelperModel? needVisitHelperModel = NeedVisitHelperModel();
  NurseActionHelperModel? nurseActionHelperModel;
  EngineerRejectHelperModel? engineerRejectHelperModel = EngineerRejectHelperModel();
  EngineerUpdateWorkOrderHelperModel? engineerUpdateWorkOrderHelperModel = EngineerUpdateWorkOrderHelperModel();
  WorkOrderCostModel? workOrderCostModel;
  WorkOrderHelperModel? workOrderHelperModel;
  List<ArrivalTypeData> arrivalTypeList = [];

  void updateAssetRetiredHelperModel(AssetRetiredHelperModel? value) {
    assetRetiredHelperModel = value;
    notifyListeners();
  }

  void updateActivityMaintenanceHelperModel(ActivityMaintenanceHelperModel? value) {
    activityMaintenanceHelperModel = value;
    notifyListeners();
  }

  void updateSparePartHelperModel(SparePartHelperModel? value) {
    sparePartHelperModel = value;
    notifyListeners();
  }

  void updateFixRemotelyHelperModel(FixRemotelyHelperModel? value) {
    fixRemotelyHelperModel = value;
    notifyListeners();
  }

  void updateNeedVisitHelperModel(NeedVisitHelperModel? value) {
    needVisitHelperModel = value;
    log("value:${value!.visitDate.toString()}");
    notifyListeners();
  }

  void updateNurseActionHelperModel(NurseActionHelperModel? value) {
    nurseActionHelperModel = value;
    notifyListeners();
  }

  void updateEngineerRejectHelperModel(EngineerRejectHelperModel? value) {
    engineerRejectHelperModel = value;
    notifyListeners();
  }

  void updateEngineerUpdateWorkOrderHelperModel(EngineerUpdateWorkOrderHelperModel? value) {
    engineerUpdateWorkOrderHelperModel = value;
    notifyListeners();
  }

  void updateWorkOrderHelperModel(WorkOrderHelperModel? value) {
    workOrderHelperModel = value;
    notifyListeners();
  }

  void updateCurrentWorkOrder(WorkOrderDetail? value) {
    currentWorkOrder = value;
    notifyListeners();
  }

  int? stateCode;

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

  TimeOfDay? get selectedTime => _selectedTime;

  set selectedTime(TimeOfDay? value) {
    _selectedTime = value;
    notifyListeners();
  } // list of user requests

  int _selectedListIndex = 0;

  int get selectedListIndex => _selectedListIndex;

  set selectedListIndex(int value) {
    _selectedListIndex = value;
    notifyListeners();
  }

  bool _isReadOnlyRequest = false;

  bool get isReadOnlyRequest => _isReadOnlyRequest;

  set isReadOnlyRequest(bool value) {
    _isReadOnlyRequest = value;
    notifyListeners();
  } //create workOrder nurse .....

  Future<int> createWorkOrder() async {
    isLoading = true;
    notifyListeners();
    try {
      final response = await ApiManager.instance.post(
        URLs.createWorkOrderUrl,
        body: workOrderHelperModel!.toJson(),
      );
      stateCode = response.statusCode;
      if (response.statusCode >= 200 && response.statusCode < 300) {
        // request.engineerName = employee.name;
      }
      isLoading = false;
      notifyListeners();
      return response.statusCode;
    } catch (error) {
      isLoading = false;
      notifyListeners();
      return -1;
    }
  }

  //getWorkOrderById......
  Future getWorkOrderById({required int id}) async {
    try {
      isLoading = true;
      notifyListeners();
      final response = await ApiManager.instance.get(URLs.getWorkOrderByIdUrl + "?workOrderId=$id");
      stateCode = response.statusCode;
      if (response.statusCode >= 200 && response.statusCode < 300) {
        currentWorkOrder = await WorkOrderDetail.fromJson(json.decode(response.body));
        //need to check on value as id changed on different env.
        if (currentWorkOrder?.data?.status?.value == 3 || currentWorkOrder?.data?.status?.value == 5 || currentWorkOrder?.data?.status?.value == 6) {
          isReadOnlyRequest = true;
        } else {
          isReadOnlyRequest = false;
        }
      } else {
        currentWorkOrder = null;
      }
      isLoading = false;
      notifyListeners();
    } catch (e) {
      log("getWorkOrder [error] : $e");
      isLoading = false;
      currentWorkOrder = null;
      notifyListeners();
      return null;
    }
  }

  //upload workorder attachment by engineer..
  Future addWorkOrderAttachment({required int woId, required List<GenericAttachmentModel> attachments, required List<GenericAttachmentModel> otherAttachment}) async {
    try {
      List<GenericAttachmentModel> woAttachments = [];
      if (otherAttachment.isNotEmpty) {
        woAttachments.addAll(otherAttachment);
      }
      for (var file in attachments) {
        String fileName = CMRequestUtils.isLocalUrl(file.name ?? '') ? ("${file.name ?? ''.split("/").last}|${base64Encode(File(file.name ?? '').readAsBytesSync())}") : file.name ?? '';
        woAttachments.add(GenericAttachmentModel(id: file.id, name: fileName, createdBy: file.createdBy, documentType: file.documentType));
      }

      isLoading = true;
      notifyListeners();
      final response = await ApiManager.instance.post(URLs.uploadWorkOrderAttachmentsUrl, body: WorkOrderHelperModel().toUploadAttachmentJson(woId, woAttachments));
      stateCode = response.statusCode;
      if (response.statusCode >= 200 && response.statusCode < 300) {
        currentWorkOrder = await WorkOrderDetail.fromJson(json.decode(response.body));
      }
      isLoading = false;
      notifyListeners();
    } catch (e) {
      log("getWorkOrder [error] : $e");
      isLoading = false;
      notifyListeners();
      return null;
    }
  }

  //getQrCode......
  Future<String?> getQrCode({required int workOrderId}) async {
    try {
      notifyListeners();
      final response = await ApiManager.instance.get(URLs.getQrCodeUrl + "/$workOrderId");
      stateCode = response.statusCode;
      if (response.statusCode >= 200 && response.statusCode < 300) {
        String base64String = response.body.split(',').last;

        return base64String;
        return response.body;
      }
      isLoading = false;
      notifyListeners();
    } catch (e) {
      log("getQrCode [error] : $e");
      isLoading = false;
      notifyListeners();
      return null;
    }
    return null;
  }

  //engineerAcceptWorkOrder......
  Future<int> engineerAcceptWorkOrder({required String id}) async {
    Response response;
    try {
      final body = {"workOrderId": id};
      isLoading = true;
      notifyListeners();
      response = await ApiManager.instance.post(URLs.engineerAcceptUrl, body: body);
      stateCode = response.statusCode;
      if (response.statusCode >= 200 && response.statusCode < 300) {
        currentWorkOrder = await WorkOrderDetail.fromJson(json.decode(response.body));
      }
      isLoading = false;
      notifyListeners();
      return response.statusCode;
    } catch (e) {
      log("engineer accept  [error] : $e");
      isLoading = false;
      notifyListeners();
      return -1;
    }
  } //engineerAcceptWorkOrder......

  Future<int> engineerAssignWorkOrderToHimself({required String id}) async {
    Response response;
    try {
      final body = {"workOrderId": id};
      isLoading = true;
      notifyListeners();
      response = await ApiManager.instance.post(URLs.engineerAssignHimSelfUrl, body: body);
      stateCode = response.statusCode;
      if (response.statusCode >= 200 && response.statusCode < 300) {
        currentWorkOrder = await WorkOrderDetail.fromJson(json.decode(response.body));
      }
      isLoading = false;
      notifyListeners();
      return response.statusCode;
    } catch (e) {
      log("engineer accept  [error] : $e");
      isLoading = false;
      notifyListeners();
      return -1;
    }
  } //engineerAssignedHimself......

  Future<int> engineerStopTimer() async {
    Response response;
    try {
      final body = {"workOrderId": currentWorkOrder?.data?.requestId};
      isLoading = true;
      notifyListeners();
      response = await ApiManager.instance.post(URLs.engineerStopTimer, body: body);
      stateCode = response.statusCode;
      if (response.statusCode >= 200 && response.statusCode < 300) {}
      isLoading = false;
      notifyListeners();
      return response.statusCode;
    } catch (e) {
      log("engineer accept  [error] : $e");
      isLoading = false;
      notifyListeners();
      return -1;
    }
  }

  Future<bool> switchToIHaveArrived() async {
    Response response;
    try {
      final body = {"workOrderId": currentWorkOrder?.data?.requestId};
      response = await ApiManager.instance.post(URLs.returnToIHaveArrive, body: body);
      stateCode = response.statusCode;
      if (response.statusCode >= 200 && response.statusCode < 300) {
        currentWorkOrder = await WorkOrderDetail.fromJson(json.decode(response.body));
        return true;
      }
      return false;
    } catch (e) {
      return false;
    }
  }

  //engineerRejectWorkOrder......
  Future<int> engineerRejectWorkOrder() async {
    Response response;
    try {
      isLoading = true;
      notifyListeners();
      response = await ApiManager.instance.post(URLs.engineerRejectUrl, body: engineerRejectHelperModel!.toJson());
      stateCode = response.statusCode;
      if (response.statusCode >= 200 && response.statusCode < 300) {
        currentWorkOrder = await WorkOrderDetail.fromJson(json.decode(response.body));
      }
      isLoading = false;
      notifyListeners();
      return response.statusCode;
    } catch (e) {
      log("engineer reject  [error] : $e");
      isLoading = false;
      notifyListeners();
      return -1;
    }
  }

  //engineerFixRemotelyWorkOrder......
  Future<int> engineerFixRemotely() async {
    Response response;
    try {
      isLoading = true;
      notifyListeners();
      response = await ApiManager.instance.post(URLs.engineerFixRemotlyUrl, body: fixRemotelyHelperModel!.toJson());
      stateCode = response.statusCode;
      if (response.statusCode >= 200 && response.statusCode < 300) {
        currentWorkOrder = await WorkOrderDetail.fromJson(json.decode(response.body));
      }
      isLoading = false;
      notifyListeners();
      return response.statusCode;
    } catch (e) {
      log("engineer fix remotely  [error] : $e");
      isLoading = false;
      notifyListeners();
      return -1;
    }
  }

  //engineerNeedAVisitWorkOrder......
  Future<int> engineerNeedVisit() async {
    Response response;
    try {
      isLoading = true;
      notifyListeners();
      response = await ApiManager.instance.post(URLs.engineerNeedVisitUrl, body: needVisitHelperModel!.toJson());
      stateCode = response.statusCode;
      if (response.statusCode >= 200 && response.statusCode < 300) {
        currentWorkOrder = await WorkOrderDetail.fromJson(json.decode(response.body));
      }
      isLoading = false;
      notifyListeners();
      return response.statusCode;
    } catch (e) {
      log("engineer accept  [error] : $e");
      isLoading = false;
      notifyListeners();
      return -1;
    }
  }

  //engineerUpdateNeedAVisitWorkOrder......
  Future<int> engineerUpdateNeedVisit() async {
    Response response;
    try {
      isLoading = true;
      notifyListeners();
      response = await ApiManager.instance.post(URLs.engineerUpdateNeedVisitUrl, body: needVisitHelperModel!.toJson());
      stateCode = response.statusCode;
      if (response.statusCode >= 200 && response.statusCode < 300) {
        currentWorkOrder = await WorkOrderDetail.fromJson(json.decode(response.body));
        notifyListeners();
      }
      isLoading = false;
      notifyListeners();
      return response.statusCode;
    } catch (e) {
      log("engineer accept  [error] : $e");
      isLoading = false;
      notifyListeners();
      return -1;
    }
  }

  bool markedAsFixed = false;

  //engineerMarkAsFixed......
  Future<int> engineerMarkAsFixed({required int workOrderId, required String feedback}) async {
    Response response;
    try {
      isLoading = true;
      notifyListeners();
      Map<String, dynamic> body = {'workOrderId': workOrderId, 'feedback': feedback};
      response = await ApiManager.instance.post(URLs.engineerMarkAsFixUrl, body: body);
      stateCode = response.statusCode;
      if (response.statusCode >= 200 && response.statusCode < 300) {
        currentWorkOrder = await WorkOrderDetail.fromJson(json.decode(response.body));
        markedAsFixed = true;
        stopTimer();
      }
      isLoading = false;
      notifyListeners();
      return response.statusCode;
    } catch (e) {
      log("engineer mark as fixed  [error] : $e");
      isLoading = false;
      notifyListeners();
      return -1;
    }
  }

  Future<int> reOrderActivities({required int workOrderId, required List<Map<String, dynamic>> reOrderActivityDTOs}) async {
    Response response;
    try {
      isLoading = true;
      notifyListeners();
      Map<String, dynamic> body = {'workOrderId': workOrderId, 'reOrderActivityDTOs': reOrderActivityDTOs};
      response = await ApiManager.instance.put(URLs.reOrderActivity, body: body);
      stateCode = response.statusCode;
      if (response.statusCode >= 200 && response.statusCode < 300) {
        currentWorkOrder = await WorkOrderDetail.fromJson(json.decode(response.body));
      }
      isLoading = false;
      notifyListeners();
      return response.statusCode;
    } catch (e) {
      log("engineer mark as fixed  [error] : $e");
      isLoading = false;
      notifyListeners();
      return -1;
    }
  }

  //engineer Confirm Arrive......
  Future<int> engineerConfirmArrival({required int workOrderId, required int verificationTypeId, String? photoInfo, String? otp, String? assetNo, String? workOrderCreatedById}) async {
    Response response;
    try {
      //"workOrderCreatedById": "string"
      Map<String, dynamic> body = {
        "workOrderId": workOrderId,
        "verificationTypeId": verificationTypeId,
        "photoInfo": photoInfo,
        "otp": otp,
        "assetNumber": assetNo,
        "workOrderCreatedById": workOrderCreatedById
      };
      isLoading = true;
      notifyListeners();
      response = await ApiManager.instance.post(URLs.engineerConfirmArriveUrl, body: body);
      stateCode = response.statusCode;
      if (response.statusCode >= 200 && response.statusCode < 300) {
        currentWorkOrder = await WorkOrderDetail.fromJson(json.decode(response.body));
      }
      if (response.statusCode >= 200 && response.statusCode < 300) {}
      isLoading = false;
      notifyListeners();
      return response.statusCode;
    } catch (e) {
      log("engineer accept  [error] : $e");
      isLoading = false;
      notifyListeners();
      return -1;
    }
  }

  //engineer Confirm Arrive......
  Future<int> engineerSetReminder({required int workOrderId, required int reminderId}) async {
    Response response;
    try {
      //"workOrderCreatedById": "string"
      Map<String, dynamic> body = {
        "workOrderId": workOrderId,
        "setReminderId": reminderId,
      };
      isLoading = true;
      notifyListeners();
      response = await ApiManager.instance.post(URLs.engineerSetReminderUrl, body: body);
      stateCode = response.statusCode;
      if (response.statusCode >= 200 && response.statusCode < 300) {
        currentWorkOrder = await WorkOrderDetail.fromJson(json.decode(response.body));
      }
      if (response.statusCode >= 200 && response.statusCode < 300) {}
      isLoading = false;
      notifyListeners();
      return response.statusCode;
    } catch (e) {
      log("engineer accept  [error] : $e");
      isLoading = false;
      notifyListeners();
      return -1;
    }
  }

  //assignEngineerToWorkOrder......
  Future<CommonResponseModel> assignEngineerWorkOrder({required String workOrderId, required String engineerId}) async {
    try {
      final body = {"workOrderId": workOrderId, "assignedEngineerId": engineerId};
      isLoading = true;
      notifyListeners();
      final response = await ApiManager.instance.post(URLs.assignEngineerToWorkOrderUrl, body: body);
      stateCode = response.statusCode;
      CommonResponseModel commonResponseModel = CommonResponseModel();
      if (response.statusCode >= 200 && response.statusCode < 300) {
        commonResponseModel = CommonResponseModel.fromJson(json.decode(response.body));
      }
      isLoading = false;
      notifyListeners();
      return commonResponseModel;
    } catch (e) {
      log("engineer accept  [error] : $e");
      isLoading = false;
      notifyListeners();
      return CommonResponseModel();
    }
  }

  //engineerUpdateWorkOrder......
  Future<bool> engineerUpdateWorkOrder() async {
    isLoading = true;
    Response response;
    try {
      response = await ApiManager.instance.post(URLs.engineerUpdateWorkOrderUrl, body: engineerUpdateWorkOrderHelperModel!.toJson());
      stateCode = response.statusCode;
      isLoading = false;
      notifyListeners();
      if (stateCode == 200) {
        currentWorkOrder = await WorkOrderDetail.fromJson(json.decode(response.body));
        notifyListeners();
        return true;
      }
      return false;
    } catch (error) {
      isLoading = false;
      stateCode = -1;
      notifyListeners();
      return false;
    }
  }

  Future<bool> engineerUpdateCost() async {
    isLoading = true;
    Response response;
    try {
      response = await ApiManager.instance.post(URLs.engineerUpdateCost, body: workOrderCostModel!.toJson());
      stateCode = response.statusCode;
      isLoading = false;
      notifyListeners();
      if (stateCode == 200) {
        currentWorkOrder = await WorkOrderDetail.fromJson(json.decode(response.body));
        notifyListeners();
        return true;
      }
      return false;
    } catch (error) {
      isLoading = false;
      stateCode = -1;
      notifyListeners();
      return false;
    }
  }

  //Nurse confirm reopen
  Future<CommonResponseModel> nurseReject() async {
    try {
      isLoading = true;
      notifyListeners();
      final response = await ApiManager.instance.post(URLs.nurseRejectUrl, body: nurseActionHelperModel!.toJson());
      stateCode = response.statusCode;
      CommonResponseModel commonResponseModel = CommonResponseModel();

      if (response.statusCode >= 200 && response.statusCode < 300) {
        commonResponseModel = CommonResponseModel.fromJson(json.decode(response.body));
      }
      isLoading = false;
      notifyListeners();
      return commonResponseModel;
    } catch (e) {
      log("nurse  reject  [error] : $e");
      isLoading = false;
      notifyListeners();
      return CommonResponseModel();
    }
  }

  //Nurse confirm arrival
  Future<int?> nurseConfirmEngineerArrival({required int workOrderId}) async {
    try {
      Map<String, dynamic> body = {"workOrderId": workOrderId};
      isLoading = true;
      notifyListeners();
      final response = await ApiManager.instance.post(URLs.nurseConfirmEngineerArrivalUrl, body: body);
      stateCode = response.statusCode;
      if (response.statusCode >= 200 && response.statusCode < 300) {
        currentWorkOrder = await WorkOrderDetail.fromJson(json.decode(response.body));
      }
      isLoading = false;
      notifyListeners();
      return stateCode;
    } catch (e) {
      log("nurse  reject  [error] : $e");
      isLoading = false;
      notifyListeners();
      return -1;
    }
  } //Nurse confirm arrival

  Future<int?> nurseRejectEngineerArrival({required int workOrderId}) async {
    try {
      Map<String, dynamic> body = {"workOrderId": workOrderId};
      isLoading = true;
      notifyListeners();
      final response = await ApiManager.instance.post(URLs.nurseRejectEngineerArrivedUrl, body: body);
      stateCode = response.statusCode;
      if (response.statusCode >= 200 && response.statusCode < 300) {
        currentWorkOrder = await WorkOrderDetail.fromJson(json.decode(response.body));
      }
      isLoading = false;
      notifyListeners();
      return stateCode;
    } catch (e) {
      log("nurse  reject  [error] : $e");
      isLoading = false;
      notifyListeners();
      return -1;
    }
  }

  //Nurse confirm close
  Future<WorkOrderDetail?> nurseConfirm() async {
    try {
      isLoading = true;
      notifyListeners();
      final response = await ApiManager.instance.post(URLs.nurseConfirmUrl, body: nurseActionHelperModel!.toJson());

      stateCode = response.statusCode;
      WorkOrderDetail? workOrderDetail;
      if (response.statusCode >= 200 && response.statusCode < 300) {
        workOrderDetail = await WorkOrderDetail.fromJson(json.decode(response.body));
      }
      isLoading = false;
      notifyListeners();
      return workOrderDetail;
    } catch (e) {
      log("engineer accept  [error] : $e");
      isLoading = false;
      notifyListeners();
      return null;
    }
  }

  Future<bool> updateActivitySparePart() async {
    isLoading = true;
    Response response;
    try {
      response = await ApiManager.instance.post(URLs.updateActivitySparePartUrl, body: sparePartHelperModel!.toJson());
      stateCode = response.statusCode;
      isLoading = false;
      notifyListeners();
      if (stateCode == 200) {
        return true;
      }
      return false;
    } catch (error) {
      isLoading = false;
      stateCode = -1;
      notifyListeners();
      return false;
    }
  }

  Future<bool> updateActivityMaintenance() async {
    isLoading = true;
    Response response;
    try {
      response = await ApiManager.instance.put(URLs.updateActivityMaintenanceUrl, body: activityMaintenanceHelperModel!.toJson());
      stateCode = response.statusCode;
      isLoading = false;
      notifyListeners();
      if (stateCode == 200) {
        return true;
      }
      return false;
    } catch (error) {
      isLoading = false;
      stateCode = -1;
      notifyListeners();
      return false;
    }
  }

  Future<List<SuppPersons>> getSupplierEngineerData({required String supplierName}) async {
    try {
      Response response = await ApiManager.instance.get("${URLs.getSuppliersAutoComplete}?searchText=$supplierName");
      stateCode = response.statusCode;
      List<SuppPersons> persons = [];
      if (response.statusCode >= 200 && response.statusCode < 300) {
        List categoriesListJson = json.decode(response.body)["data"][0]['suppPersons'];
        persons = categoriesListJson.map((item) => SuppPersons.fromJson(item)).toList();
      }
      notifyListeners();
      return persons;
    } catch (error) {
      stateCode = -1;
      notifyListeners();
      return [];
    }
  }

  Future<void> getStoreAvailabilityById({required num? partId}) async {
    try {
      isLoading = true;
      notifyListeners();

      final response = await ApiManager.instance.post(
        URLs.getSparePartAvailableQuantity + "?PartId=$partId",
        body: {},
      );

      stateCode = response.statusCode;

      if (response.statusCode >= 200 && response.statusCode < 300) {
        final List<dynamic> data = json.decode(response.body)["data"];
        storeAvailability = data.map((item) => StoreAvailability.fromJson(item)).toList();
      }

      isLoading = false;
      notifyListeners();
    } catch (e) {
      log("getStoreAvalivility  [error] : $e");
      isLoading = false;
      notifyListeners();
    }
  }

  Future<int> deleteActivitySparePart({required int id, required int workOrderId}) async {
    isLoading = true;
    notifyListeners();
    var body = {'id': id, 'workOrderId': workOrderId};
    try {
      final response = await ApiManager.instance.post(URLs.deleteActivitySparePartUrl, body: body);
      stateCode = response.statusCode;
      if (response.statusCode >= 200 && response.statusCode < 300) {
        //map to the model...

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

  Future<int> deleteActivityMaintenance({required int id, required int workOrderId}) async {
    isLoading = true;
    notifyListeners();
    var body = {'id': id, 'workOrderId': workOrderId};
    try {
      final response = await ApiManager.instance.delete(
        URLs.deleteActivityMaintenanceUrl,
        body: body,
      );
      stateCode = response.statusCode;

      if (response.statusCode >= 200 && response.statusCode < 300) {
        //map to the model...
      }
      isLoading = false;
      notifyListeners();
      return response.statusCode;
    } catch (error) {
      isLoading = false;
      notifyListeners();
      return -1;
    }
  }

  Future<bool> createActivitySparePart() async {
    isLoading = true;
    Response response;
    try {
      response = await ApiManager.instance.post(
        URLs.createActivitySparePartUrl,
        body: sparePartHelperModel!.toJson(),
      );
      stateCode = response.statusCode;
      isLoading = false;
      notifyListeners();
      if (stateCode == 200) {
        return true;
      }
      return false;
    } catch (error) {
      isLoading = false;
      stateCode = -1;
      notifyListeners();
      return false;
    }
  }

  Future<bool> createActivityMaintenanceRequest() async {
    isLoading = true;
    Response response;
    try {
      response = await ApiManager.instance.post(
        URLs.createActivityMaintenanceUrl,
        body: activityMaintenanceHelperModel!.toJson(),
      );
      stateCode = response.statusCode;
      isLoading = false;
      notifyListeners();
      if (stateCode == 200) {
        return true;
      }
      return false;
    } catch (error) {
      isLoading = false;
      stateCode = -1;
      notifyListeners();
      return false;
    }
  }

//create asset retired request..
  Future<int> createActivityAssetToBeRetired() async {
    isLoading = true;
    notifyListeners();
    try {
      final response = await ApiManager.instance.post(
        URLs.createActivityAssetToBeRetiredUrl,
        body: assetRetiredHelperModel!.toJson(),
      );
      stateCode = response.statusCode;
      if (response.statusCode >= 200 && response.statusCode < 300) {
        currentWorkOrder = await WorkOrderDetail.fromJson(json.decode(response.body));
      }
      isLoading = false;
      notifyListeners();
      return response.statusCode;
    } catch (error) {
      isLoading = false;
      notifyListeners();
      return -1;
    }
  }

  //get Arrival type......
  Future<int> getArrivalVerificationType() async {
    try {
      isArrivalLoading = true;
      notifyListeners();
      final response = await ApiManager.instance.get(URLs.getArrivalVerificationTypeUrl);
      stateCode = response.statusCode;
      if (response.statusCode >= 200 && response.statusCode < 300) {
        ArrivalVerificationTypeModel arrivalVerificationTypeModel = ArrivalVerificationTypeModel.fromJson(json.decode(response.body));
        arrivalTypeList = arrivalVerificationTypeModel.data ?? [];
      }
      isArrivalLoading = false;
      notifyListeners();
      return response.statusCode;
    } catch (e) {
      log("getArrivalVerifaction [error] : $e");
      isArrivalLoading = false;
      notifyListeners();
      return -1;
    }
  }

  //send otp..
  Future<int?> sendOtp({required int workOrderId}) async {
    isLoading = true;
    notifyListeners();
    try {
      final response = await ApiManager.instance.post(URLs.sendOtpUrl + "$workOrderId", body: {}, showToast: false);
      stateCode = response.statusCode;
      if (response.statusCode >= 200 && response.statusCode < 300) {}
      isLoading = false;
      notifyListeners();
      return response.statusCode;
    } catch (error) {
      isLoading = false;
      notifyListeners();
      return -1;
    }
  }

  //verify otp..
  Future<int> verifyOtp({required int workOrderId, required String otpCode}) async {
    isLoading = true;
    notifyListeners();
    try {
      final response = await ApiManager.instance.post(URLs.verifyOtpUrl + '$workOrderId&$otpCode', body: {});

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

  Future<List<WoByAssetIdModel>> getWorkOrderByAssetId(String searchText, int assetId) async {
    late Response response;
    try {
      response = await ApiManager.instance.post(URLs.workOrderByAssetIdAutoComplete, body: {"pageSize": 1, "pageNumber": 20, "search": searchText, "assetId": assetId});
      List<WoByAssetIdModel> woList = [];
      if (response.statusCode >= 200 && response.statusCode < 300) {
        List categoriesListJson = json.decode(response.body)["data"];
        woList = categoriesListJson.map((wo) => WoByAssetIdModel.fromJson(wo)).toList();
      }
      return woList;
    } catch (error) {
      return [];
    }
  }
}
