import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter/material.dart';
import 'package:smart_hotel_app/views/service/room/cubit/service_room_state.dart';

class ServiceRoomCubit extends Cubit<ServiceRoomState> {
  final String? roomNumber;

  ServiceRoomCubit({this.roomNumber}) : super(const ServiceRoomState()) {
    initData();
  }

  void initData() {
    final num = roomNumber ?? '302';
    final numInt = int.tryParse(num) ?? 302;
    final statuses = ['空闲', '入住中', '待清洁'];
    final statusIndex = numInt % 3;

    emit(state.copyWith(
      roomNumber: num,
      roomStatus: statuses[statusIndex],
      mainPowerOn: numInt % 2 == 0,
      roomDevices: [
        const RoomDevice(
          name: '空调',
          icon: Icons.air_outlined,
          isOn: true,
          statusText: '24°C·开',
        ),
        const RoomDevice(
          name: '照明',
          icon: Icons.light_outlined,
          isOn: false,
          statusText: '关',
        ),
        const RoomDevice(
          name: '电视',
          icon: Icons.tv_outlined,
          isOn: true,
          statusText: '开',
        ),
        const RoomDevice(
          name: '窗帘',
          icon: Icons.curtains_closed_outlined,
          isOn: false,
          statusText: '关',
        ),
      ],
      controlDevices: [
        const ControlDevice(
          name: '空调',
          icon: Icons.air_outlined,
          isOn: true,
          detailText: '当前:制冷24°C·风速:自动',
        ),
        const ControlDevice(
          name: '主照明',
          icon: Icons.light_outlined,
          isOn: false,
        ),
        const ControlDevice(
          name: '电视',
          icon: Icons.tv_outlined,
          isOn: true,
        ),
      ],
    ));
  }

  void toggleMainPower(bool value) {
    emit(state.copyWith(mainPowerOn: value));
  }

  void toggleControlDevice(int index, bool value) {
    final updatedDevices = List<ControlDevice>.from(state.controlDevices);
    if (index >= 0 && index < updatedDevices.length) {
      updatedDevices[index] = ControlDevice(
        name: updatedDevices[index].name,
        icon: updatedDevices[index].icon,
        isOn: value,
        detailText: updatedDevices[index].detailText,
      );
      emit(state.copyWith(controlDevices: updatedDevices));
    }
  }
}