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/wall_sensor/bloc/wall_event.dart';
import 'package:syncrow_web/pages/device_managment/wall_sensor/bloc/wall_state.dart';
import 'package:syncrow_web/pages/device_managment/wall_sensor/model/wall_sensor_model.dart';
import 'package:syncrow_web/services/devices_mang_api.dart';

class WallSensorBloc extends Bloc<WallSensorEvent, WallSensorState> {
  final String deviceId;
  late WallSensorModel deviceStatus;
  Timer? _timer;

  WallSensorBloc({required this.deviceId}) : super(WallSensorInitialState()) {
    on<WallSensorFetchStatusEvent>(_fetchWallSensorStatus);
    on<WallSensorFetchBatchStatusEvent>(_fetchWallSensorBatchControl);
    on<WallSensorChangeValueEvent>(_changeValue);
    on<WallSensorBatchControlEvent>(_onBatchControl);
    on<GetDeviceReportsEvent>(_getDeviceReports);
    on<ShowDescriptionEvent>(_showDescription);
    on<BackToGridViewEvent>(_backToGridView);
    on<WallSensorFactoryResetEvent>(_onFactoryReset);
    on<WallSensorRealtimeUpdateEvent>(_onRealtimeUpdate);
  }

  void _fetchWallSensorStatus(
      WallSensorFetchStatusEvent event, Emitter<WallSensorState> emit) async {
    emit(WallSensorLoadingInitialState());
    try {
      var response = await DevicesManagementApi().getDeviceStatus(deviceId);
      deviceStatus = WallSensorModel.fromJson(response.status);
      emit(WallSensorUpdateState(wallSensorModel: deviceStatus));
      _listenToChanges(deviceId);
    } catch (e) {
      emit(WallSensorFailedState(error: e.toString()));
      return;
    }
  }

  // Fetch batch status
  FutureOr<void> _fetchWallSensorBatchControl(
      WallSensorFetchBatchStatusEvent event,
      Emitter<WallSensorState> emit) async {
    emit(WallSensorLoadingInitialState());
    try {
      var response =
          await DevicesManagementApi().getBatchStatus(event.devicesIds);
      deviceStatus = WallSensorModel.fromJson(response.status);
      emit(WallSensorUpdateState(wallSensorModel: deviceStatus));
    } catch (e) {
      emit(WallSensorFailedState(error: e.toString()));
    }
  }

  void _listenToChanges(String deviceId) {
    DatabaseReference ref =
        FirebaseDatabase.instance.ref('device-status/$deviceId');
    ref.onValue.listen((DatabaseEvent event) {
      final data = event.snapshot.value as Map<dynamic, dynamic>?;
      if (data == null) return;

      final statusList = (data['status'] as List?)
          ?.map((e) => Status(code: e['code'], value: e['value']))
          .toList();

      if (statusList != null) {
        final updatedDeviceStatus = WallSensorModel.fromJson(statusList);
        if (!isClosed) {
          add(WallSensorRealtimeUpdateEvent(updatedDeviceStatus));
        }
      }
    });
  }


  void _changeValue(
      WallSensorChangeValueEvent event, Emitter<WallSensorState> emit) async {
    emit(WallSensorLoadingNewSate(wallSensorModel: deviceStatus));
    if (event.code == 'far_detection') {
      deviceStatus.farDetection = event.value;
    } else if (event.code == 'motionless_sensitivity') {
      deviceStatus.motionlessSensitivity = event.value;
    } else if (event.code == 'motion_sensitivity_value') {
      deviceStatus.motionSensitivity = event.value;
    } else if (event.code == 'no_one_time') {
      deviceStatus.noBodyTime = event.value;
    }
    emit(WallSensorUpdateState(wallSensorModel: deviceStatus));
    await _runDeBouncer(
      deviceId: deviceId,
      code: event.code,
      value: event.value,
      isBatch: false,
      emit: emit,
    );
  }

  Future<void> _onBatchControl(
      WallSensorBatchControlEvent event, Emitter<WallSensorState> emit) async {
    emit(WallSensorLoadingNewSate(wallSensorModel: deviceStatus));
    if (event.code == 'far_detection') {
      deviceStatus.farDetection = event.value;
    } else if (event.code == 'motionless_sensitivity') {
      deviceStatus.motionlessSensitivity = event.value;
    } else if (event.code == 'motion_sensitivity_value') {
      deviceStatus.motionSensitivity = event.value;
    } else if (event.code == 'no_one_time') {
      deviceStatus.noBodyTime = event.value;
    }
    emit(WallSensorUpdateState(wallSensorModel: deviceStatus));
    await _runDeBouncer(
      deviceId: event.deviceIds,
      code: event.code,
      value: event.value,
      emit: emit,
      isBatch: true,
    );
  }

  _runDeBouncer({
    required dynamic deviceId,
    required String code,
    required dynamic value,
    required Emitter<WallSensorState> emit,
    required bool isBatch,
  }) {
    if (_timer != null) {
      _timer!.cancel();
    }
    _timer = Timer(const Duration(seconds: 1), () async {
      try {
        late bool response;
        if (isBatch) {
          response = await DevicesManagementApi()
              .deviceBatchControl(deviceId, code, value);
        } else {
          response = await DevicesManagementApi()
              .deviceControl(deviceId, Status(code: code, value: value));
        }

        if (!response) {
          add(WallSensorFetchStatusEvent());
        }
      } catch (_) {
        await Future.delayed(const Duration(milliseconds: 500));
        add(WallSensorFetchStatusEvent());
      }
    });
  }

  FutureOr<void> _getDeviceReports(
      GetDeviceReportsEvent event, Emitter<WallSensorState> emit) async {
    emit(DeviceReportsLoadingState());
    // final from = DateTime.now().subtract(const Duration(days: 30)).millisecondsSinceEpoch;
    // final to = DateTime.now().millisecondsSinceEpoch;

    try {
      // await DevicesManagementApi.getDeviceReportsByDate(
      //         deviceId, event.code, from.toString(), to.toString())
      await DevicesManagementApi.getDeviceReports(deviceId, event.code)
          .then((value) {
        emit(DeviceReportsState(deviceReport: value, code: event.code));
      });
    } catch (e) {
      emit(DeviceReportsFailedState(error: e.toString()));
      return;
    }
  }

  void _showDescription(
      ShowDescriptionEvent event, Emitter<WallSensorState> emit) {
    emit(WallSensorShowDescriptionState(description: event.description));
  }

  void _backToGridView(
      BackToGridViewEvent event, Emitter<WallSensorState> emit) {
    emit(WallSensorUpdateState(wallSensorModel: deviceStatus));
  }

  FutureOr<void> _onFactoryReset(
      WallSensorFactoryResetEvent event, Emitter<WallSensorState> emit) async {
    emit(WallSensorLoadingNewSate(wallSensorModel: deviceStatus));
    try {
      final response = await DevicesManagementApi().factoryReset(
        event.factoryReset,
        event.deviceId,
      );
      if (!response) {
        emit(const WallSensorFailedState(error: 'Failed'));
      } else {
        emit(WallSensorUpdateState(wallSensorModel: deviceStatus));
      }
    } catch (e) {
      emit(WallSensorFailedState(error: e.toString()));
    }
  }

  void _onRealtimeUpdate(
    WallSensorRealtimeUpdateEvent event,
    Emitter<WallSensorState> emit,
  ) {
    deviceStatus = event.deviceStatus;
    emit(WallSensorUpdateState(wallSensorModel: deviceStatus));
  }
}
