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

import 'package:flutter/cupertino.dart';
import 'package:localization/localization.dart';
import 'package:http/http.dart';
import 'package:test_sa/controllers/api_routes/api_manager.dart';
import 'package:test_sa/controllers/api_routes/http_status_manger.dart';
import 'package:test_sa/controllers/api_routes/urls.dart';
import 'package:test_sa/models/device/asset_by_id_model.dart';
import 'package:test_sa/models/device/asset_search.dart';
import 'package:test_sa/models/generic_attachment_model.dart';
import 'package:test_sa/models/lookup.dart';
import 'package:test_sa/models/user.dart';
import 'package:test_sa/modules/asset_delivery_module/models/technical_inpection_asset_model.dart';

import '../../../l10n/app_localizations.dart';
import '../../../models/device/asset.dart';

class AssetProvider extends ChangeNotifier {
  //reset provider data
  void reset() {
    _devices = [];
    _stateCode = null;
  }

  void searchReset() {
    _stateCode = null;
    _searchDevices = [];
  }

  final pageItemNumber = 10;
  final searchPageItemNumber = 10;

  bool nextPage = true;

  int? _stateCode;

  int? get stateCode => _stateCode;

  set stateCode(int? code) => _stateCode = code;

  List<Asset> _devices = [];
  List<Asset> _searchDevices = [];
  List<TechnicalInspectionAssetBasicInfoModel> technicalInspectionAsset = [];

  List<Asset> get devices => _devices;

  List<Asset> get searchDevices => _searchDevices;

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

  bool get isLoading => _loading;

  AssetByIdModel? _assetById;

  AssetByIdModel? get assetById => _assetById;

  set isLoading(bool isLoading) {
    _loading = isLoading;
    notifyListeners();
  }

  Future<int> getAssets({DeviceSearch? search, bool isQr = false, bool isSearchBy = false}) async {
    if (_loading == true) return -2;
    _loading = true;
    notifyListeners();
    late Response response;
    try {
      final Map<String, dynamic> body = {
        "pageSize": isSearchBy ? searchPageItemNumber : pageItemNumber,
        "pageNumber": isSearchBy ? (searchDevices.length / searchPageItemNumber).ceil() + 1 : devices.length ~/ pageItemNumber + 1,
      };
      if (search != null) body.addAll(search.toJson());
      response = await ApiManager.instance.post(URLs.getAssets, body: body);
    } catch (error) {
      _loading = false;
      _stateCode = -1;
      notifyListeners();
      return -1;
    }
    _stateCode = response.statusCode;
    if (response.statusCode >= 200 && response.statusCode < 300) {
      // client's request was successfully received
      List equipmentListJson = json.decode(response.body)["data"];
      var dList = equipmentListJson.map<Asset>((asset) => Asset.fromJson(asset)).toList() ?? [];
      try {
        if (isQr) {
          dList = dList.where((element) => search?.assetNo?.toLowerCase() == element.assetNumber?.toLowerCase()).toList() ?? [];
        }
      } catch (e) {
        print(e);
      }
      isSearchBy ? _searchDevices.addAll(dList) : _devices.addAll(dList);
      nextPage = true;
    } else {
      nextPage = false;
    }
    _loading = false;
    notifyListeners();
    return response.statusCode;
  }

  Future<int> getAssetsForAssetDelivery({DeviceSearch? search, bool isSearchBy = false, int? lineId}) async {
    if (_loading == true) return -2;
    _loading = true;
    notifyListeners();
    late Response response;
    try {
      final Map<String, dynamic> body = {
        "pageSize": isSearchBy ? searchPageItemNumber : pageItemNumber,
        "pageNumber": isSearchBy ? (searchDevices.length / searchPageItemNumber).ceil() + 1 : devices.length ~/ pageItemNumber + 1,

        ///Uncommit this after testing...
        "assetDeliveryExternalDetailId": lineId,
        "assetName": search?.assetName,

        // "assetDeliveryExternalDetailId": 2,
        // "assetName": "Treatment Center Intego - Dental Chair",
        "assetNumber": search?.assetNo,
        "model": search?.model,
        "manufacturer": search?.manufacturer,
      };
      response = await ApiManager.instance.post(URLs.getAssetFromInternalTechnicalInspection, body: body);
    } catch (error) {
      _loading = false;
      _stateCode = -1;
      notifyListeners();
      return -1;
    }
    _stateCode = response.statusCode;
    if (response.statusCode >= 200 && response.statusCode < 300) {
      List equipmentListJson = json.decode(response.body)["data"];
      var dList = equipmentListJson.map<TechnicalInspectionAssetBasicInfoModel>((asset) => TechnicalInspectionAssetBasicInfoModel.fromJson(asset)).toList() ?? [];
      technicalInspectionAsset.addAll(dList);
      nextPage = true;
    } else {
      nextPage = false;
    }
    _loading = false;
    notifyListeners();
    return response.statusCode;
  }

  Future<AssetByIdModel> getAssetById(int assetId, AppLocalizations appLocalizations) async {
    late Response response;
    try {
      response = await ApiManager.instance.get(URLs.getAssetById + "$assetId");
    } catch (error) {
      print(error);
      throw (HttpStatusManger.getStatusMessage(status: -1, subtitle: appLocalizations));
    }
    if (response.statusCode >= 200 && response.statusCode < 300) {
      Map<String, dynamic> assetData = json.decode(response.body)["data"];
      _assetById = AssetByIdModel.fromJson(assetData);
      return _assetById!;
    }
    throw (HttpStatusManger.getStatusMessage(status: response.statusCode, subtitle: appLocalizations));
  }

  Future<List<Asset>> getDevicesList({
    required String host,
    required User user,
    required int hospitalId,
    // String serialNumber,
    // String number,
    bool addPagination = true,
    DeviceSearch? search,
  }) async {
    late Response response;
    try {
      Map<String, dynamic> body = {
        // "pageSize": pageItemNumber,
        // "pageNumber": devices.length ~/ pageItemNumber + 1,
        // "siteId": hospitalId,
        // if (serialNumber?.isEmpty == false) "assetSerialNumber": serialNumber,
        // if (number?.isEmpty == false) "assetNo": number,
      };
      if (search != null) body.addAll(search.toJson());
      if (addPagination) {
        body["pageSize"] = pageItemNumber;
        body["pageNumber"] = devices.length ~/ pageItemNumber + 1;
      }

      response = await ApiManager.instance.post(URLs.getAssets, body: body);
      // response = await get(
      //     Uri.parse("$host${URLs.getEquipment}?siteId=$hospitalId"
      //         "${serialNumber?.isEmpty == false ? "&assetSerialNumber=$serialNumber" :""}"
      //         "${number?.isEmpty == false ? "&assetNo=$number" : ""}"
      //     ),
      // );
      List<Asset> page = [];
      if (response.statusCode >= 200 && response.statusCode < 300) {
        // client's request was successfully received
        List equipmentListJson = json.decode(response.body)["data"];
        page = equipmentListJson.map((asset) => Asset.fromJson(asset)).toList();
        _devices.addAll(equipmentListJson.map<Asset>((asset) => Asset.fromJson(asset)).toList());
        notifyListeners();
      }
      return page;
    } catch (error) {
      return [];
    }
  }

  Future<List<Lookup>> getModels({
    String? code,
  }) async {
    late Response response;
    try {
      response = await ApiManager.instance.get(URLs.getModels + "?code=${code ?? ""}");
      List<Lookup> page = [];
      if (response.statusCode >= 200 && response.statusCode < 300) {
        // client's request was successfully received
        List categoriesListJson = json.decode(response.body)["data"];
        page = categoriesListJson
            .map((json) => Lookup(
                  name: json["modelDefCode"],
                  id: json["id"],
                  value: json["id"],
                ))
            .toList();
      }
      return page;
    } catch (error) {
      return [];
    }
  }

  Future<bool> uploadAssetImages(int assetId, TrainingImageData trainingImageData) async {
    late Response response;
    try {
      List<Future<MultipartFile>> files = [];
      files.add(MultipartFile.fromPath("LeftImage", trainingImageData.leftImage!.name!));
      files.add(MultipartFile.fromPath("RightImage", trainingImageData.rightImage!.name!));
      files.add(MultipartFile.fromPath("UpImage", trainingImageData.upImage!.name!));
      files.add(MultipartFile.fromPath("DownImage", trainingImageData.downImage!.name!));

      for (var i = 0; i < (trainingImageData.additionalImages?.length ?? 0); i++) {
        files.add(
          MultipartFile.fromPath('AdditionalImage', trainingImageData.additionalImages![i].name!),
        );
      }
      response = await ApiManager.instance.multiPart(URLs.saveAssetImages + "?AssetId=$assetId", body: {}, files: files);
      if (response.statusCode >= 200 && response.statusCode < 300) {
        // client's request was successfully received
        // Map<String, dynamic> assetData = json.decode(response.body)["data"];
        // _assetById = AssetByIdModel.fromJson(assetData);
        // return _assetById!;
        return true;
      }
      return false;
    } catch (error) {
      return false;
    }
  }
}
