import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:smart_hotel_app/repositories/room_repository.dart';
import 'package:smart_hotel_app/services/room_service.dart';
import 'package:smart_hotel_app/views/report/room/cubit/room_report_state.dart';

class RoomReportCubit extends Cubit<RoomReportState> {
  final RoomService _service;

  RoomReportCubit({RoomService? service})
      : _service = service ?? RoomService(repository: RoomRepository()),
        super(const RoomReportState()) {
    loadData();
  }

  Future<void> loadData({int? floorId}) async {
    emit(state.copyWith(isLoading: true, error: null));
    try {
      final overview = await _service.getOverview(floorId);
      final activeIndex = overview.floorList.indexWhere((f) => f.isActive);
      emit(state.copyWith(
        isLoading: false,
        summary: overview.summary,
        floors: overview.floorList,
        selectedFloorIndex: activeIndex >= 0 ? activeIndex : 0,
        roomGrid: overview.roomGrid,
        detailRooms: overview.roomDetailList,
      ));
    } catch (e) {
      emit(state.copyWith(isLoading: false, error: e.toString()));
    }
  }

  void selectFloor(int index) {
    final floorId = state.floors[index].floorId;
    emit(state.copyWith(selectedFloorIndex: index));
    loadData(floorId: floorId);
  }
}
