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

import 'package:equatable/equatable.dart';
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/all_devices/models/factory_reset_model.dart';
import 'package:syncrow_web/pages/device_managment/three_gang_switch/models/living_room_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 'living_room_event.dart';
part 'living_room_state.dart';

class LivingRoomBloc extends Bloc<LivingRoomEvent, LivingRoomState> {
  late LivingRoomStatusModel deviceStatus;
  final String deviceId;
  final ControlDeviceService controlDeviceService;
  final BatchControlDevicesService batchControlDevicesService;

  LivingRoomBloc({
    required this.deviceId,
    required this.controlDeviceService,
    required this.batchControlDevicesService,
  }) : super(LivingRoomInitial()) {
    on<LivingRoomFetchDeviceStatusEvent>(_onFetchDeviceStatus);
    on<LivingRoomControl>(_livingRoomControl);
    on<LivingRoomBatchControl>(_livingRoomBatchControl);
    on<LivingRoomFetchBatchEvent>(_livingRoomFetchBatchControl);
    on<LivingRoomFactoryResetEvent>(_livingRoomFactoryReset);
    on<StatusUpdated>(_onStatusUpdated);
  }

  Future<void> _onFetchDeviceStatus(
    LivingRoomFetchDeviceStatusEvent event,
    Emitter<LivingRoomState> emit,
  ) async {
    emit(LivingRoomDeviceStatusLoading());
    try {
      final status = await DevicesManagementApi().getDeviceStatus(event.deviceId);
      _listenToChanges(deviceId);
      deviceStatus = LivingRoomStatusModel.fromJson(event.deviceId, status.status);
      emit(LivingRoomDeviceStatusLoaded(deviceStatus));
    } catch (e) {
      emit(LivingRoomDeviceManagementError(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 = LivingRoomStatusModel.fromJson(deviceId, statusList);
        add(StatusUpdated(deviceStatus));
      });
    } catch (_) {
      log('Error listening to changes');
    }
  }

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

  Future<void> _livingRoomControl(
    LivingRoomControl event,
    Emitter<LivingRoomState> emit,
  ) async {
    emit(LivingRoomDeviceStatusLoading());
    _updateLocalValue(event.code, event.value);
    emit(LivingRoomDeviceStatusLoaded(deviceStatus));

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

  Future<void> _livingRoomBatchControl(
    LivingRoomBatchControl event,
    Emitter<LivingRoomState> emit,
  ) async {
    emit(LivingRoomDeviceStatusLoading());
    _updateLocalValue(event.code, event.value);
    emit(LivingRoomDeviceStatusLoaded(deviceStatus));

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

  Future<void> _livingRoomFetchBatchControl(
    LivingRoomFetchBatchEvent event,
    Emitter<LivingRoomState> emit,
  ) async {
    emit(LivingRoomDeviceStatusLoading());
    try {
      final status = await DevicesManagementApi().getBatchStatus(event.devicesIds);
      deviceStatus =
          LivingRoomStatusModel.fromJson(event.devicesIds.first, status.status);
      emit(LivingRoomDeviceStatusLoaded(deviceStatus));
    } catch (e) {
      emit(LivingRoomDeviceManagementError(e.toString()));
    }
  }

  Future<void> _livingRoomFactoryReset(
    LivingRoomFactoryResetEvent event,
    Emitter<LivingRoomState> emit,
  ) async {
    emit(LivingRoomDeviceStatusLoading());
    try {
      final response = await DevicesManagementApi().factoryReset(
        event.factoryReset,
        event.uuid,
      );
      if (!response) {
        emit(const LivingRoomDeviceManagementError('Failed to reset device'));
      } else {
        add(LivingRoomFetchDeviceStatusEvent(event.uuid));
      }
    } catch (e) {
      emit(LivingRoomDeviceManagementError(e.toString()));
    }
  }

  void _updateLocalValue(String code, dynamic value) {
    if (value is! bool) return;

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