import 'dart:async';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/device_managment/all_devices/models/device_status.dart';
import 'package:syncrow_web/pages/device_managment/curtain/bloc/curtain_event.dart';
import 'package:syncrow_web/pages/device_managment/curtain/bloc/curtain_state.dart';
import 'package:syncrow_web/services/devices_mang_api.dart';

class CurtainBloc extends Bloc<CurtainEvent, CurtainState> {
  late bool deviceStatus;
  final String deviceId;
  Timer? _timer;

  CurtainBloc({required this.deviceId}) : super(CurtainInitial()) {
    on<CurtainFetchDeviceStatus>(_onFetchDeviceStatus);
    on<CurtainControl>(_onCurtainControl);
  }

  FutureOr<void> _onFetchDeviceStatus(
      CurtainFetchDeviceStatus event, Emitter<CurtainState> emit) async {
    emit(CurtainStatusLoading());
    try {
      final status =
          await DevicesManagementApi().getDeviceStatus(event.deviceId);

      deviceStatus = _checkStatus(status.status[0].value);

      emit(CurtainStatusLoaded(deviceStatus));
    } catch (e) {
      emit(CurtainError(e.toString()));
    }
  }

  FutureOr<void> _onCurtainControl(
      CurtainControl event, Emitter<CurtainState> emit) async {
    final oldValue = deviceStatus;

    _updateLocalValue(event.value, emit);

    emit(CurtainStatusLoaded(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 bool value,
    required bool oldValue,
    required Emitter<CurtainState> emit,
  }) async {
    if (_timer != null) {
      _timer!.cancel();
    }
    _timer = Timer(const Duration(seconds: 1), () async {
      try {
        final controlValue = value ? 'open' : 'close';

        final response = await DevicesManagementApi()
            .deviceControl(deviceId, Status(code: code, value: controlValue));

        if (!response) {
          _revertValueAndEmit(deviceId, oldValue, emit);
        }
      } catch (e) {
        _revertValueAndEmit(deviceId, oldValue, emit);
      }
    });
  }

  void _revertValueAndEmit(
      String deviceId, bool oldValue, Emitter<CurtainState> emit) {
    _updateLocalValue(oldValue, emit);
    emit(CurtainStatusLoaded(deviceStatus));
    emit(const CurtainControlError('Failed to control the device.'));
  }

  void _updateLocalValue(bool value, Emitter<CurtainState> emit) {
    deviceStatus = value;
    emit(CurtainStatusLoaded(deviceStatus));
  }

  bool _checkStatus(String command) {
    return command.toLowerCase() == 'open';
  }
}
