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

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

class RequestDetailProvider extends ChangeNotifier {
  final pageItemNumber = 10;

  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;

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

  void stopTimer() {
    Timer.periodic(const Duration(seconds: 1), (Timer t) {
      timerStartTime = timerStartTime.add(const Duration(seconds: 1));
      notifyListeners(); // Notify UI when time is updated
    });
    timer?.cancel();
    isTimerRunning = false;
    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 get isLoading => _isLoading;

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

  //UI models
  WorkOrderDetail? currentWorkOrder;
  AssetRetiredHelperModel? assetRetiredHelperModel = AssetRetiredHelperModel();
  ActivityMaintenanceHelperModel? activityMaintenanceHelperModel = ActivityMaintenanceHelperModel();
  SparePartHelperModel? sparePartHelperModel;
  FixRemotelyHelperModel? fixRemotelyHelperModel = FixRemotelyHelperModel();
  NeedVisitHelperModel? needVisitHelperModel = NeedVisitHelperModel();
  NurseActionHelperModel? nurseActionHelperModel;
  EngineerRejectHelperModel? engineerRejectHelperModel = EngineerRejectHelperModel();
  EngineerUpdateWorkOrderHelperModel? engineerUpdateWorkOrderHelperModel = EngineerUpdateWorkOrderHelperModel();
  WorkOrderHelperModel? workOrderHelperModel;

  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;
    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();
  }

  //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;
      print('response of create request is ${response.body}');
      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 = WorkOrderDetail.fromJson(json.decode(response.body));
      }
      isLoading = false;
      notifyListeners();
    } catch (e) {
      log("getSubWorkOrderDetails [error] : $e");
      isLoading = false;
      notifyListeners();
      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 = 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> engineerStopTimer() async {
    Response response;
    try {
      final body = {"workOrderId": currentWorkOrder?.data?.requestId};
      isLoading = true;
      notifyListeners();
      response = await ApiManager.instance.post(URLs.engineerStopTimer, body: body);
      print('response of stop timer is ${response.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;
    }
  }

  //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 = 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 = 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 = 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;
      print('body i got is ${needVisitHelperModel?.toJson()}');
      print('response i got is ${response.body}');
      if (response.statusCode >= 200 && response.statusCode < 300) {
        currentWorkOrder = WorkOrderDetail.fromJson(json.decode(response.body));
      }
      isLoading = false;
      notifyListeners();
      return response.statusCode;
    } catch (e) {
      log("engineer accept  [error] : $e");
      isLoading = false;
      notifyListeners();
      return -1;
    }
  }

  //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;
      print('engineer mark as fixed response is ${response.body}');
      if (response.statusCode >= 200 && response.statusCode < 300) {
        currentWorkOrder = 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;
    }
  }

  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 = 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, required String photoInfo, required String otp, String? assetNo}) async {
    Response response;
    try {
      Map<String, dynamic> body = {"workOrderId": workOrderId, "verificationTypeId": verificationTypeId, "photoInfo": photoInfo, "otp": otp, "assetNumber": assetNo};
      isLoading = true;
      notifyListeners();
      response = await ApiManager.instance.post(URLs.engineerConfirmArriveUrl, body: body);
      stateCode = response.statusCode;
      if (response.statusCode >= 200 && response.statusCode < 300) {
        //  print('response of Engineer confirm arrival  ${response.body}');
      }
      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<void> engineerUpdateWorkOrder() async {
    try {
      isLoading = true;
      notifyListeners();
      final response = await ApiManager.instance.post(URLs.engineerUpdateWorkOrderUrl, body: engineerUpdateWorkOrderHelperModel!.toJson());
      stateCode = response.statusCode;
      if (response.statusCode >= 200 && response.statusCode < 300) {
        currentWorkOrder = WorkOrderDetail.fromJson(json.decode(response.body));
      }
      isLoading = false;
      notifyListeners();
    } catch (e) {
      log("engineer update workorder  [error] : $e");
      isLoading = false;
      notifyListeners();
    }
  }



  //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 close
  Future<CommonResponseModel> nurseConfirm() async {
    try {
      isLoading = true;
      notifyListeners();
      final response = await ApiManager.instance.post(URLs.nurseConfirmUrl, 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("engineer accept  [error] : $e");
      isLoading = false;
      notifyListeners();
      return CommonResponseModel();
    }
  }

  Future<int> updateActivitySparePart() async {
    isLoading = true;
    notifyListeners();
    try {
      final response = await ApiManager.instance.post(URLs.updateActivitySparePartUrl, body: sparePartHelperModel!.toJson());
      stateCode = response.statusCode;
      print('update response i got is ${response.body}');
      if (response.statusCode >= 200 && response.statusCode < 300) {
        // request.engineerName = employee.name;
      }
      isLoading = false;
      notifyListeners();
      return response.statusCode;
    } catch (error) {
      isLoading = false;
      notifyListeners();
      return -1;
    }
  }

  Future<int> updateActivityMaintenance() async {
    isLoading = true;
    notifyListeners();
    try {
      final response = await ApiManager.instance.put(URLs.updateActivityMaintenanceUrl, body: activityMaintenanceHelperModel!.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;
    }
  }

  Future<List<SuppPersons>> getSupplierEngineerData({required String supplierName}) async {
    try {
      Response response = await ApiManager.instance.get("${URLs.getSuppliersAutoComplete}?searchText=$supplierName");
      stateCode = response.statusCode;
      print('response i got is ${json.decode(response.body)["data"]}');
      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<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;
      print('response of delete activity spare part is ${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<int> createActivitySparePart() async {
    isLoading = true;
    notifyListeners();
    try {
      final response = await ApiManager.instance.post(
        URLs.createActivitySparePartUrl,
        body: sparePartHelperModel!.toJson(),
      );
      stateCode = response.statusCode;
      print('add sparepart activity response i got is ${response.body}');
      if (response.statusCode >= 200 && response.statusCode < 300) {
        // currentWorkOrder = WorkOrderDetail.fromJson(json.decode(response.body));
        // // updateCurrentWorkOrder(currentWorkOrder);
        // notifyListeners();
      }
      isLoading = false;
      notifyListeners();
      return response.statusCode;
    } catch (error) {
      isLoading = false;
      notifyListeners();
      return -1;
    }
  }

  Future<int> createActivityMaintenanceRequest() async {
    isLoading = true;
    notifyListeners();
    try {
      final response = await ApiManager.instance.post(
        URLs.createActivityMaintenanceUrl,
        body: activityMaintenanceHelperModel!.toJson(),
      );
      stateCode = response.statusCode;
      print('add maintenance activity response i got is ${response.body}');
      if (response.statusCode >= 200 && response.statusCode < 300) {
        // currentWorkOrder = WorkOrderDetail.fromJson(json.decode(response.body));
        // updateCurrentWorkOrder(currentWorkOrder);
      }
      isLoading = false;
      notifyListeners();
      return response.statusCode;
    } catch (error) {
      isLoading = false;
      notifyListeners();
      return -1;
    }
  }

//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 = WorkOrderDetail.fromJson(json.decode(response.body));
      }
      isLoading = false;
      notifyListeners();
      return response.statusCode;
    } catch (error) {
      isLoading = false;
      notifyListeners();
      return -1;
    }
  }

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

  //send otp..
  Future<int?> sendOtp({required int workOrderId}) async {
    isLoading = true;
    notifyListeners();
    try {
      final response = await ApiManager.instance.postWithOutBody(
        URLs.sendOtpUrl + "$workOrderId",
      );
      print('url  for send otp is ${URLs.sendOtpUrl + "$workOrderId"}');
      stateCode = response.statusCode;
      print('response i got is ${response.body}');

      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.postWithOutBody(URLs.verifyOtpUrl + '$workOrderId&$otpCode');

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