import 'dart:convert';
import 'dart:developer';
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/modules/export_module/models/asset_column_metadata.dart';
import 'package:test_sa/modules/export_module/models/export_module_type.dart';
import 'package:test_sa/providers/loading_list_notifier.dart';

class AssetColumnsProvider extends LoadingListNotifier<AssetColumnMetadata> {
  @override
  Future<void> getData({int? id}) async {
    loading = true;
    notifyListeners();

    try {
      final moduleType = id != null ? ExportModuleType.fromId(id) : ExportModuleType.asset;
      String apiUrl;
      switch (moduleType) {
        case ExportModuleType.asset:
          apiUrl = URLs.getAssetColumnsMetadata;
          break;
        case ExportModuleType.callRequest:
          apiUrl = URLs.getAllWorkOrderColumnsMetadata;
          break;
      }

      Response response = await ApiManager.instance.get(apiUrl);

      stateCode = response.statusCode;

      if (response.statusCode >= 200 && response.statusCode < 300) {
        final responseData = json.decode(response.body);
        final List<dynamic> data = responseData['data'] ?? [];
        log('Raw data received: ${data.length} items for ${moduleType.displayName}');

        items = data.map((item) => AssetColumnMetadata.fromJson(item)).toList();
        log('First item: ${items.isNotEmpty ? items.first.displayName : "empty"}');
      } else {
        log('Failed with status code: ${response.statusCode}');
        items = [];
      }
    } catch (error) {
      debugPrint('Error fetching columns: $error');
      stateCode = -1;
      items = [];
    } finally {
      loading = false;
      log('Loading finished. Items count: ${items.length}, Loading: $loading, StateCode: $stateCode');
      notifyListeners();
    }
  }
}
