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/door_lock/bloc/door_lock_event.dart';
import 'package:syncrow_web/pages/device_managment/door_lock/bloc/door_lock_state.dart';
import 'package:syncrow_web/pages/device_managment/door_lock/models/door_lock_status_model.dart';
import 'package:syncrow_web/services/devices_mang_api.dart';

class DoorLockBloc extends Bloc<DoorLockEvent, DoorLockState> {
  late DoorLockStatusModel deviceStatus;
  final String deviceId;
  Timer? _timer;

  DoorLockBloc({required this.deviceId}) : super(DoorLockInitial()) {
    on<DoorLockFetchStatus>(_onFetchDeviceStatus);
    on<UpdateLockEvent>(_updateLock);
    on<DoorLockFactoryReset>(_onFactoryReset);
    on<StatusUpdated>(_onStatusUpdated);
  }

  void _listenToChanges(String deviceId) {
    try {
      final ref = FirebaseDatabase.instance.ref('device-status/$deviceId');
      ref.onValue.listen((event) {
        final data = event.snapshot.value;
        if (data is Map) {
          final statusData = data['status'] as List<dynamic>? ?? [];
          final statusList = statusData.map((item) {
            return Status(code: item['code'], value: item['value']);
          }).toList();

          final model =
              DoorLockStatusModel.fromJson(data['productUuid'], statusList);
          if (!isClosed) {
            add(StatusUpdated(model));
          }
        }
      });
    } catch (_) {}
  }

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

  Future<void> _onFetchDeviceStatus(
      DoorLockFetchStatus event, Emitter<DoorLockState> emit) async {
    emit(DoorLockStatusLoading());
    try {
      final status =
          await DevicesManagementApi().getDeviceStatus(event.deviceId);
      deviceStatus =
          DoorLockStatusModel.fromJson(event.deviceId, status.status);
      _listenToChanges(event.deviceId);
      emit(DoorLockStatusLoaded(deviceStatus));
    } catch (e) {
      emit(DoorLockControlError(e.toString()));
    }
  }

  Future<void> _updateLock(
      UpdateLockEvent event, Emitter<DoorLockState> emit) async {
    final oldValue = deviceStatus.normalOpenSwitch;
    deviceStatus = deviceStatus.copyWith(normalOpenSwitch: !oldValue);
    emit(DoorLockStatusLoaded(deviceStatus));

    try {
      final response = await DevicesManagementApi.openDoorLock(deviceId);
      if (!response) {
        _revertValueAndEmit(deviceId, 'normal_open_switch', oldValue, emit);
      }
    } catch (e) {
      _revertValueAndEmit(deviceId, 'normal_open_switch', oldValue, emit);
      emit(DoorLockControlError('Error controlling the lock: $e'));
    }
  }

  void _revertValueAndEmit(String deviceId, String code, dynamic oldValue,
      Emitter<DoorLockState> emit) {
    _updateLocalValue(code, oldValue);
    emit(DoorLockStatusLoaded(deviceStatus));
    emit(const DoorLockControlError('Failed to control the device.'));
  }

  void _updateLocalValue(String code, dynamic value) {
    switch (code) {
      case 'normal_open_switch':
        if (value is bool) {
          deviceStatus = deviceStatus.copyWith(normalOpenSwitch: value);
        }
        break;
      case 'reverse_lock':
        if (value is bool) {
          deviceStatus = deviceStatus.copyWith(reverseLock: value);
        }
        break;
      default:
        break;
    }
    emit(DoorLockStatusLoaded(deviceStatus));
  }

  Future<void> _onFactoryReset(
      DoorLockFactoryReset event, Emitter<DoorLockState> emit) async {
    emit(DoorLockStatusLoading());
    try {
      final response = await DevicesManagementApi().factoryReset(
        event.factoryReset,
        event.deviceId,
      );
      if (!response) {
        emit(const DoorLockControlError('Failed'));
      } else {
        add(DoorLockFetchStatus(event.deviceId));
      }
    } catch (e) {
      emit(DoorLockControlError(e.toString()));
    }
  }
}
