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/one_gang_switch/bloc/wall_light_switch_event.dart';
import 'package:syncrow_web/pages/device_managment/one_gang_switch/bloc/wall_light_switch_state.dart';
import 'package:syncrow_web/pages/device_managment/one_gang_switch/models/wall_light_status_model.dart';
import 'package:syncrow_web/services/devices_mang_api.dart';

class WallLightSwitchBloc
    extends Bloc<WallLightSwitchEvent, WallLightSwitchState> {
  WallLightSwitchBloc({required this.deviceId})
      : super(WallLightSwitchInitial()) {
    on<WallLightSwitchFetchDeviceEvent>(_onFetchDeviceStatus);
    on<WallLightSwitchControl>(_onControl);
    on<WallLightSwitchFetchBatchEvent>(_onFetchBatchStatus);
    on<WallLightSwitchBatchControl>(_onBatchControl);
    on<WallLightFactoryReset>(_onFactoryReset);
    on<StatusUpdated>(_onStatusUpdated);
  }

  late WallLightStatusModel deviceStatus;
  final String deviceId;
  Timer? _timer;

  FutureOr<void> _onFetchDeviceStatus(WallLightSwitchFetchDeviceEvent event,
      Emitter<WallLightSwitchState> emit) async {
    emit(WallLightSwitchLoading());
    try {
      final status =
          await DevicesManagementApi().getDeviceStatus(event.deviceId);

      deviceStatus =
          WallLightStatusModel.fromJson(event.deviceId, status.status);
      _listenToChanges(event.deviceId);
      emit(WallLightSwitchStatusLoaded(deviceStatus));
    } catch (e) {
      emit(WallLightSwitchError(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 =
            WallLightStatusModel.fromJson(usersMap['productUuid'], statusList);
        if (!isClosed) {
          add(StatusUpdated(deviceStatus));
        }
      });
    } catch (_) {}
  }

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

  FutureOr<void> _onControl(
      WallLightSwitchControl event, Emitter<WallLightSwitchState> emit) async {
    final oldValue = _getValueByCode(event.code);

    _updateLocalValue(event.code, event.value);

    emit(WallLightSwitchStatusLoaded(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 bool value,
    required bool oldValue,
    required Emitter<WallLightSwitchState> 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<WallLightSwitchState> emit) {
    _updateLocalValue(code, oldValue);
    emit(WallLightSwitchStatusLoaded(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;
    }
  }

  Future<void> _onFetchBatchStatus(WallLightSwitchFetchBatchEvent event,
      Emitter<WallLightSwitchState> emit) async {
    emit(WallLightSwitchLoading());
    try {
      final status =
          await DevicesManagementApi().getBatchStatus(event.devicesIds);
      deviceStatus =
          WallLightStatusModel.fromJson(event.devicesIds.first, status.status);
      emit(WallLightSwitchStatusLoaded(deviceStatus));
    } catch (e) {
      emit(WallLightSwitchError(e.toString()));
    }
  }

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

  FutureOr<void> _onBatchControl(WallLightSwitchBatchControl event,
      Emitter<WallLightSwitchState> emit) async {
    final oldValue = _getValueByCode(event.code);

    _updateLocalValue(event.code, event.value);

    emit(WallLightSwitchStatusLoaded(deviceStatus));

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

  FutureOr<void> _onFactoryReset(
      WallLightFactoryReset event, Emitter<WallLightSwitchState> emit) async {
    emit(WallLightSwitchLoading());
    try {
      final response = await DevicesManagementApi().factoryReset(
        event.factoryReset,
        event.deviceId,
      );
      if (!response) {
        emit(WallLightSwitchError('Failed'));
      } else {
        emit(WallLightSwitchStatusLoaded(deviceStatus));
      }
    } catch (e) {
      emit(WallLightSwitchError(e.toString()));
    }
  }
}
