import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.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/employee.dart';

class NurseProvider extends ChangeNotifier {
  //reset provider data
  void reset() {
    _items = null;
    _stateCode = null;
  }

  int? _stateCode; // Now nullable

  int? get stateCode => _stateCode;
  List<Employee>? _items; // Now nullable

  List<Employee> get nursesList => _items ?? []; // Return empty list if null
  bool _loading = false; // Initialize loading to false

  bool get isLoading => _loading;

  int? siteId; // Now nullable

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

  Future<int> getData() async {
    if (_loading) return -2;
    _loading = true;
    notifyListeners();
    try {
      if (siteId == null) {
        await Future.delayed(const Duration(seconds: 1));
        _items = [];
        _loading = false;
        notifyListeners();
        _stateCode = 200;
        return _stateCode!; // Non-null assertion since _stateCode is set to 200
      }
      final response = await ApiManager.instance.get(URLs.getNursesBySiteId + "&siteId=$siteId");
      _stateCode = response.statusCode;
      if (response.statusCode >= 200 && response.statusCode < 300) {
        final categoriesListJson = json.decode(response.body) as List;
        _items = categoriesListJson.map((type) => Employee.fromJson(type)).toList();
        _items!.sort((a, b) => a.name!.compareTo(b.name!)); // Null-aware operator for sorting
      }
      _loading = false;
      notifyListeners();
      return response.statusCode;
    } catch (error) {
      _loading = false;
      _stateCode = -1;
      notifyListeners();
      return -1;
    }
  }
}
