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

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

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

    if (id == null) {
      log('Department fetch: ID is null, clearing items');
      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 ApiManager.instance.get(
          '${URLs.signUpGetDepartmentAutoComplete}?assetGroupId=$id',
        // Uri.parse('${URLs.signUpGetDepartmentAutoComplete}?assetGroupId=$id'),
        headers: headers,
      );

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

      if (response.statusCode >= 200 && response.statusCode < 300) {
        final data = json.decode(response.body);
        log('Department API response data type: ${data.runtimeType}');

        // Check if response is wrapped in a 'data' property or direct array
        if (data is Map && data['data'] != null && data['data'] is List) {
          items = (data['data'] as List).map((item) => DepartmentModel.fromJson(item)).toList();
          log('Successfully parsed ${items.length} departments from data wrapper');
        } else if (data is List) {
          items = data.map((item) => DepartmentModel.fromJson(item)).toList();
          log('Successfully parsed ${items.length} departments from direct array');
        } else {
          log('Department API response format unexpected: ${data.runtimeType}');
          if (data is Map) {
            log('Response keys: ${data.keys.toList()}');
          }
          items = [];
        }
      } else {
        log('Department API request failed with status: ${response.statusCode}');
        items = [];
      }

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

  /// Fetches departments based on selected sites and asset group
  Future<int> getDepartmentsBySites({
    required List<int> siteIds,
    required int assetGroupId,
  }) async {
    log('Fetching departments for sites: $siteIds and asset group: $assetGroupId');

    if (loading) return -2;

    if (siteIds.isEmpty) {
      log('Department fetch: Site IDs are empty, clearing items');
      items = [];
      notifyListeners();
      return -1;
    }

    loading = true;
    notifyListeners();

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

      final body = {
        'siteIds': siteIds,
        'assetGroupId': assetGroupId,
      };

      final response = await ApiManager.instance.post(
          URLs.signUpGetDepartmentsBySitesAndAssetGroup,
        headers: headers,
        body: body,
      );

      stateCode = response.statusCode;

      if (response.statusCode >= 200 && response.statusCode < 300) {
        final data = json.decode(response.body);
        if (data is Map && data['data'] != null && data['data'] is List) {
          items = (data['data'] as List).map((item) => DepartmentModel.fromJson(item)).toList();
        } else if (data is List) {
          items = data.map((item) => DepartmentModel.fromJson(item)).toList();
        } else {
          items = [];
        }
      } else {
        items = [];
      }

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