import 'dart:async';

import 'package:equatable/equatable.dart';
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/three_g_glass_switch/models/three_gang_glass_switch.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 'three_gang_glass_switch_event.dart';
part 'three_gang_glass_switch_state.dart';

class ThreeGangGlassSwitchBloc
    extends Bloc<ThreeGangGlassSwitchEvent, ThreeGangGlassSwitchState> {
  late ThreeGangGlassStatusModel deviceStatus;
  final String deviceId;
  final ControlDeviceService controlDeviceService;
  final BatchControlDevicesService batchControlDevicesService;

  ThreeGangGlassSwitchBloc({
    required this.deviceId,
    required this.controlDeviceService,
    required this.batchControlDevicesService,
  }) : super(ThreeGangGlassSwitchInitial()) {
    on<ThreeGangGlassSwitchFetchDeviceEvent>(_onFetchDeviceStatus);
    on<ThreeGangGlassSwitchControl>(_onControl);
    on<ThreeGangGlassSwitchBatchControl>(_onBatchControl);
    on<ThreeGangGlassSwitchFetchBatchStatusEvent>(_onFetchBatchStatus);
    on<ThreeGangGlassFactoryReset>(_onFactoryReset);
    on<StatusUpdated>(_onStatusUpdated);
  }

  Future<void> _onFetchDeviceStatus(
    ThreeGangGlassSwitchFetchDeviceEvent event,
    Emitter<ThreeGangGlassSwitchState> emit,
  ) async {
    emit(ThreeGangGlassSwitchLoading());
    try {
      final status = await DevicesManagementApi().getDeviceStatus(event.deviceId);
      _listenToChanges(event.deviceId);
      deviceStatus =
          ThreeGangGlassStatusModel.fromJson(event.deviceId, status.status);
      emit(ThreeGangGlassSwitchStatusLoaded(deviceStatus));
    } catch (e) {
      emit(ThreeGangGlassSwitchError(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 =
            ThreeGangGlassStatusModel.fromJson(usersMap['productUuid'], statusList);

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

  void _onStatusUpdated(
    StatusUpdated event,
    Emitter<ThreeGangGlassSwitchState> emit,
  ) {
    emit(ThreeGangGlassSwitchLoading());
    deviceStatus = event.deviceStatus;
    emit(ThreeGangGlassSwitchStatusLoaded(deviceStatus));
  }

  Future<void> _onControl(
    ThreeGangGlassSwitchControl event,
    Emitter<ThreeGangGlassSwitchState> emit,
  ) async {
    emit(ThreeGangGlassSwitchLoading());
    _updateLocalValue(event.code, event.value);
    emit(ThreeGangGlassSwitchStatusLoaded(deviceStatus));

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

  Future<void> _onBatchControl(
    ThreeGangGlassSwitchBatchControl event,
    Emitter<ThreeGangGlassSwitchState> emit,
  ) async {
    emit(ThreeGangGlassSwitchLoading());
    _updateLocalValue(event.code, event.value);
    emit(ThreeGangGlassSwitchBatchStatusLoaded(deviceStatus));

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

  Future<void> _onFetchBatchStatus(
    ThreeGangGlassSwitchFetchBatchStatusEvent event,
    Emitter<ThreeGangGlassSwitchState> emit,
  ) async {
    emit(ThreeGangGlassSwitchLoading());
    try {
      final status = await DevicesManagementApi().getBatchStatus(event.deviceIds);
      deviceStatus =
          ThreeGangGlassStatusModel.fromJson(event.deviceIds.first, status.status);
      emit(ThreeGangGlassSwitchBatchStatusLoaded(deviceStatus));
    } catch (e) {
      emit(ThreeGangGlassSwitchError(e.toString()));
    }
  }

  Future<void> _onFactoryReset(
    ThreeGangGlassFactoryReset event,
    Emitter<ThreeGangGlassSwitchState> emit,
  ) async {
    emit(ThreeGangGlassSwitchLoading());
    try {
      final response = await DevicesManagementApi().factoryReset(
        event.factoryReset,
        event.deviceId,
      );
      if (!response) {
        emit(ThreeGangGlassSwitchError('Failed to reset device'));
      } else {
        add(ThreeGangGlassSwitchFetchDeviceEvent(event.deviceId));
      }
    } catch (e) {
      emit(ThreeGangGlassSwitchError(e.toString()));
    }
  }

  void _updateLocalValue(String code, bool value) {
    switch (code) {
      case 'switch_1':
        deviceStatus = deviceStatus.copyWith(switch1: value);
        break;
      case 'switch_2':
        deviceStatus = deviceStatus.copyWith(switch2: value);
        break;
      case 'switch_3':
        deviceStatus = deviceStatus.copyWith(switch3: value);
        break;
    }
  }

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