import 'package:dio/dio.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:syncrow_app/features/app_layout/model/space_model.dart';
import 'package:syncrow_app/features/auth/model/user_model.dart';
import 'package:syncrow_app/features/devices/model/subspace_model.dart';
import 'package:syncrow_app/services/api/api_links_endpoints.dart';
import 'package:syncrow_app/services/api/http_service.dart';
import 'package:syncrow_app/utils/constants/temp_const.dart';

class SpacesAPI {
  static final HTTPService _httpService = HTTPService();

  static Future<List<SpaceModel>> getSpacesByUserId() async {
    try {
      var uuid =
          await const FlutterSecureStorage().read(key: UserModel.userUuidKey);
      if (uuid == null) throw Exception("User UUID is missing");

      final path = ApiEndpoints.userSpaces.replaceFirst('{userUuid}', uuid);
      final response = await _httpService.get(
        path: path,
        showServerMessage: false,
        expectedResponseModel: (json) {
          return SpaceModel.fromJsonList(json['data']);
        },
      );

      return response;
    } catch (error) {
      rethrow; // Rethrow the error to be caught by `fetchUnitsByUserId`
    }
  }

  static Future<List<SubSpaceModel>> getSubSpaceBySpaceId(
      String communityId, String spaceId, String projectId) async {
    try {
      // Construct the API path
      final path = ApiEndpoints.listSubspace
          .replaceFirst('{communityUuid}', communityId)
          .replaceFirst('{spaceUuid}', spaceId)
          .replaceAll('{projectUuid}', projectId);

      final response = await _httpService.get(
        path: path,
        queryParameters: {"page": 1, "pageSize": 10},
        showServerMessage: false,
        expectedResponseModel: (json) {
          List<SubSpaceModel> rooms = [];
          if (json['data'] != null) {
            for (var subspace in json['data']) {
              rooms.add(SubSpaceModel.fromJson(subspace));
            }
          } else {
            print("Warning: 'data' key is missing or null in response JSON.");
          }
          return rooms;
        },
      );

      return response;
    } catch (error, stackTrace) {
      return []; // Return an empty list if there's an error
    }
  }

  //factory/reset/{deviceUuid}

  static Future<String> generateInvitationCode(
      String unitId, String communityId, String projectId) async {
    final response = await _httpService.post(
      path: ApiEndpoints.invitationCode
          .replaceAll('{unitUuid}', unitId)
          .replaceAll('{communityUuid}', communityId)
          .replaceAll('{projectUuid}', projectId),
      showServerMessage: false,
      expectedResponseModel: (json) {
        if (json != null && json['data'] != null) {
          return json['data']['invitationCode'];
        } else {
          throw Exception('Data field is null');
        }
      },
    );
    return response;
  }

  static Future<bool> joinUnit(
    String userId,
    Map<String, String> body,
  ) async {
    final response = await _httpService.post(
      path: ApiEndpoints.verifyInvitationCode.replaceAll('{userUuid}', userId),
      showServerMessage: false,
      body: body,
      expectedResponseModel: (json) => json['success'],
    );
    return response;
  }

  static Future activationCodeSpace({
    String? activationCode,
    String? userUuid,
  }) async {
    Map body = {"activationCode": activationCode, "userUuid": userUuid};
    final response = await _httpService.post(
      path: ApiEndpoints.activationCode,
      showServerMessage: true,
      body: body,
      expectedResponseModel: (json) {
        return json;
      },
    );
    return response;
  }
}
