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/batch_control_devices_service.dart';
import 'package:syncrow_web/services/control_device_service.dart';
import 'package:syncrow_web/services/devices_mang_api.dart';

class WallLightSwitchBloc extends Bloc<WallLightSwitchEvent, WallLightSwitchState> {
  late WallLightStatusModel deviceStatus;
  final String deviceId;
  final ControlDeviceService controlDeviceService;
  final BatchControlDevicesService batchControlDevicesService;

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

  Future<void> _onFetchDeviceStatus(
    WallLightSwitchFetchDeviceEvent event,
    Emitter<WallLightSwitchState> emit,
  ) async {
    emit(WallLightSwitchLoading());
    try {
      final status = await DevicesManagementApi().getDeviceStatus(event.deviceId);
      _listenToChanges(event.deviceId, emit);
      deviceStatus = WallLightStatusModel.fromJson(event.deviceId, status.status);
      emit(WallLightSwitchStatusLoaded(deviceStatus));
    } catch (e) {
      emit(WallLightSwitchError(e.toString()));
    }
  }

  void _listenToChanges(
    String deviceId,
    Emitter<WallLightSwitchState> emit,
  ) {
    try {
      final ref = FirebaseDatabase.instance.ref('device-status/$deviceId');
      final stream = ref.onValue;

      stream.listen((DatabaseEvent event) {
        final data = event.snapshot.value as Map<dynamic, dynamic>?;
        if (data == null) return;

        final statusList = <Status>[];
        if (data['status'] != null) {
          for (var element in data['status']) {
            statusList.add(
              Status(
                code: element['code'].toString(),
                value: element['value'].toString(),
              ),
            );
          }
        }
        if (statusList.isNotEmpty) {
          final newStatus = WallLightStatusModel.fromJson(deviceId, statusList);
          if (newStatus != deviceStatus) {
            deviceStatus = newStatus;
            if (!isClosed) {
              add(StatusUpdated(deviceStatus));
            }
          }
        }
      });
    } catch (e) {
      emit(WallLightSwitchError('Failed to listen to changes: $e'));
    }
  }

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

  Future<void> _onControl(
    WallLightSwitchControl event,
    Emitter<WallLightSwitchState> emit,
  ) async {
    emit(WallLightSwitchLoading());
    _updateLocalValue(event.code, event.value);
    emit(WallLightSwitchStatusLoaded(deviceStatus));

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

  Future<void> _onBatchControl(
    WallLightSwitchBatchControl event,
    Emitter<WallLightSwitchState> emit,
  ) async {
    emit(WallLightSwitchLoading());
    _updateLocalValue(event.code, event.value);
    emit(WallLightSwitchStatusLoaded(deviceStatus));

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

  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()));
    }
  }

  Future<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 to reset device'));
      } else {
        add(WallLightSwitchFetchDeviceEvent(event.deviceId));
      }
    } catch (e) {
      emit(WallLightSwitchError(e.toString()));
    }
  }

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