import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:smart_hotel_app/views/service/index/cubit/service_index_state.dart';
import 'package:smart_hotel_app/services/room_service.dart';
import 'package:smart_hotel_app/repositories/room_repository.dart';
import 'package:smart_hotel_app/models/bo/room_bo.dart';
import 'package:smart_hotel_app/services/room_statistics_service.dart';
import 'package:smart_hotel_app/repositories/room_statistics_repository.dart';

class ServiceIndexCubit extends Cubit<ServiceIndexState> {
  final RoomService _roomService;
  final RoomStatisticsService _statisticsService;
  final Map<String, List<Map<String, dynamic>>> _roomCache = {};
  List<FloorAreaBO> _floorAreasCache = [];

  ServiceIndexCubit()
      : _roomService = RoomService(repository: RoomRepository()),
        _statisticsService = RoomStatisticsService(
          repository: RoomStatisticsRepository(),
        ),
        super(const ServiceIndexState()) {
    _init();
  }

  Future<void> _init() async {
    await Future.wait([
      loadStatistics(),
      loadFloorAndAreas(),
    ]);
  }

  Future<void> reloadAll() async {
    await Future.wait([
      loadStatistics(),
      loadFloorAndAreas(),
    ]);
  }

  /// 加载客房服务看板-统计数据（待响应、入住中、空闲可清洁）
  Future<void> loadStatistics() async {
    emit(state.copyWith(isLoading: true, error: null));
    try {
      final stats = await _statisticsService.getStatistics();
      emit(state.copyWith(
        isLoading: false,
        pendingCount: stats.pendingResponseCount,
        occupiedRooms: stats.occupiedCount,
        vacantRooms: stats.vacantCleanableCount,
      ));
    } catch (e) {
      emit(state.copyWith(isLoading: false, error: e.toString()));
    }
  }

  /// 加载楼层和区域信息（仅进入页面时调用一次）
  Future<void> loadFloorAndAreas() async {
    emit(state.copyWith(isLoading: true, error: null));
    try {
      final floorAreas = await _roomService.getFloorAreas();
      _floorAreasCache = floorAreas;

      final floors = floorAreas.map((f) => {f.floorId: f.floorId.toString()}).toList();

      emit(state.copyWith(
        isLoading: false,
        floors: floors,
      ));

      // 默认选中第一个楼层，加载其房间数据
      if (floors.isNotEmpty) {
        final firstFloor = floors.first;
        final firstFloorId = firstFloor.keys.first;
        final firstFloorLabel = firstFloor.values.first;
        _updateAreasForFloor(firstFloorLabel);
        selectFloor(firstFloorLabel);
        await loadRooms(floorId: firstFloorId);
      }
    } catch (e) {
      emit(state.copyWith(isLoading: false, error: e.toString()));
    }
  }

  /// 根据选中的楼层更新 areas
  void _updateAreasForFloor(String floorLabel) {
    final matched = _floorAreasCache.where(
      (f) => f.floorId.toString() == floorLabel,
    );
    final areas = matched.isNotEmpty ? matched.first.areas : <String>[];
    emit(state.copyWith(areas: areas));
  }

  /// 加载房间状态列表
  Future<void> loadRooms({
    int? floorId,
    String? areaType,
  }) async {
    emit(state.copyWith(isLoading: true, error: null));
    try {
      final roomStatuses = await _roomService.getRoomStatus(
        floorId: floorId,
        areaType: areaType,
      );

      // 如果指定了楼层，直接缓存到对应楼层key下
      if (floorId != null) {
        final floorKey = floorId.toString();
        // 更新该楼层的房间数据到 _roomCache
        final updatedAllRooms = <Map<String, dynamic>>[];
        for (final rs in roomStatuses) {
          updatedAllRooms.add(_statusBoToRoomMap(rs));
        }
        _roomCache[floorKey] = updatedAllRooms;
      } else {
        // 未指定楼层，按房间号提取楼层归类（兜底）
        _roomCache.clear();
        for (final floorMap in (state.floors ?? [])) {
          _roomCache[floorMap.values.first] = [];
        }
        for (final rs in roomStatuses) {
          final floorNum = _extractFloor(rs.roomNumber);
          final floorKey = floorNum.toString();
          _roomCache.putIfAbsent(floorKey, () => []);
          _roomCache[floorKey]!.add(_statusBoToRoomMap(rs));
        }
      }

      // 展平所有房间用于全量展示（可被页面直接使用）
      final allRooms = <Map<String, dynamic>>[];
      for (final floorMap in (state.floors ?? [])) {
        final floorLabel = floorMap.values.first;
        allRooms.addAll(_roomCache[floorLabel] ?? []);
      }
      emit(state.copyWith(isLoading: false, rooms: allRooms));
    } catch (e) {
      emit(state.copyWith(isLoading: false, error: e.toString()));
    }
  }

  /// 将 RoomStatusBO 转为页面所需的 Map
  Map<String, dynamic> _statusBoToRoomMap(RoomStatusBO rs) {
    // 状态映射：cleanStatus "2" → 待清洁，occupancyStatus "1" → 入住，其余为 空闲
    String displayStatus;
    if (rs.cleanStatus == '2') {
      displayStatus = '待清洁';
    } else if (rs.occupancyStatus == '1') {
      displayStatus = '入住';
    } else {
      displayStatus = '空闲';
    }

    return {
      'roomId': rs.roomId,
      'number': rs.roomNumber,
      'status': displayStatus,
      'type': '客房', // 默认类型，后续可通过楼层areas信息扩展
    };
  }

  /// 从房间号提取楼层，如 "301" → 3
  int _extractFloor(String roomNumber) {
    if (roomNumber.length >= 2) {
      final match = RegExp(r'^(\d+)').firstMatch(roomNumber);
      if (match != null) {
        final num = int.tryParse(match.group(1) ?? '');
        if (num != null) {
          if (num > 100) {
            return num ~/ 100;
          }
          return num;
        }
      }
    }
    return 1;
  }

  List<Map<String, dynamic>> getRoomsByFloor(String floor) {
    return _roomCache[floor] ?? [];
  }

  void selectFloor(String? floor) {
    emit(state.copyWith(selectedFloor: floor));
    if (floor != null) {
      _updateAreasForFloor(floor);
    }
  }

  void selectType(String? type) {
    emit(state.copyWith(selectedType: type));
  }

  /// 加载非客房-相关楼层区域设备
  Future<void> loadAreaDevices({
    required int floorId,
    required String areaType,
  }) async {
    emit(state.copyWith(isLoadingAreaDevices: true, error: null));
    try {
      final devices = await _roomService.getAreaDevices(
        floorId: floorId,
        areaType: areaType,
      );
      emit(state.copyWith(
        isLoadingAreaDevices: false,
        areaDevices: devices,
      ));
    } catch (e) {
      emit(state.copyWith(
        isLoadingAreaDevices: false,
        error: e.toString(),
      ));
    }
  }

  void selectRoom(String? room) {
    emit(state.copyWith(selectedRoom: room));
  }

  void setSearchText(String text) {
    emit(state.copyWith(searchText: text));
  }

  Future<void> powerOnRoom(String roomNumber) async {
    if (state.isPoweringOn || state.isPoweringOff) return;
    emit(state.copyWith(isPoweringOn: true));
    try {
      final room = _findRoomByNumber(roomNumber);
      if (room == null) {
        throw Exception('未找到房间信息');
      }
      await _roomService.powerOn(roomId: room['roomId'] as int);
      emit(state.copyWith(isPoweringOn: false));
    } catch (e) {
      emit(state.copyWith(isPoweringOn: false));
      rethrow;
    }
  }

  Future<void> powerOffRoom(String roomNumber) async {
    if (state.isPoweringOff || state.isPoweringOn) return;
    emit(state.copyWith(isPoweringOff: true));
    try {
      final room = _findRoomByNumber(roomNumber);
      if (room == null) {
        throw Exception('未找到房间信息');
      }
      await _roomService.powerOff(roomId: room['roomId'] as int);
      emit(state.copyWith(isPoweringOff: false));
    } catch (e) {
      emit(state.copyWith(isPoweringOff: false));
      rethrow;
    }
  }

  /// 从缓存中根据房号查找房间数据
  Map<String, dynamic>? _findRoomByNumber(String roomNumber) {
    for (final rooms in _roomCache.values) {
      for (final room in rooms) {
        if (room['number'] == roomNumber) {
          return room;
        }
      }
    }
    return null;
  }
}
