import 'dart:async';

import 'package:bloc/bloc.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:meta/meta.dart';
import 'package:syncrow_web/pages/device_managment/all_devices/models/device_status.dart';
import 'package:syncrow_web/pages/device_managment/all_devices/models/factory_reset_model.dart';
import 'package:syncrow_web/pages/device_managment/one_g_glass_switch/models/once_gang_glass_status_model.dart';
import 'package:syncrow_web/services/devices_mang_api.dart';

part 'one_gang_glass_switch_event.dart';
part 'one_gang_glass_switch_state.dart';

class OneGangGlassSwitchBloc
    extends Bloc<OneGangGlassSwitchEvent, OneGangGlassSwitchState> {
  OneGangGlassStatusModel deviceStatus;
  Timer? _timer;

  OneGangGlassSwitchBloc({required String deviceId})
      : deviceStatus = OneGangGlassStatusModel(
            uuid: deviceId, switch1: false, countDown: 0),
        super(OneGangGlassSwitchInitial()) {
    on<OneGangGlassSwitchFetchDeviceEvent>(_onFetchDeviceStatus);
    on<OneGangGlassSwitchControl>(_onControl);
    on<OneGangGlassSwitchBatchControl>(_onBatchControl);
    on<OneGangGlassSwitchFetchBatchStatusEvent>(_onFetchBatchStatus);
    on<OneGangGlassFactoryResetEvent>(_onFactoryReset);
    on<StatusUpdated>(_onStatusUpdated);
  }

  Future<void> _onFetchDeviceStatus(OneGangGlassSwitchFetchDeviceEvent event,
      Emitter<OneGangGlassSwitchState> emit) async {
    emit(OneGangGlassSwitchLoading());
    try {
      final status =
          await DevicesManagementApi().getDeviceStatus(event.deviceId);
      _listenToChanges(event.deviceId);
      deviceStatus =
          OneGangGlassStatusModel.fromJson(event.deviceId, status.status);
      emit(OneGangGlassSwitchStatusLoaded(deviceStatus));
    } catch (e) {
      emit(OneGangGlassSwitchError(e.toString()));
    }
  }

  _listenToChanges(deviceId) {
    try {
      DatabaseReference ref =
          FirebaseDatabase.instance.ref('device-status/$deviceId');
      Stream<DatabaseEvent> stream = ref.onValue;

      stream.listen((DatabaseEvent event) {
        Map<dynamic, dynamic> usersMap =
            event.snapshot.value as Map<dynamic, dynamic>;

        List<Status> statusList = [];
        usersMap['status'].forEach((element) {
          statusList
              .add(Status(code: element['code'], value: element['value']));
        });

        deviceStatus = OneGangGlassStatusModel.fromJson(
            usersMap['productUuid'], statusList);
        if (!isClosed) {
          add(StatusUpdated(deviceStatus));
        }
      });
    } catch (_) {}
  }

  void _onStatusUpdated(
      StatusUpdated event, Emitter<OneGangGlassSwitchState> emit) {
    deviceStatus = event.deviceStatus;
    emit(OneGangGlassSwitchStatusLoaded(deviceStatus));
  }

  Future<void> _onControl(OneGangGlassSwitchControl event,
      Emitter<OneGangGlassSwitchState> emit) async {
    final oldValue = _getValueByCode(event.code);

    _updateLocalValue(event.code, event.value);
    emit(OneGangGlassSwitchStatusLoaded(deviceStatus));

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

  Future<void> _onFactoryReset(OneGangGlassFactoryResetEvent event,
      Emitter<OneGangGlassSwitchState> emit) async {
    emit(OneGangGlassSwitchLoading());
    try {
      final response = await DevicesManagementApi()
          .factoryReset(event.factoryReset, event.deviceId);
      if (!response) {
        emit(OneGangGlassSwitchError('Failed to reset device'));
      } else {
        emit(OneGangGlassSwitchStatusLoaded(deviceStatus));
      }
    } catch (e) {
      emit(OneGangGlassSwitchError(e.toString()));
    }
  }

  Future<void> _onBatchControl(OneGangGlassSwitchBatchControl event,
      Emitter<OneGangGlassSwitchState> emit) async {
    final oldValue = _getValueByCode(event.code);

    _updateLocalValue(event.code, event.value);
    emit(OneGangGlassSwitchStatusLoaded(deviceStatus));

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

  Future<void> _onFetchBatchStatus(
      OneGangGlassSwitchFetchBatchStatusEvent event,
      Emitter<OneGangGlassSwitchState> emit) async {
    emit(OneGangGlassSwitchLoading());
    try {
      final status =
          await DevicesManagementApi().getBatchStatus(event.deviceIds);
      deviceStatus = OneGangGlassStatusModel.fromJson(
          event.deviceIds.first, status.status);
      emit(OneGangGlassSwitchStatusLoaded(deviceStatus));
    } catch (e) {
      emit(OneGangGlassSwitchError(e.toString()));
    }
  }

  Future<void> _runDebounce({
    required dynamic deviceId,
    required String code,
    required bool value,
    required bool oldValue,
    required Emitter<OneGangGlassSwitchState> emit,
    required bool isBatch,
  }) async {
    late String id;
    if (deviceId is List) {
      id = deviceId.first;
    } else {
      id = deviceId;
    }

    if (_timer != null) {
      _timer!.cancel();
    }

    _timer = Timer(const Duration(milliseconds: 500), () async {
      try {
        late bool response;
        if (isBatch) {
          response = await DevicesManagementApi()
              .deviceBatchControl(deviceId, code, value);
        } else {
          response = await DevicesManagementApi()
              .deviceControl(deviceId, Status(code: code, value: value));
        }

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

  void _revertValueAndEmit(String deviceId, String code, bool oldValue,
      Emitter<OneGangGlassSwitchState> emit) {
    _updateLocalValue(code, oldValue);
    emit(OneGangGlassSwitchStatusLoaded(deviceStatus));
  }

  void _updateLocalValue(String code, bool value) {
    if (code == 'switch_1') {
      deviceStatus = deviceStatus.copyWith(switch1: value);
    }
  }

  bool _getValueByCode(String code) {
    switch (code) {
      case 'switch_1':
        return deviceStatus.switch1;
      default:
        return false;
    }
  }

  @override
  Future<void> close() {
    _timer?.cancel();
    return super.close();
  }
}
