import 'dart:async';

import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/foundation.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/all_devices/models/factory_reset_model.dart';
import 'package:syncrow_web/pages/device_managment/one_g_glass_switch/models/once_gang_glass_status_model.dart';
import 'package:syncrow_web/services/batch_control_devices_service.dart';
import 'package:syncrow_web/services/control_device_service.dart';
import 'package:syncrow_web/services/devices_mang_api.dart';

part 'one_gang_glass_switch_event.dart';
part 'one_gang_glass_switch_state.dart';

class OneGangGlassSwitchBloc
    extends Bloc<OneGangGlassSwitchEvent, OneGangGlassSwitchState> {
  late OneGangGlassStatusModel deviceStatus;
  final String deviceId;
  final ControlDeviceService controlDeviceService;
  final BatchControlDevicesService batchControlDevicesService;

  OneGangGlassSwitchBloc({
    required this.deviceId,
    required this.controlDeviceService,
    required this.batchControlDevicesService,
  }) : super(OneGangGlassSwitchInitial()) {
    on<OneGangGlassSwitchFetchDeviceEvent>(_onFetchDeviceStatus);
    on<OneGangGlassSwitchControl>(_onControl);
    on<OneGangGlassSwitchBatchControl>(_onBatchControl);
    on<OneGangGlassSwitchFetchBatchStatusEvent>(_onFetchBatchStatus);
    on<OneGangGlassFactoryResetEvent>(_onFactoryReset);
    on<StatusUpdated>(_onStatusUpdated);
  }

  Future<void> _onFetchDeviceStatus(
    OneGangGlassSwitchFetchDeviceEvent event,
    Emitter<OneGangGlassSwitchState> emit,
  ) async {
    emit(OneGangGlassSwitchLoading());
    try {
      final status = await DevicesManagementApi().getDeviceStatus(event.deviceId);
      _listenToChanges(event.deviceId);
      deviceStatus = OneGangGlassStatusModel.fromJson(event.deviceId, status.status);
      emit(OneGangGlassSwitchStatusLoaded(deviceStatus));
    } catch (e) {
      emit(OneGangGlassSwitchError(e.toString()));
    }
  }

  StreamSubscription<DatabaseEvent>? _deviceStatusSubscription;

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

        final usersMap = event.snapshot.value! as Map<dynamic, dynamic>;

        final statusList = <Status>[];

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

        deviceStatus =
            OneGangGlassStatusModel.fromJson(usersMap['productUuid'], statusList);

        add(StatusUpdated(deviceStatus));
      });
    } catch (_) {}
  }

  void _onStatusUpdated(
    StatusUpdated event,
    Emitter<OneGangGlassSwitchState> emit,
  ) {
    emit(OneGangGlassSwitchLoading());
    deviceStatus = event.deviceStatus;
    emit(OneGangGlassSwitchStatusLoaded(deviceStatus));
  }

  Future<void> _onControl(
    OneGangGlassSwitchControl event,
    Emitter<OneGangGlassSwitchState> emit,
  ) async {
    emit(OneGangGlassSwitchLoading());
    _updateLocalValue(event.code, event.value);
    emit(OneGangGlassSwitchStatusLoaded(deviceStatus));

    try {
      await controlDeviceService.controlDevice(
        deviceUuid: event.deviceId,
        status: Status(code: event.code, value: event.value),
      );
    } catch (e) {
      _updateLocalValue(event.code, !event.value);
      emit(OneGangGlassSwitchError(e.toString()));
    }
  }

  Future<void> _onBatchControl(
    OneGangGlassSwitchBatchControl event,
    Emitter<OneGangGlassSwitchState> emit,
  ) async {
    emit(OneGangGlassSwitchLoading());
    _updateLocalValue(event.code, event.value);
    emit(OneGangGlassSwitchStatusLoaded(deviceStatus));

    try {
      await batchControlDevicesService.batchControlDevices(
        uuids: event.deviceIds,
        code: event.code,
        value: event.value,
      );
    } catch (e) {
      _updateLocalValue(event.code, !event.value);
      emit(OneGangGlassSwitchError(e.toString()));
    }
  }

  Future<void> _onFetchBatchStatus(
    OneGangGlassSwitchFetchBatchStatusEvent event,
    Emitter<OneGangGlassSwitchState> emit,
  ) async {
    emit(OneGangGlassSwitchLoading());
    try {
      final status = await DevicesManagementApi().getBatchStatus(event.deviceIds);
      deviceStatus =
          OneGangGlassStatusModel.fromJson(event.deviceIds.first, status.status);
      emit(OneGangGlassSwitchStatusLoaded(deviceStatus));
    } catch (e) {
      emit(OneGangGlassSwitchError(e.toString()));
    }
  }

  Future<void> _onFactoryReset(
    OneGangGlassFactoryResetEvent event,
    Emitter<OneGangGlassSwitchState> emit,
  ) async {
    emit(OneGangGlassSwitchLoading());
    try {
      final response = await DevicesManagementApi().factoryReset(
        event.factoryReset,
        event.deviceId,
      );
      if (!response) {
        emit(OneGangGlassSwitchError('Failed to reset device'));
      } else {
        add(OneGangGlassSwitchFetchDeviceEvent(event.deviceId));
      }
    } catch (e) {
      emit(OneGangGlassSwitchError(e.toString()));
    }
  }

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

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