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

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/lookup.dart';
import 'package:test_sa/modules/loan_module/models/medical_department_model.dart';
import 'package:test_sa/providers/loading_list_notifier.dart';

class CostCenterProvider extends LoadingListNotifier<Lookup> {
  @override
  Future<void> getData({int? id}) async {
    if (loading) return;
    loading = true;
    notifyListeners();
    try {
      final response = await ApiManager.instance.get(
        URLs.getCostCenterToPo + "?assetDeliveryExternalMasterId=$id",
      );
      stateCode = response.statusCode;
      if (response.statusCode >= 200 && response.statusCode < 300) {
        final List list = json.decode(response.body)['data'];
        final Set<String> seenNames = {};
        int index = 0;
        items =
            list.where((e) => e is Map && e['name'] != null && e['name'].toString().trim().isNotEmpty).map((e) => e['name'].toString().trim()).where((name) => seenNames.add(name)).map<Lookup>((name) {
          final lookup = Lookup(
            id: index,
            value: index + 1,
            name: name,
          );
          index++;
          return lookup;
        }).toList();
      }
    } catch (e, s) {
      log('getData error', error: e, stackTrace: s);
      stateCode = -1;
    } finally {
      loading = false;
      notifyListeners();
    }
  }
}
