import 'dart:async';
import 'dart:developer';

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/two_gang_switch/bloc/two_gang_switch_event.dart';
import 'package:syncrow_web/pages/device_managment/two_gang_switch/bloc/two_gang_switch_state.dart';
import 'package:syncrow_web/pages/device_managment/two_gang_switch/models/two_gang_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 TwoGangSwitchBloc extends Bloc<TwoGangSwitchEvent, TwoGangSwitchState> {
  final String deviceId;
  final ControlDeviceService controlDeviceService;
  final BatchControlDevicesService batchControlDevicesService;

  late TwoGangStatusModel deviceStatus;

  TwoGangSwitchBloc({
    required this.deviceId,
    required this.controlDeviceService,
    required this.batchControlDevicesService,
  }) : super(TwoGangSwitchInitial()) {
    on<TwoGangSwitchFetchDeviceEvent>(_onFetchDeviceStatus);
    on<TwoGangSwitchControl>(_onControl);
    on<TwoGangSwitchFetchBatchEvent>(_onFetchBatchStatus);
    on<TwoGangSwitchBatchControl>(_onBatchControl);
    on<TwoGangFactoryReset>(_onFactoryReset);
    on<StatusUpdated>(_onStatusUpdated);
  }

  Future<void> _onFetchDeviceStatus(
    TwoGangSwitchFetchDeviceEvent event,
    Emitter<TwoGangSwitchState> emit,
  ) async {
    emit(TwoGangSwitchLoading());
    try {
      final status = await DevicesManagementApi().getDeviceStatus(event.deviceId);
      deviceStatus = TwoGangStatusModel.fromJson(event.deviceId, status.status);
      _listenToChanges(event.deviceId);
      emit(TwoGangSwitchStatusLoaded(deviceStatus));
    } catch (e) {
      emit(TwoGangSwitchError(e.toString()));
    }
  }

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

      ref.onValue.listen((event) {
        final eventsMap = event.snapshot.value as Map<dynamic, dynamic>;

        List<Status> statusList = [];
        eventsMap['status'].forEach((element) {
          statusList.add(
            Status(code: element['code'], value: element['value']),
          );
        });

        deviceStatus = TwoGangStatusModel.fromJson(deviceId, statusList);
        add(StatusUpdated(deviceStatus));
      });
    } catch (_) {
      log(
        'Error listening to changes',
        name: 'TwoGangSwitchBloc._listenToChanges',
      );
    }
  }

  Future<void> _onControl(
    TwoGangSwitchControl event,
    Emitter<TwoGangSwitchState> emit,
  ) async {
    emit(TwoGangSwitchLoading());
    _updateLocalValue(event.code, event.value);
    emit(TwoGangSwitchStatusLoaded(deviceStatus));

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

  Future<void> _onBatchControl(
    TwoGangSwitchBatchControl event,
    Emitter<TwoGangSwitchState> emit,
  ) async {
    emit(TwoGangSwitchLoading());
    _updateLocalValue(event.code, event.value);
    emit(TwoGangSwitchStatusLoaded(deviceStatus));

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

  Future<void> _onFetchBatchStatus(
    TwoGangSwitchFetchBatchEvent event,
    Emitter<TwoGangSwitchState> emit,
  ) async {
    emit(TwoGangSwitchLoading());
    try {
      final status = await DevicesManagementApi().getBatchStatus(event.devicesIds);
      deviceStatus = TwoGangStatusModel.fromJson(
        event.devicesIds.first,
        status.status,
      );
      emit(TwoGangSwitchStatusLoaded(deviceStatus));
    } catch (e) {
      emit(TwoGangSwitchError(e.toString()));
    }
  }

  Future<void> _onFactoryReset(
    TwoGangFactoryReset event,
    Emitter<TwoGangSwitchState> emit,
  ) async {
    emit(TwoGangSwitchLoading());
    try {
      final response = await DevicesManagementApi().factoryReset(
        event.factoryReset,
        event.deviceId,
      );
      if (!response) {
        emit(TwoGangSwitchError('Failed to reset device'));
      } else {
        add(TwoGangSwitchFetchDeviceEvent(event.deviceId));
      }
    } catch (e) {
      emit(TwoGangSwitchError(e.toString()));
    }
  }

  void _onStatusUpdated(
    StatusUpdated event,
    Emitter<TwoGangSwitchState> emit,
  ) {
    deviceStatus = event.deviceStatus;
    emit(TwoGangSwitchStatusLoaded(deviceStatus));
  }

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