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

import 'package:http/http.dart' as http;
import 'package:test_sa/controllers/api_routes/urls.dart';
import 'package:test_sa/modules/signup/models/site_model.dart';
import 'package:test_sa/providers/loading_list_notifier.dart';

class SignupSiteProvider extends LoadingListNotifier<SiteModel> {
  @override
  Future getData({int? id}) async {
    log('Fetching site list for asset group ID: $id');
    if (loading) return -2;

    if (id == null) {
      items = [];
      notifyListeners();
      return -1;
    }

    loading = true;
    notifyListeners();

    try {
      final headers = {
        'Content-Type': 'application/json',
        'X-Timezone-Offset': DateTime.now().timeZoneOffset.toString().split(".").first,
      };

      final response = await http.post(
        Uri.parse('${URLs.signUpGetSiteList}?assetGroupId=$id'),
        headers: headers,
        body: '',
      );

      stateCode = response.statusCode;
      log('Site API response status: ${response.statusCode}');

      if (response.statusCode >= 200 && response.statusCode < 300) {
        final data = json.decode(response.body);
        log('Site API response data type: ${data.runtimeType}');
        if (data['data'] != null && data['data'] is List) {
          items = (data['data'] as List)
              .map((item) => SiteModel.fromJson(item))
              .toList();
          log('Successfully parsed ${items.length} sites');
        } else {
          log('Site API response does not contain data array');
          items = [];
        }
      } else {
        log('Site API request failed with status: ${response.statusCode}');
        items = [];
      }

      loading = false;
      notifyListeners();
      return response.statusCode;
    } catch (error) {
      log('Site API error: $error');
      loading = false;
      stateCode = -1;
      items = [];
      notifyListeners();
      return -1;
    }
  }
}
