import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:smart_hotel_app/models/bo/room_bo.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/service/room/cubit/service_room_state.dart';

class ServiceRoomCubit extends Cubit<ServiceRoomState> {
  final RoomService _service;
  final int _roomId;

  ServiceRoomCubit({
    RoomService? service,
    required int roomId,
    String roomNumber = '',
  })  : _service = service ??
            RoomService(repository: RoomRepository()),
        _roomId = roomId,
        super(ServiceRoomState(roomId: roomId, roomNumber: roomNumber)) {
    loadDetail();
  }

  Future<void> loadDetail() async {
    emit(state.copyWith(isLoading: true, error: null));
    try {
      final detail = await _service.getRoomDetail(roomId: _roomId);
      emit(_mapDetailToState(detail));
    } catch (e) {
      emit(state.copyWith(isLoading: false, error: e.toString()));
    }
  }

  ServiceRoomState _mapDetailToState(RoomDetailBO detail) {
    final basic = detail.roomBasicInfo;
    final statusTags = _buildStatusTags(
      occupancyStatus: basic.occupancyStatus,
      powerSupplyStatus: basic.powerSupplyStatus,
      wifiOnlineStatus: basic.wifiOnlineStatus,
    );

    final roomDevices = detail.deviceStatusList.map((d) {
      return RoomDevice(
        name: d.deviceName,
        icon: _mapDeviceIcon(d.deviceTypeName, d.deviceTypeIcon),
        isOn: d.powerStatus == '1' || d.powerStatus == 'on',
        statusText: _buildDeviceStatusText(d),
      );
    }).toList();

    final controlDevices = detail.deviceControl.subDeviceControls.map((c) {
      return ControlDevice(
        deviceId: c.deviceId,
        name: c.deviceName,
        icon: _mapDeviceIcon(c.deviceTypeName, ''),
        isOn: c.powerOn,
        detailText: c.currentParamDisplay.isNotEmpty ? c.currentParamDisplay : null,
        deviceTypeName: c.deviceTypeName,
      );
    }).toList();

    return state.copyWith(
      isLoading: false,
      roomNumber: basic.roomNumber,
      roomStatus: _mapOccupancyStatus(basic.occupancyStatus),
      statusTags: statusTags,
      roomDevices: roomDevices,
      mainPowerOn: detail.deviceControl.roomPowerControl.powerOn,
      controlDevices: controlDevices,
    );
  }

  List<RoomStatusTag> _buildStatusTags({
    required String occupancyStatus,
    required bool powerSupplyStatus,
    required String wifiOnlineStatus,
  }) {
    final tags = <RoomStatusTag>[];
    if (occupancyStatus == '1') {
      tags.add(RoomStatusTag.hasPerson);
    }
    if (powerSupplyStatus) {
      tags.add(RoomStatusTag.powerOn);
    }
    if (wifiOnlineStatus == '1' || wifiOnlineStatus == 'online') {
      tags.add(RoomStatusTag.wifiNormal);
    }
    return tags;
  }

  String _buildDeviceStatusText(DeviceStatusBO d) {
    if (d.powerStatusText.isNotEmpty) {
      return d.powerStatusText;
    }
    if (d.runStatusText.isNotEmpty) {
      return d.runStatusText;
    }
    if (d.deviceParams != null) {
      final p = d.deviceParams!;
      final parts = <String>[];
      if (p.temperature.isNotEmpty) parts.add('${p.temperature}°C');
      if (p.mode.isNotEmpty) parts.add(p.mode);
      return parts.join('·');
    }
    return '';
  }

  String _mapOccupancyStatus(String status) {
    switch (status) {
      case '1':
        return '入住中';
      case '0':
      default:
        return '空闲';
    }
  }

  IconData _mapDeviceIcon(String deviceTypeName, String deviceTypeIcon) {
    // Try to match by deviceTypeName first
    final name = deviceTypeName.toLowerCase();
    if (name.contains('空调') || name.contains('air')) {
      return Icons.air_outlined;
    }
    if (name.contains('照明') || name.contains('灯') || name.contains('light')) {
      return Icons.light_outlined;
    }
    if (name.contains('电视') || name.contains('tv')) {
      return Icons.tv_outlined;
    }
    if (name.contains('窗帘') || name.contains('curtain')) {
      return Icons.curtains_closed_outlined;
    }

    // Fallback: match by deviceTypeIcon string
    final icon = deviceTypeIcon.toLowerCase();
    if (icon.contains('air') || icon.contains('ac')) {
      return Icons.air_outlined;
    }
    if (icon.contains('light')) {
      return Icons.light_outlined;
    }
    if (icon.contains('tv')) {
      return Icons.tv_outlined;
    }
    if (icon.contains('curtain')) {
      return Icons.curtains_closed_outlined;
    }

    return Icons.devices_other;
  }

    /// 房间总电源开关
  Future<void> toggleMainPowerForSwitch(bool value) async {
    if (state.isTogglingPower) return;
    emit(state.copyWith(isTogglingPower: true));
    try {
      if (value) {
        await _service.roomPowerOn(roomId: _roomId);
      } else {
        await _service.roomPowerOff(roomId: _roomId);
      }
      emit(state.copyWith(isTogglingPower: false, mainPowerOn: value));
    } catch (e) {
      emit(state.copyWith(isTogglingPower: false));
      // Re-throw so the view can show error snackbar
      rethrow;
    }
  }

  /// 房间总电源开关
  Future<void> toggleMainPower(bool value) async {
    if (state.isTogglingPower) return;
    emit(state.copyWith(isTogglingPower: true));
    try {
      if (value) {
        await _service.powerOn(roomId: _roomId);
      } else {
        await _service.powerOff(roomId: _roomId);
      }
      emit(state.copyWith(isTogglingPower: false, mainPowerOn: value));
    } catch (e) {
      emit(state.copyWith(isTogglingPower: false));
      // Re-throw so the view can show error snackbar
      rethrow;
    }
  }

  /// 分设备电源开关
  Future<void> toggleControlDevice(int index, bool value) async {
    final devices = state.controlDevices;
    if (index < 0 || index >= devices.length) return;
    // Note: The API for individual device power control uses deviceId.
    // However, we don't have deviceId in ControlDevice model yet.
    // For now, just update UI state. The device control card in the view
    // navigates to ServiceDeviceDetailRoute for AC control.
    final updatedDevices = List<ControlDevice>.from(devices);
    updatedDevices[index] = ControlDevice(
      deviceId: updatedDevices[index].deviceId,
      name: updatedDevices[index].name,
      icon: updatedDevices[index].icon,
      isOn: value,
      detailText: updatedDevices[index].detailText,
      deviceTypeName: updatedDevices[index].deviceTypeName,
    );
    emit(state.copyWith(controlDevices: updatedDevices));
  }
}
