// ignore_for_file: invalid_use_of_visible_for_testing_member

import 'dart:async';
import 'package:firebase_database/firebase_database.dart';
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/door_lock/bloc/door_lock_event.dart';
import 'package:syncrow_web/pages/device_managment/door_lock/bloc/door_lock_state.dart';
import 'package:syncrow_web/pages/device_managment/door_lock/models/door_lock_status_model.dart';
import 'package:syncrow_web/services/devices_mang_api.dart';

class DoorLockBloc extends Bloc<DoorLockEvent, DoorLockState> {
  late DoorLockStatusModel deviceStatus;
  final String deviceId;
  Timer? _timer;

  DoorLockBloc({required this.deviceId}) : super(DoorLockInitial()) {
    on<DoorLockFetchStatus>(_onFetchDeviceStatus);
    //on<DoorLockControl>(_onDoorLockControl);
    on<UpdateLockEvent>(_updateLock);
    on<DoorLockFactoryReset>(_onFactoryReset);
    on<StatusUpdated>(_onStatusUpdated);
  }

  _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 =
            DoorLockStatusModel.fromJson(usersMap['productUuid'], statusList);
        if (!isClosed) {
          add(StatusUpdated(deviceStatus));
        }
      });
    } catch (_) {}
  }

  void _onStatusUpdated(StatusUpdated event, Emitter<DoorLockState> emit) {
    emit(DoorLockStatusLoading());

    deviceStatus = event.deviceStatus;
    emit(DoorLockStatusLoaded(deviceStatus));
  }

  FutureOr<void> _onFetchDeviceStatus(
      DoorLockFetchStatus event, Emitter<DoorLockState> emit) async {
    emit(DoorLockStatusLoading());
    try {
      final status =
          await DevicesManagementApi().getDeviceStatus(event.deviceId);
      deviceStatus =
          DoorLockStatusModel.fromJson(event.deviceId, status.status);
      _listenToChanges(event.deviceId);

      emit(DoorLockStatusLoaded(deviceStatus));
    } catch (e) {
      emit(DoorLockControlError(e.toString()));
    }
  }

  FutureOr<void> _updateLock(
      UpdateLockEvent event, Emitter<DoorLockState> emit) async {
    final oldValue = deviceStatus.normalOpenSwitch;
    deviceStatus = deviceStatus.copyWith(normalOpenSwitch: !oldValue);
    emit(DoorLockStatusLoaded(deviceStatus));

    try {
      final response = await DevicesManagementApi.openDoorLock(deviceId);

      if (!response) {
        _revertValueAndEmit(deviceId, 'normal_open_switch', oldValue, emit);
      }
    } catch (e) {
      _revertValueAndEmit(deviceId, 'normal_open_switch', oldValue, emit);
      emit(DoorLockControlError('Error controlling the lock: $e'));
    }
  }

  Future<void> _runDebounce({
    required String deviceId,
    required String code,
    required dynamic value,
    required dynamic oldValue,
    required Emitter<DoorLockState> 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<DoorLockState> emit,
  ) {
    _updateLocalValue(code, oldValue);
    emit(DoorLockStatusLoaded(deviceStatus));
    emit(const DoorLockControlError('Failed to control the device.'));
  }

  void _updateLocalValue(String code, dynamic value) {
    switch (code) {
      case 'reverse_lock':
        if (value is bool) {
          deviceStatus = deviceStatus.copyWith(reverseLock: value);
        }
        break;
      case 'normal_open_switch':
        if (value is bool) {
          deviceStatus = deviceStatus.copyWith(normalOpenSwitch: value);
        }
        break;
      default:
        break;
    }
    emit(DoorLockStatusLoaded(deviceStatus));
  }

  dynamic _getValueByCode(String code) {
    switch (code) {
      case 'reverse_lock':
        return deviceStatus.reverseLock;
      case 'normal_open_switch':
        return deviceStatus.normalOpenSwitch;
      default:
        return null;
    }
  }

  FutureOr<void> _onFactoryReset(
      DoorLockFactoryReset event, Emitter<DoorLockState> emit) async {
    emit(DoorLockStatusLoading());
    try {
      final response = await DevicesManagementApi().factoryReset(
        event.factoryReset,
        event.deviceId,
      );
      if (!response) {
        emit(const DoorLockControlError('Failed'));
      } else {
        add(DoorLockFetchStatus(event.deviceId));
      }
    } catch (e) {
      emit(DoorLockControlError(e.toString()));
    }
  }
}
