// ignore_for_file: invalid_use_of_visible_for_testing_member

import 'dart:async';
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:syncrow_web/pages/device_managment/all_devices/models/device_status.dart';
import 'package:syncrow_web/pages/device_managment/three_gang_switch/models/living_room_model.dart';
import 'package:syncrow_web/services/devices_mang_api.dart';

part 'living_room_event.dart';
part 'living_room_state.dart';

class LivingRoomBloc extends Bloc<LivingRoomEvent, LivingRoomState> {
  late LivingRoomStatusModel deviceStatus;
  final String deviceId;
  Timer? _timer;

  LivingRoomBloc({required this.deviceId}) : super(LivingRoomInitial()) {
    on<LivingRoomFetchDeviceStatus>(_onFetchDeviceStatus);
    on<LivingRoomControl>(_livingRoomControl);
  }

  FutureOr<void> _onFetchDeviceStatus(
      LivingRoomFetchDeviceStatus event, Emitter<LivingRoomState> emit) async {
    emit(LivingRoomDeviceStatusLoading());
    try {
      final status = await DevicesManagementApi().getDeviceStatus(event.deviceId);
      deviceStatus = LivingRoomStatusModel.fromJson(event.deviceId, status.status);
      emit(LivingRoomDeviceStatusLoaded(deviceStatus));
    } catch (e) {
      emit(LivingRoomDeviceManagementError(e.toString()));
    }
  }

  FutureOr<void> _livingRoomControl(LivingRoomControl event, Emitter<LivingRoomState> emit) async {
    final oldValue = _getValueByCode(event.code);

    _updateLocalValue(event.code, event.value);

    emit(LivingRoomDeviceStatusLoaded(deviceStatus));

    await _runDebounce(
      deviceId: event.deviceId,
      code: event.code,
      value: event.value,
      oldValue: oldValue,
      emit: emit,
    );
  }

  Future<void> _runDebounce({
    required String deviceId,
    required String code,
    required dynamic value,
    required dynamic oldValue,
    required Emitter<LivingRoomState> emit,
  }) async {
    if (_timer != null) {
      _timer!.cancel();
    }
    _timer = Timer(const Duration(seconds: 1), () async {
      try {
        final response =
            await DevicesManagementApi().deviceControl(deviceId, Status(code: code, value: value));
        if (!response) {
          _revertValueAndEmit(deviceId, code, oldValue, emit);
        }
      } catch (e) {
        _revertValueAndEmit(deviceId, code, oldValue, emit);
      }
    });
  }

  void _revertValueAndEmit(
      String deviceId, String code, dynamic oldValue, Emitter<LivingRoomState> emit) {
    _updateLocalValue(code, oldValue);
    emit(LivingRoomDeviceStatusLoaded(deviceStatus));
    emit(const LivingRoomControlError('Failed to control the device.'));
  }

  void _updateLocalValue(String code, dynamic value) {
    switch (code) {
      case 'switch_1':
        if (value is bool) {
          deviceStatus = deviceStatus.copyWith(switch1: value);
        }
        break;
      case 'switch_2':
        if (value is bool) {
          deviceStatus = deviceStatus.copyWith(switch2: value);
        }
        break;
      case 'switch_3':
        if (value is bool) {
          deviceStatus = deviceStatus.copyWith(switch3: value);
        }
        break;
      default:
        break;
    }
    emit(LivingRoomDeviceStatusLoaded(deviceStatus));
  }

  dynamic _getValueByCode(String code) {
    switch (code) {
      case 'switch_1':
        return deviceStatus.switch1;
      case 'switch_2':
        return deviceStatus.switch2;
      case 'switch_3':
        return deviceStatus.switch3;
      default:
        return null;
    }
  }
}
