import 'dart:convert';

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

class ServiceReportLastCallsProvider extends ChangeNotifier {
  //reset provider data
  void reset() {
    _calls = null;
    _loading = false; // Set to false initially
    _stateCode = null;
  }

  int? _stateCode;

  int? get stateCode => _stateCode;

  List<Lookup>? _calls;

  List<Lookup>? get calls => _calls;

  bool _loading = false; // Initialize to false

  bool get isLoading => _loading;

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

  Future<int> getCalls({String? parentId, int? id, String? typeName}) async {
    if (_loading) return -2;
    _loading = true;
    notifyListeners();
    try {
      final response = await ApiManager.instance.get(
        "${URLs.getServiceReportLastCalls}?parentWOId=${parentId ?? id}&isAdd=true&id=${id ?? 0}&typeTransaction=$typeName",
      );
      _stateCode = response.statusCode;
      if (response.statusCode >= 200 && response.statusCode < 300) {
        final categoriesListJson = json.decode(response.body)["data"] as List;
        _calls = categoriesListJson.map((type) => Lookup.fromJson(type)).toList();
      }
      _loading = false;
      notifyListeners();
      return response.statusCode;
    } catch (error) {
      _loading = false;
      _stateCode = -1;
      notifyListeners();
      return -1;
    }
  }
}
