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/models/device/asset_search.dart';
import 'package:test_sa/models/lookup.dart';
import 'package:test_sa/models/new_models/asset_nd_auto_complete_by_dynamic_codes_model.dart';
import 'package:test_sa/modules/internal_audit_module/models/update_audit_form_model.dart';
import 'package:test_sa/modules/internal_audit_module/models/equipment_internal_audit_data_model.dart';
import 'package:test_sa/modules/internal_audit_module/models/equipment_internal_audit_form_model.dart';
import 'package:test_sa/modules/internal_audit_module/models/system_internal_audit_data_model.dart';
import 'package:test_sa/modules/internal_audit_module/models/system_internal_audit_form_model.dart';
import 'package:test_sa/new_views/common_widgets/app_lazy_loading.dart';

class InternalAuditProvider extends ChangeNotifier {
  final pageItemNumber = 10;
  final searchPageItemNumber = 10;
  int pageNo = 1;

  void reset() {
    pageNo = 1;
    stateCode = null;
  }

  int? stateCode;
  bool isDetailLoading = false;
  bool nextPage = false;
  bool isNextPageLoading = false;
  bool isLoading = false;

  Future<EquipmentInternalAuditDataModel?> getEquipmentInternalAuditById(int id) async {
    try {
      isLoading = true;
      notifyListeners();
      Response response = await ApiManager.instance.get(
        "${URLs.getInternalAuditEquipmentById}?internalAuditEquipmentId=$id",
      );
      if (response.statusCode >= 200 && response.statusCode < 300) {
        final decodedBody = jsonDecode(response.body);
        EquipmentInternalAuditDataModel model = EquipmentInternalAuditDataModel.fromJson(decodedBody["data"]);
        isLoading = false;
        notifyListeners();
        return model;
      } else {
        isLoading = false;
        notifyListeners();
        return null;
      }
    } catch (error) {
      isLoading = false;
      notifyListeners();
      return null;
    }
  }

  Future<SystemInternalAuditDataModel?> getInternalSystemAuditById(int id) async {
    try {
      isLoading = true;
      notifyListeners();
      Response response = await ApiManager.instance.get("${URLs.getInternalAuditSystemById}?AuditSystemId=$id");
      if (response.statusCode >= 200 && response.statusCode < 300) {
        final decodedBody = jsonDecode(response.body);
        SystemInternalAuditDataModel model = SystemInternalAuditDataModel.fromJson(decodedBody["data"]);
        isLoading = false;
        notifyListeners();
        return model;
      } else {
        isLoading = false;
        notifyListeners();
        return null;
      }
    } catch (error) {
      isLoading = false;
      notifyListeners();
      return null;
    }
  }

  Future<SystemAuditWorkOrderDetailModel?> loadAllWorkOrderDetailsByID({required int workOrderTypeId, required int workOrderId}) async {
    try {
      isLoading = true;
      notifyListeners();
      Response response = await ApiManager.instance.get("${URLs.loadAllWorkOrderDetailsByID}?workOrderTypeId=$workOrderTypeId&workOrderId=$workOrderId");
      if (response.statusCode >= 200 && response.statusCode < 300) {
        final decodedBody = jsonDecode(response.body);
        SystemAuditWorkOrderDetailModel model = SystemAuditWorkOrderDetailModel.fromJson(decodedBody["data"]);
        isLoading = false;
        notifyListeners();
        return model;
      } else {
        isLoading = false;
        notifyListeners();
        return null;
      }
    } catch (error) {
      isLoading = false;
      notifyListeners();
      return null;
    }
  }

  Future<bool> updateEquipmentInternalAudit({required AuditFormModel model}) async {
    isLoading = true;
    Response response;
    try {
      response = await ApiManager.instance.put(URLs.updateAuditEquipmentsEngineer, body: model.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> updateSystemInternalAudit({required AuditFormModel model}) async {
    isLoading = true;
    Response response;
    try {
      response = await ApiManager.instance.put(URLs.updateAuditSystemEngineer, body: model.toJson());
      stateCode = response.statusCode;
      isLoading = false;
      notifyListeners();
      log('status code ${stateCode}');
      if (stateCode == 200) {
        return true;
      }
      return false;
    } catch (error) {
      isLoading = false;
      stateCode = -1;
      notifyListeners();
      return false;
    }
  }

  Future<bool> addEquipmentInternalAudit({
    required BuildContext context,
    required EquipmentInternalAuditFormModel request,
  }) async {
    bool status = false;
    Response response;
    try {
      response = await ApiManager.instance.post(URLs.addOrUpdateEquipmentInternalAudit, body: request.toJson());
      if (response.statusCode >= 200 && response.statusCode < 300) {
        status = true;
        notifyListeners();
      } else {
        Fluttertoast.showToast(msg: "${context.translation.failedRequestMessage} :${json.decode(response.body)['message']}");
        status = false;
      }
      return status;
    } catch (error) {
      print(error);
      status = false;
      notifyListeners();
      return status;
    }
  }

  Future<bool> addSystemInternalAudit({
    required BuildContext context,
    required SystemInternalAuditFormModel request,
  }) async {
    bool status = false;
    Response response;
    try {
      response = await ApiManager.instance.post(URLs.addOrUpdateInternalAuditSystem, body: request.toJson());
      if (response.statusCode >= 200 && response.statusCode < 300) {
        status = true;
        notifyListeners();
      } else {
        Fluttertoast.showToast(msg: "${context.translation.failedRequestMessage} :${json.decode(response.body)['message']}");
        status = false;
      }
      return status;
    } catch (error) {
      print(error);
      status = false;
      notifyListeners();
      return status;
    }
  }

  Future<List<WoAutoCompleteModel>> getWorkOrderByWoType({String? text, required int? woId}) async {
    late Response response;
    try {
      Response response = await ApiManager.instance.get("${URLs.getWoAutoComplete}?workOrderTypeId=$woId&search=$text");
      // response = await ApiManager.instance.post(url, body: {"search": text});
      List<WoAutoCompleteModel> woOrderList = [];
      if (response.statusCode >= 200 && response.statusCode < 300) {
        List categoriesListJson = json.decode(response.body)["data"];
        woOrderList = categoriesListJson.map((wo) => WoAutoCompleteModel.fromJson(wo)).toList();
      }
      return woOrderList;
    } catch (error) {
      return [];
    }
  }
}
