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/ceiling_sensor/bloc/ceiling_event.dart';
import 'package:syncrow_web/pages/device_managment/ceiling_sensor/bloc/ceiling_state.dart';
import 'package:syncrow_web/pages/device_managment/ceiling_sensor/model/ceiling_sensor_model.dart';
import 'package:syncrow_web/pages/device_managment/ceiling_sensor/model/help_description.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';

class CeilingSensorBloc extends Bloc<CeilingSensorEvent, CeilingSensorState> {
  final String deviceId;
  final ControlDeviceService controlDeviceService;
  final BatchControlDevicesService batchControlDevicesService;
  late CeilingSensorModel deviceStatus;

  CeilingSensorBloc({
    required this.deviceId,
    required this.controlDeviceService,
    required this.batchControlDevicesService,
  }) : super(CeilingInitialState()) {
    on<CeilingInitialEvent>(_fetchCeilingSensorStatus);
    on<CeilingFetchDeviceStatusEvent>(_fetchCeilingSensorBatchControl);
    on<CeilingChangeValueEvent>(_changeValue);
    on<CeilingBatchControlEvent>(_onBatchControl);
    on<GetCeilingDeviceReportsEvent>(_getDeviceReports);
    on<ShowCeilingDescriptionEvent>(_showDescription);
    on<BackToCeilingGridViewEvent>(_backToGridView);
    on<CeilingFactoryResetEvent>(_onFactoryReset);
    on<StatusUpdated>(_onStatusUpdated);
  }

  Future<void> _fetchCeilingSensorStatus(
    CeilingInitialEvent event,
    Emitter<CeilingSensorState> emit,
  ) async {
    emit(CeilingLoadingInitialState());
    try {
      final response = await DevicesManagementApi().getDeviceStatus(event.deviceId);
      deviceStatus = CeilingSensorModel.fromJson(response.status);
      emit(CeilingUpdateState(ceilingSensorModel: deviceStatus));
      _listenToChanges(event.deviceId);
    } catch (e) {
      emit(CeilingFailedState(error: e.toString()));
    }
  }

  void _listenToChanges(String deviceId) {
    try {
      final ref = FirebaseDatabase.instance.ref('device-status/$deviceId');
      final stream = ref.onValue;

      stream.listen((DatabaseEvent event) {
        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 = CeilingSensorModel.fromJson(statusList);
        if (!isClosed) {
          add(StatusUpdated(deviceStatus));
        }
      });
    } catch (_) {}
  }

  void _onStatusUpdated(
    StatusUpdated event,
    Emitter<CeilingSensorState> emit,
  ) {
    deviceStatus = event.deviceStatus;
    emit(CeilingUpdateState(ceilingSensorModel: deviceStatus));
  }

  Future<void> _changeValue(
    CeilingChangeValueEvent event,
    Emitter<CeilingSensorState> emit,
  ) async {
    emit(CeilingLoadingNewSate(ceilingSensorModel: deviceStatus));
    _updateDeviceFunctionFromCode(event.code, event.value);
    emit(CeilingUpdateState(ceilingSensorModel: deviceStatus));

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

  Future<void> _onBatchControl(
    CeilingBatchControlEvent event,
    Emitter<CeilingSensorState> emit,
  ) async {
    emit(CeilingLoadingNewSate(ceilingSensorModel: deviceStatus));
    _updateDeviceFunctionFromCode(event.code, event.value);
    emit(CeilingUpdateState(ceilingSensorModel: deviceStatus));

    try {
      final success = await batchControlDevicesService.batchControlDevices(
        uuids: event.deviceIds,
        code: event.code,
        value: event.value,
      );

      if (!success) {
        emit(const CeilingFailedState(error: 'Failed to control devices'));
      }
    } catch (e) {
      emit(CeilingFailedState(error: e.toString()));
    }
  }

  void _updateDeviceFunctionFromCode(String code, dynamic value) {
    switch (code) {
      case 'sensitivity':
        deviceStatus.sensitivity = value;
        break;
      case 'none_body_time':
        deviceStatus.noBodyTime = value;
        break;
      case 'moving_max_dis':
        deviceStatus.maxDistance = value;
        break;
      case 'scene':
        deviceStatus.spaceType = getSpaceType(value);
        break;
      default:
        break;
    }
  }

  Future<void> _getDeviceReports(
    GetCeilingDeviceReportsEvent event,
    Emitter<CeilingSensorState> emit,
  ) async {
    if (event.code.isEmpty) {
      emit(ShowCeilingDescriptionState(description: reportString));
      return;
    }

    emit(CeilingReportsLoadingState());
    try {
      final value = await DevicesManagementApi.getDeviceReports(
        deviceId,
        event.code,
      );
      emit(CeilingReportsState(deviceReport: value));
    } catch (e) {
      emit(CeilingReportsFailedState(error: e.toString()));
    }
  }

  void _showDescription(
    ShowCeilingDescriptionEvent event,
    Emitter<CeilingSensorState> emit,
  ) {
    emit(ShowCeilingDescriptionState(description: event.description));
  }

  void _backToGridView(
    BackToCeilingGridViewEvent event,
    Emitter<CeilingSensorState> emit,
  ) {
    emit(CeilingUpdateState(ceilingSensorModel: deviceStatus));
  }

  Future<void> _fetchCeilingSensorBatchControl(
    CeilingFetchDeviceStatusEvent event,
    Emitter<CeilingSensorState> emit,
  ) async {
    emit(CeilingLoadingInitialState());
    try {
      final response = await DevicesManagementApi().getBatchStatus(event.devicesIds);
      deviceStatus = CeilingSensorModel.fromJson(response.status);
      emit(CeilingUpdateState(ceilingSensorModel: deviceStatus));
    } catch (e) {
      emit(CeilingFailedState(error: e.toString()));
    }
  }

  Future<void> _onFactoryReset(
    CeilingFactoryResetEvent event,
    Emitter<CeilingSensorState> emit,
  ) async {
    emit(CeilingLoadingNewSate(ceilingSensorModel: deviceStatus));
    try {
      final response = await DevicesManagementApi().factoryReset(
        event.factoryResetModel,
        event.devicesId,
      );
      if (!response) {
        emit(const CeilingFailedState(error: 'Failed'));
      } else {
        emit(CeilingUpdateState(ceilingSensorModel: deviceStatus));
      }
    } catch (e) {
      emit(CeilingFailedState(error: e.toString()));
    }
  }
}
