import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:syncrow_app/features/app_layout/bloc/home_cubit.dart';
import 'package:syncrow_app/features/auth/model/user_model.dart';
import 'package:syncrow_app/features/devices/model/device_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 HomeManagementAPI {
  static final HTTPService _httpService = HTTPService();

  static Future<List<DeviceModel>> fetchDevicesByUserId() async {
    var storage = const FlutterSecureStorage();
    var userId = await storage.read(key: UserModel.userUuidKey) ?? '';

    List<DeviceModel> list = [];

    await _httpService.get(
        path: ApiEndpoints.getDevicesByUserId.replaceAll("{userId}", userId),
        showServerMessage: false,
        expectedResponseModel: (json) {
          json.forEach((value) {
            list.add(DeviceModel.fromJson(value));
          });
        });

    return list;
  }

  static Future<List<DeviceModel>> fetchDevices(projectUuid) async {
    List<DeviceModel> list = [];

    await _httpService.get(
        path: ApiEndpoints.devices.replaceAll("{projectUuid}", projectUuid),
        showServerMessage: false,
        expectedResponseModel: (json) {
          json['data'].forEach((value) {
            list.add(DeviceModel.fromJson(value));
          });
        });

    return list;
  }

  static Future<List<DeviceModel>> fetchDevicesByUnitId(
      String projectUuid) async {
    List<DeviceModel> list = [];

    try {
      // Retrieve selected space details
      final selectedSpace = HomeCubit.getInstance().selectedSpace;
      final communityUuid = selectedSpace?.community?.uuid ?? '';
      final spaceUuid = selectedSpace?.id ?? '';

      // Ensure both placeholders are replaced
      final path = ApiEndpoints.spaceDevices
          .replaceAll('{communityUuid}', communityUuid)
          .replaceAll('{spaceUuid}', spaceUuid)
          .replaceAll('{projectUuid}', projectUuid);

      await _httpService.get(
        path: path,
        showServerMessage: false,
        expectedResponseModel: (json) {
          if (json['data'] != null) {
            json['data'].forEach((value) {
              list.add(DeviceModel.fromJson(value));
            });
          }
        },
      );

      // Debugging: Log successful fetch
    } catch (e) {
      // Log the error for debugging
    }

    return list;
  }

  static Future<Map<String, dynamic>> assignDeviceToRoom(
      String communityId,
      String spaceId,
      String subSpaceId,
      String deviceId,
      String projectId) async {
    try {
      final response = await _httpService.post(
        path: ApiEndpoints.assignDeviceToRoom
            .replaceAll('{projectUuid}', projectId)
            .replaceAll('{communityUuid}', communityId)
            .replaceAll('{spaceUuid}', spaceId)
            .replaceAll('{subSpaceUuid}', subSpaceId)
            .replaceAll('{deviceUuid}', deviceId),
        expectedResponseModel: (json) {
          return json;
        },
      );
      return response;
    } catch (e) {
      rethrow;
    }
  }

  static Future<Map<String, dynamic>> unAssignDeviceToRoom(
      String communityId,
      String spaceId,
      String subSpaceId,
      String deviceId,
      String projectId) async {
    try {
      final response = await _httpService.delete(
        path: ApiEndpoints.assignDeviceToRoom
            .replaceAll('{communityUuid}', communityId)
            .replaceAll('{spaceUuid}', spaceId)
            .replaceAll('{subSpaceUuid}', subSpaceId)
            .replaceAll('{deviceUuid}', deviceId)
            .replaceAll('{projectUuid}', projectId),
        expectedResponseModel: (json) {
          return json;
        },
      );
      return response;
    } catch (e) {
      rethrow;
    }
  }
}
