import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:smart_hotel_app/models/bo/inspection_room_bo.dart';
import 'package:smart_hotel_app/repositories/inspection_device_repository.dart';
import 'package:smart_hotel_app/repositories/inspection_room_repository.dart';
import 'package:smart_hotel_app/services/inspection_device_service.dart';
import 'package:smart_hotel_app/services/inspection_room_service.dart';
import 'package:smart_hotel_app/views/home/inspection/cubit/inspection_state.dart';

class InspectionCubit extends Cubit<InspectionState> {
  final InspectionRoomService _roomService;
  final InspectionDeviceService _deviceService;

  static const int _pageSize = 20;

  InspectionCubit({
    InspectionRoomService? roomService,
    InspectionDeviceService? deviceService,
  })  : _roomService = roomService ??
            InspectionRoomService(repository: InspectionRoomRepository()),
        _deviceService = deviceService ??
            InspectionDeviceService(
                repository: InspectionDeviceRepository()),
        super(const InspectionState(isLoading: true)) {
    initData();
  }

  Future<void> initData() async {
    try {
      final rooms = await _roomService.getRooms();
      final roomsMap = <int, String>{};
      for (final r in rooms) {
        roomsMap[r.roomId] = r.roomNumber;
      }
      final tabCounts = _computeTabCounts(rooms);

      final firstRoomIds = rooms.isNotEmpty ? [rooms.first.roomId] : <int>[];

      emit(state.copyWith(
        isLoading: false,
        error: null,
        allRooms: roomsMap,
        selectedRoomIds: firstRoomIds,
        tabCounts: tabCounts,
      ));
    } catch (e) {
      emit(state.copyWith(
        isLoading: false,
        error: e.toString(),
      ));
    }
  }

  /// 供 PagingController.fetchPage 回调使用
  Future<List<InspectionDevice>> fetchPage(int pageKey) async {
    final roomId = state.selectedRoomIds.length == 1
        ? state.selectedRoomIds.first
        : null;

    final result = await _deviceService.getList(
      pageSize: _pageSize,
      pageNum: pageKey,
      roomId: roomId,
    );
    return result.data
        .map((e) => InspectionDevice.fromInspectionDeviceBO(e))
        .toList();
  }

  Map<DeviceStatusTab, int> _computeTabCounts(List<InspectionRoomBO> rooms) {
    int normal = 0;
    int warning = 0;
    int offline = 0;
    int fault = 0;

    for (final room in rooms) {
      normal += room.runStatus.normal;
      warning += room.runStatus.warning;
      offline += room.runStatus.offline;
      fault += room.runStatus.fault;
    }

    return {
      DeviceStatusTab.total: normal + warning + offline + fault,
      DeviceStatusTab.on: normal,
      DeviceStatusTab.off: 0,
      DeviceStatusTab.offline: offline,
      DeviceStatusTab.alarm: warning,
      DeviceStatusTab.fault: fault,
    };
  }

  void selectTab(DeviceStatusTab tab) {
    emit(state.copyWith(selectedTab: tab));
  }

  void toggleRoom(int roomId) {
    final List<int> newSelected = List.from(state.selectedRoomIds);
    if (newSelected.contains(roomId)) {
      newSelected.remove(roomId);
    } else {
      newSelected.clear();
      newSelected.add(roomId);
    }
    emit(state.copyWith(selectedRoomIds: newSelected));
  }
}