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/two_g_glass_switch/models/two_gang_glass_status_model.dart';
import 'package:syncrow_web/services/devices_mang_api.dart';
part 'two_gang_glass_switch_event.dart';
part 'two_gang_glass_switch_state.dart';

class TwoGangGlassSwitchBloc
    extends Bloc<TwoGangGlassSwitchEvent, TwoGangGlassSwitchState> {
  TwoGangGlassStatusModel deviceStatus;
  Timer? _timer;
  TwoGangGlassSwitchBloc({required String deviceId})
      : deviceStatus = TwoGangGlassStatusModel(
            uuid: deviceId,
            switch1: false,
            countDown1: 0,
            switch2: false,
            countDown2: 0),
        super(TwoGangGlassSwitchInitial()) {
    on<TwoGangGlassSwitchFetchDeviceEvent>(_onFetchDeviceStatus);
    on<TwoGangGlassSwitchControl>(_onControl);
    on<TwoGangGlassSwitchBatchControl>(_onBatchControl);
    on<TwoGangGlassSwitchFetchBatchStatusEvent>(_onFetchBatchStatus);
    on<TwoGangGlassFactoryReset>(_onFactoryReset);
    on<StatusUpdated>(_onStatusUpdated);
  }

  Future<void> _onFetchDeviceStatus(TwoGangGlassSwitchFetchDeviceEvent event,
      Emitter<TwoGangGlassSwitchState> emit) async {
    emit(TwoGangGlassSwitchLoading());
    try {
      final status =
          await DevicesManagementApi().getDeviceStatus(event.deviceId);
      deviceStatus =
          TwoGangGlassStatusModel.fromJson(event.deviceId, status.status);
      _listenToChanges(event.deviceId);
      emit(TwoGangGlassSwitchStatusLoaded(deviceStatus));
    } catch (e) {
      emit(TwoGangGlassSwitchError(e.toString()));
    }
  }

  void _listenToChanges(String deviceId) {
    try {
      DatabaseReference ref =
          FirebaseDatabase.instance.ref('device-status/$deviceId');
      ref.onValue.listen((DatabaseEvent event) {
        if (event.snapshot.value == null) return;

        Map<dynamic, dynamic> data =
            event.snapshot.value as Map<dynamic, dynamic>;
        List<Status> statusList = [];

        data['status'].forEach((element) {
          statusList
              .add(Status(code: element['code'], value: element['value']));
        });

        // Parse the new status and add the event
        final updatedStatus =
            TwoGangGlassStatusModel.fromJson(data['productUuid'], statusList);
        if (!isClosed) {
          add(StatusUpdated(updatedStatus));
        }
      });
    } catch (e) {
      // Handle errors and emit an error state if necessary
      if (!isClosed) {
        // add(TwoGangGlassSwitchError('Error listening to updates: $e'));
      }
    }
  }

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

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

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

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

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

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

  Future<void> _onFetchBatchStatus(
      TwoGangGlassSwitchFetchBatchStatusEvent event,
      Emitter<TwoGangGlassSwitchState> emit) async {
    emit(TwoGangGlassSwitchLoading());
    try {
      final status =
          await DevicesManagementApi().getBatchStatus(event.deviceIds);
      deviceStatus = TwoGangGlassStatusModel.fromJson(
          event.deviceIds.first, status.status);
      emit(TwoGangGlassSwitchBatchStatusLoaded(deviceStatus));
    } catch (e) {
      emit(TwoGangGlassSwitchError(e.toString()));
    }
  }

  Future<void> _onFactoryReset(TwoGangGlassFactoryReset event,
      Emitter<TwoGangGlassSwitchState> emit) async {
    emit(TwoGangGlassSwitchLoading());
    try {
      final response = await DevicesManagementApi()
          .factoryReset(event.factoryReset, event.deviceId);
      if (!response) {
        emit(TwoGangGlassSwitchError('Failed'));
      } else {
        emit(TwoGangGlassSwitchStatusLoaded(deviceStatus));
      }
    } catch (e) {
      emit(TwoGangGlassSwitchError(e.toString()));
    }
  }

  Future<void> _runDebounce({
    required dynamic deviceId,
    required String code,
    required bool value,
    required bool oldValue,
    required Emitter<TwoGangGlassSwitchState> 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<TwoGangGlassSwitchState> emit) {
    _updateLocalValue(code, oldValue);
    emit(TwoGangGlassSwitchStatusLoaded(deviceStatus));
  }

  void _updateLocalValue(String code, bool value) {
    if (code == 'switch_1') {
      deviceStatus = deviceStatus.copyWith(switch1: value);
    } else 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;
    }
  }

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

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

  void _onStatusUpdated(
      StatusUpdated event, Emitter<TwoGangGlassSwitchState> emit) {
    // Update the local deviceStatus with the new status from the event
    deviceStatus = event.deviceStatus;
    // Emit the new state with the updated status
    emit(TwoGangGlassSwitchStatusLoaded(deviceStatus));
  }
}
