import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:smart_hotel_app/models/bo/ac_bo.dart';
import 'package:smart_hotel_app/repositories/ac_repository.dart';
import 'package:smart_hotel_app/services/ac_service.dart';
import 'package:smart_hotel_app/views/service/device/cubit/service_device_state.dart';

class ServiceDeviceCubit extends Cubit<ServiceDeviceState> {
  final AcService _service;
  final int _deviceId;

  ServiceDeviceCubit({
    AcService? service,
    required int deviceId,
  })  : _service = service ?? AcService(repository: AcRepository()),
        _deviceId = deviceId,
        super(ServiceDeviceState(deviceId: deviceId)) {
    loadAcStatus();
  }

  /// 加载空调状态
  Future<void> loadAcStatus() async {
    emit(state.copyWith(isLoading: true, clearError: true));
    try {
      final status = await _service.getStatus(deviceId: _deviceId);
      emit(_mapStatusToState(status));
    } catch (e) {
      emit(state.copyWith(isLoading: false, error: e.toString()));
    }
  }

  /// 将 API 返回的 AcStatusBO 映射为 State
  ServiceDeviceState _mapStatusToState(AcStatusBO status) {
    // 构建模式数据列表
    const allModes = ['制冷', '制热', '除湿', '送风'];
    final currentModeName = AcModeMapper.modeTextFromCode(status.mode);
    final modeData = allModes.map((name) {
      return {
        'name': name,
        'icon': _modeIcon(name),
        'isSelected': name == currentModeName,
      };
    }).toList();

    // 解析温度
    final currentTemp = status.currentTempInt;
    final targetTemp = status.targetTempInt;

    // 获取当前风速的 UI 名称
    final currentSpeed = AcModeMapper.fanSpeedTextFromGetCode(status.fanSpeed);

    return ServiceDeviceState(
      isLoading: false,
      deviceId: _deviceId,
      isOn: status.isPowerOn,
      currentTemperature: currentTemp > 0 ? currentTemp : 26,
      targetTemperature: targetTemp > 0 ? targetTemp : 24,
      minTemperature: 16,
      maxTemperature: 30,
      modeData: modeData,
      currentSpeed: currentSpeed,
      speedOptions: const ['自动', '低', '中', '高'],
    );
  }

  /// 获取模式对应的图标
  IconData _modeIcon(String modeName) {
    switch (modeName) {
      case '制冷':
        return Icons.ac_unit;
      case '制热':
        return Icons.heat_pump;
      case '除湿':
        return Icons.water_drop;
      case '送风':
        return Icons.air;
      default:
        return Icons.ac_unit;
    }
  }

  /// 开关机
  Future<void> togglePower(bool value) async {
    if (state.isOperating) return;
    // 乐观更新 UI
    final previousState = state;
    emit(state.copyWith(isOn: value, isOperating: true));
    try {
      await _service.control(
        deviceId: _deviceId,
        powerOn: value,
      );
      emit(state.copyWith(isOperating: false));
    } catch (e) {
      // 失败时回滚状态
      emit(previousState.copyWith(
        isOperating: false,
        error: e.toString(),
      ));
    }
  }

  /// 设置目标温度
  Future<void> _setTargetTemperature(int temp) async {
    if (state.isOperating) return;
    if (temp < state.minTemperature || temp > state.maxTemperature) return;
    final previousState = state;
    emit(state.copyWith(targetTemperature: temp, isOperating: true));
    try {
      await _service.control(
        deviceId: _deviceId,
        targetTemperature: temp,
      );
      emit(state.copyWith(isOperating: false));
    } catch (e) {
      emit(previousState.copyWith(
        isOperating: false,
        error: e.toString(),
      ));
    }
  }

  void increaseTemperature() {
    if (state.targetTemperature < state.maxTemperature) {
      _setTargetTemperature(state.targetTemperature + 1);
    }
  }

  void decreaseTemperature() {
    if (state.targetTemperature > state.minTemperature) {
      _setTargetTemperature(state.targetTemperature - 1);
    }
  }

  /// 选择模式
  Future<void> selectMode(int index) async {
    if (state.isOperating) return;
    if (index < 0 || index >= state.modeData.length) return;

    final previousState = state;
    final updatedModeData = state.modeData.map((mode) {
      return {...mode, 'isSelected': false};
    }).toList();
    updatedModeData[index]['isSelected'] = true;
    final modeName = updatedModeData[index]['name'] as String;

    emit(state.copyWith(modeData: updatedModeData, isOperating: true));
    try {
      await _service.control(
        deviceId: _deviceId,
        mode: AcModeMapper.postModeFromUi(modeName),
      );
      emit(state.copyWith(isOperating: false));
    } catch (e) {
      emit(previousState.copyWith(
        isOperating: false,
        error: e.toString(),
      ));
    }
  }

  /// 设置风速
  Future<void> setWindSpeed(String speed) async {
    if (state.isOperating) return;

    final previousState = state;
    emit(state.copyWith(currentSpeed: speed, isOperating: true));
    try {
      await _service.control(
        deviceId: _deviceId,
        fanSpeed: AcModeMapper.postFanSpeedFromUi(speed),
      );
      emit(state.copyWith(isOperating: false));
    } catch (e) {
      emit(previousState.copyWith(
        isOperating: false,
        error: e.toString(),
      ));
    }
  }
}
