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/two_gang_switch/bloc/two_gang_switch_event.dart';
import 'package:syncrow_web/pages/device_managment/two_gang_switch/bloc/two_gang_switch_state.dart';
import 'package:syncrow_web/pages/device_managment/two_gang_switch/models/two_gang_status_model.dart';
import 'package:syncrow_web/services/devices_mang_api.dart';

class TwoGangSwitchBloc extends Bloc<TwoGangSwitchEvent, TwoGangSwitchState> {
  TwoGangSwitchBloc({required this.deviceId}) : super(TwoGangSwitchInitial()) {
    on<TwoGangSwitchFetchDeviceEvent>(_onFetchDeviceStatus);
    on<TwoGangSwitchControl>(_onControl);
    on<TwoGangSwitchFetchBatchEvent>(_onFetchBatchStatus);
    on<TwoGangSwitchBatchControl>(_onBatchControl);
    on<TwoGangFactoryReset>(_onFactoryReset);
    on<StatusUpdated>(_onStatusUpdated);
  }

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

  FutureOr<void> _onFetchDeviceStatus(TwoGangSwitchFetchDeviceEvent event,
      Emitter<TwoGangSwitchState> emit) async {
    emit(TwoGangSwitchLoading());
    try {
      final status =
          await DevicesManagementApi().getDeviceStatus(event.deviceId);
      deviceStatus = TwoGangStatusModel.fromJson(event.deviceId, status.status);
      _listenToChanges(event.deviceId);
      emit(TwoGangSwitchStatusLoaded(deviceStatus));
    } catch (e) {
      emit(TwoGangSwitchError(e.toString()));
    }
  }

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

    _updateLocalValue(event.code, event.value);

    emit(TwoGangSwitchStatusLoaded(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<TwoGangSwitchState> 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<TwoGangSwitchState> emit) {
    _updateLocalValue(code, oldValue);
    emit(TwoGangSwitchStatusLoaded(deviceStatus));
  }

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

    if (code == 'switch_2') {
      deviceStatus = deviceStatus.copyWith(switch2: value);
    }
  }

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

  Future<void> _onFetchBatchStatus(TwoGangSwitchFetchBatchEvent event,
      Emitter<TwoGangSwitchState> emit) async {
    emit(TwoGangSwitchLoading());
    try {
      final status =
          await DevicesManagementApi().getBatchStatus(event.devicesIds);
      deviceStatus =
          TwoGangStatusModel.fromJson(event.devicesIds.first, status.status);
      emit(TwoGangSwitchStatusLoaded(deviceStatus));
    } catch (e) {
      emit(TwoGangSwitchError(e.toString()));
    }
  }

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

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

    _updateLocalValue(event.code, event.value);

    emit(TwoGangSwitchStatusLoaded(deviceStatus));

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

  FutureOr<void> _onFactoryReset(
      TwoGangFactoryReset event, Emitter<TwoGangSwitchState> emit) async {
    emit(TwoGangSwitchLoading());
    try {
      final response = await DevicesManagementApi().factoryReset(
        event.factoryReset,
        event.deviceId,
      );
      if (!response) {
        emit(TwoGangSwitchError('Failed'));
      } else {
        emit(TwoGangSwitchStatusLoaded(deviceStatus));
      }
    } catch (e) {
      emit(TwoGangSwitchError(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 =
            TwoGangStatusModel.fromJson(usersMap['productUuid'], statusList);
        if (!isClosed) {
          add(StatusUpdated(deviceStatus));
        }
      });
    } catch (_) {}
  }

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