// 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:firebase_database/firebase_database.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/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<LivingRoomFetchDeviceStatusEvent>(_onFetchDeviceStatus);
    on<LivingRoomControl>(_livingRoomControl);
    on<LivingRoomBatchControl>(_livingRoomBatchControl);
    on<LivingRoomFetchBatchEvent>(_livingRoomFetchBatchControl);
    on<LivingRoomFactoryResetEvent>(_livingRoomFactoryReset);
    on<StatusUpdated>(_onStatusUpdated);
  }

  FutureOr<void> _onFetchDeviceStatus(LivingRoomFetchDeviceStatusEvent event,
      Emitter<LivingRoomState> emit) async {
    emit(LivingRoomDeviceStatusLoading());
    try {
      final status =
          await DevicesManagementApi().getDeviceStatus(event.deviceId);
      deviceStatus =
          LivingRoomStatusModel.fromJson(event.deviceId, status.status);
      _listenToChanges(deviceId);
      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,
      isBatch: false,
    );
  }

  Future<void> _runDebounce({
    required dynamic deviceId,
    required String code,
    required dynamic value,
    required dynamic oldValue,
    required Emitter<LivingRoomState> 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(seconds: 1), () 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, dynamic oldValue,
      Emitter<LivingRoomState> emit) {
    _updateLocalValue(code, oldValue);
    emit(LivingRoomDeviceStatusLoaded(deviceStatus));
  }

  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;
    }
  }

  FutureOr<void> _livingRoomFetchBatchControl(
      LivingRoomFetchBatchEvent event, Emitter<LivingRoomState> emit) async {
    emit(LivingRoomDeviceStatusLoading());
    try {
      final status =
          await DevicesManagementApi().getBatchStatus(event.devicesIds);
      deviceStatus =
          LivingRoomStatusModel.fromJson(event.devicesIds.first, status.status);
      // for (var deviceId in event.devicesIds) {
      //   _listenToChanges(deviceId);
      // }
      emit(LivingRoomDeviceStatusLoaded(deviceStatus));
    } catch (e) {
      emit(LivingRoomDeviceManagementError(e.toString()));
    }
  }

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

    _updateLocalValue(event.code, event.value);

    emit(LivingRoomDeviceStatusLoaded(deviceStatus));

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

  FutureOr<void> _livingRoomFactoryReset(
      LivingRoomFactoryResetEvent event, Emitter<LivingRoomState> emit) async {
    emit(LivingRoomDeviceStatusLoading());
    try {
      final response = await DevicesManagementApi().factoryReset(
        event.factoryReset,
        event.uuid,
      );
      if (!response) {
        emit(const LivingRoomDeviceManagementError('Failed'));
      } else {
        emit(LivingRoomDeviceStatusLoaded(deviceStatus));
      }
    } catch (e) {
      emit(LivingRoomDeviceManagementError(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 =
            LivingRoomStatusModel.fromJson(usersMap['productUuid'], statusList);
        if (!isClosed) {
          add(StatusUpdated(deviceStatus));
        }
      });
    } catch (_) {}
  }

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