import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.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/models/hospital.dart';
import 'package:test_sa/models/user.dart';

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

  //reset provider data
  void reset() {
    _hospitals = null;
    _stateCode = null;
  }

  // state code of current request to defied error message
  // like 400 customer request failed
  // 500 service not available
  int? _stateCode;

  int? get stateCode => _stateCode;

  // true if there is next page in product list and false if not
  bool _nextPage = true;

  bool get nextPage => _nextPage;

  // contain user data
  // when user not login or register _user = null
  List<Hospital>? _hospitals;

  List<Hospital>? get hospitals => _hospitals;

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

  bool get isLoading => _loading;

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

  /// return -2 if request in progress
  /// return -1 if 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> getHospitals({String? host, User? user, String? title}) async {
    if (_loading == true) return -2;
    _loading = true;
    notifyListeners();
    late Response response;
    try {
      response = await ApiManager.instance.post(URLs.getSites, body: {
        "pageNumber": (hospitals?.length ?? 0) ~/ pageItemNumber + 1,
        "pageSize": 50,
        if (title != null && title.isNotEmpty) "name": title,
      });
      _stateCode = response.statusCode;
      if (response.statusCode >= 200 && response.statusCode < 300) {
        // client's request was successfully received
        List categoriesListJson = json.decode(response.body)["data"];
        List<Hospital> page = categoriesListJson.map((category) => Hospital.fromJson(category)).toList();
        if (hospitals == null) _hospitals = [];

        _hospitals!.addAll(page);
        if (page.length >= pageItemNumber) {
          _nextPage = true;
        } else {
          _nextPage = false;
        }
      }
      _loading = false;
      notifyListeners();
      return response.statusCode;
    } catch (error) {
      _loading = false;
      _stateCode = -1;
      notifyListeners();
      return -1;
    }
  }

  Future<List<Hospital>> getHospitalsList({String? host, User? user, String? title}) async {
    late Response response;
    try {
      response = await ApiManager.instance.post(URLs.getSites, body: {
        "pageSize": 50,
        if (title != null && title.isNotEmpty) "name": title,
      });
      // response = await get(
      //     Uri.parse(host + URLs.getHospitals
      //         + ( title == null || title.isEmpty ? "" : "?name=$title" )),
      //     headers: {
      //       "Content-Type":"application/json; charset=utf-8"
      //     }
      // );
      _stateCode = response.statusCode;

      List<Hospital> page = [];
      if (response.statusCode >= 200 && response.statusCode < 300) {
        // client's request was successfully received
        List categoriesListJson = json.decode(response.body)["data"];
        page = categoriesListJson.map((category) => Hospital.fromJson(category)).toList();
      }
      return page;
    } catch (error) {
      _loading = false;
      _stateCode = -1;
      notifyListeners();
      return [];
    }
  }

  Future<List<Hospital>> getHospitalsListByVal({String searchVal = ""}) async {
    late Response response;
    try {
      if (searchVal.isNotEmpty) {
        searchVal = "?searchText=$searchVal";
      }
      response = await ApiManager.instance.get(URLs.getSitesAutoComplete + searchVal);
      // response = await get(
      //     Uri.parse(host + URLs.getHospitals
      //         + ( title == null || title.isEmpty ? "" : "?name=$title" )),
      //     headers: {
      //       "Content-Type":"application/json; charset=utf-8"
      //     }
      // );
      _stateCode = response.statusCode;

      List<Hospital> page = [];
      if (response.statusCode >= 200 && response.statusCode < 300) {
        // client's request was successfully received
        List categoriesListJson = json.decode(response.body)["data"];
        page = categoriesListJson.map((category) => Hospital.fromJson(category)).toList();
      }
      return page;
    } catch (error) {
      _loading = false;
      _stateCode = -1;
      notifyListeners();
      return [];
    }
  }
}
