import 'package:flutter_bloc/flutter_bloc.dart';
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/project_model.dart';
import 'package:syncrow_app/features/auth/model/user_model.dart';
import 'package:syncrow_app/features/menu/bloc/create_unit_bloc/create_unit_event.dart';
import 'package:syncrow_app/features/menu/bloc/create_unit_bloc/create_unit_state.dart';
import 'package:syncrow_app/services/api/home_creation_api.dart';
import 'package:syncrow_app/utils/constants/temp_const.dart';
import 'package:syncrow_app/utils/helpers/snack_bar.dart';

class CreateUnitBloc extends Bloc<CreateUnitEvent, CreateUnitState> {
  List<String> rooms = [];
  String unitName = '';
  String locationName = '';

  CreateUnitBloc() : super(InitialState()) {
    on<CreateRoomEvent>(_createRoom);
    on<RemoveRoomEvent>(_removeRoom);
    on<SaveRooms>(_save);
  }

  void _createRoom(CreateRoomEvent event, Emitter<CreateUnitState> emit) async {
    try {
      emit(LoadingState());
      if (rooms.contains(event.roomName)) {
        emit(const ErrorState(message: 'This name is already exist'));
        emit(CreateRoomState(roomList: rooms));
        return;
      }
      rooms.add(event.roomName);
      emit(CreateRoomState(roomList: rooms));
    } catch (e) {
      emit(const ErrorState(message: 'Something went wrong'));
      return;
    }
  }

  void _removeRoom(RemoveRoomEvent event, Emitter<CreateUnitState> emit) {
    try {
      emit(LoadingState());
      rooms.removeWhere((element) => element == event.roomName);
      emit(CreateRoomState(roomList: rooms));
    } catch (e) {
      emit(const ErrorState(message: 'Something went wrong'));
      return;
    }
  }

  void _save(SaveRooms event, Emitter<CreateUnitState> emit) async {
    try {
      if (event.unitName.isEmpty) {
        CustomSnackBar.displaySnackBar('Please enter the unit name');
        return;
      }
      if (rooms.isEmpty) {
        CustomSnackBar.displaySnackBar('Please add at least one room!');
        return;
      }

      emit(LoadingState());

      var storage = const FlutterSecureStorage();
      var userId = await storage.read(key: UserModel.userUuidKey) ?? '';

      Map<String, String> communityBody = {
        'communityName': event.communityName
      };
      final response = await HomeCreation.createCommunity(communityBody);
      if (response['data']['uuid'] != '') {
        // final result =
        //     await _assignToCommunity(communityId: response['data']['uuid'], userId: userId);

        // if (result) {
        String buildingId = await _createBuilding(
            buildingName: event.buildingName,
            communityId: response['data']['uuid'],
            userId: userId);

        if (buildingId.isNotEmpty) {
          final floorId = await _createFloor(
              floorName: event.floorName,
              buildingId: buildingId,
              userId: userId);

          if (floorId.isNotEmpty) {
            final unitId = await _createUnit(
                unitName: event.unitName, floorId: floorId, userId: userId);

            if (unitId.isNotEmpty && rooms.isNotEmpty) {
              rooms.forEach((room) async {
                await _createNewRoom(
                  roomName: room,
                  unitId: unitId,
                  userId: userId,
                  communityId: response['data']['uuid'],
                );
              });
            }
          }
        }
        // }
      }
      await HomeCubit.getInstance().fetchUnitsByUserId();
      emit(RoomsSavedSuccessfully());
    } catch (_) {
      emit(const ErrorState(message: 'Something went wrong'));
      return;
    }
  }
}

Future<bool> _assignToCommunity(
    {required String communityId, required String userId}) async {
  try {
    Map<String, String> body = {
      'communityUuid': communityId,
      'userUuid': userId,
    };
    final response = await HomeCreation.assignUserToCommunity(body);

    return response['success'] ?? false;
  } catch (_) {
    return false;
  }
}

Future<String> _createBuilding(
    {required String buildingName,
    required String communityId,
    required String userId}) async {
  try {
    Map<String, String> body = {
      'buildingName': buildingName,
      'communityUuid': communityId
    };
    final response = await HomeCreation.createBuilding(body);
    // if (response['data']['uuid'] != '') {
    // final result = await _assignToBuilding(buildingId: response['data']['uuid'], userId: userId);

    return response['data']['uuid'] ?? '';
    // } else {
    // return '';
    // }
  } catch (_) {
    return '';
  }
}

Future<bool> _assignToBuilding(
    {required String buildingId, required String userId}) async {
  try {
    Map<String, String> body = {
      'buildingUuid': buildingId,
      'userUuid': userId,
    };
    final response = await HomeCreation.assignUserToBuilding(body);

    return response['success'] ?? false;
  } catch (_) {
    return false;
  }
}

Future<String> _createFloor(
    {required String floorName,
    required String buildingId,
    required String userId}) async {
  try {
    Map<String, String> body = {
      'floorName': floorName,
      'buildingUuid': buildingId
    };
    final response = await HomeCreation.createFloor(body);
    // if (response['data']['uuid'] != '') {
    // final result = await _assignToFloor(buildingId: response['data']['uuid'], userId: userId);

    return response['data']['uuid'] ?? '';
    // } else {
    //   return '';
    // }
  } catch (_) {
    return '';
  }
}

Future<bool> _assignToFloor(
    {required String buildingId, required String userId}) async {
  try {
    Map<String, String> body = {
      'floorUuid': buildingId,
      'userUuid': userId,
    };
    final response = await HomeCreation.assignUserToFloor(body);

    return response['success'] ?? false;
  } catch (_) {
    return false;
  }
}

Future<String> _createUnit(
    {required String unitName,
    required String floorId,
    required String userId}) async {
  try {
    Map<String, String> body = {'unitName': unitName, 'floorUuid': floorId};
    final response = await HomeCreation.createUnit(body);
    if (response['data']['uuid'] != '') {
      final result =
          await _assignToUnit(unitId: response['data']['uuid'], userId: userId);

      return result ? response['data']['uuid'] : '';
    } else {
      return '';
    }
  } catch (_) {
    return '';
  }
}

Future<bool> _assignToUnit(
    {required String unitId, required String userId}) async {
  try {
    Map<String, String> body = {
      'unitUuid': unitId,
      'userUuid': userId,
    };
    final response = await HomeCreation.assignUserToUnit(body);

    return response['success'] ?? false;
  } catch (_) {
    return false;
  }
}

Future<String> _createNewRoom(
    {required String roomName,
    required String unitId,
    required String userId,
    required String communityId}) async {
  try {
    Map<String, String> body = {'subspaceName': roomName};
    Project? project = HomeCubit.getInstance().project;

    final response = await HomeCreation.createRoom(
        communityId: communityId,
        spaceId: unitId,
        body: body,
        projectId: project?.uuid ?? TempConst.projectIdDev);
    // if (response['data']['uuid'] != '') {
    //   final result = await _assignToRoom(roomId: response['data']['uuid'], userId: userId);

    return response['data']['uuid'] ?? '';
    // } else {
    //   return '';
    // }
  } catch (e) {
    return '';
  }
}

Future<bool> _assignToRoom(
    {required String roomId, required String userId}) async {
  try {
    Map<String, String> body = {
      'roomUuid': roomId,
      'userUuid': userId,
    };
    final response = await HomeCreation.assignUserToRoom(body);

    return response['success'] ?? false;
  } catch (_) {
    return false;
  }
}
