import 'package:bloc/bloc.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:syncrow_web/pages/device_managment/all_devices/models/device_reports.dart';
import 'package:syncrow_web/pages/device_managment/all_devices/models/device_status.dart';
import 'package:syncrow_web/pages/device_managment/water_leak/bloc/water_leak_event.dart';
import 'package:syncrow_web/pages/device_managment/water_leak/bloc/water_leak_state.dart';
import 'package:syncrow_web/pages/device_managment/water_leak/model/water_leak_status_model.dart';

import 'dart:async';

import 'package:syncrow_web/services/devices_mang_api.dart';

class WaterLeakBloc extends Bloc<WaterLeakEvent, WaterLeakState> {
  WaterLeakStatusModel? deviceStatus;
  Timer? _timer;
  final String deviceId;

  WaterLeakBloc(this.deviceId) : super(WaterLeakInitialState()) {
    on<FetchWaterLeakStatusEvent>(_onFetchWaterLeakStatus);
    on<WaterLeakControlEvent>(_onControl);
    on<WaterLeakBatchControlEvent>(_onBatchControl);
    on<FetchWaterLeakBatchStatusEvent>(_onFetchBatchStatus);
    on<FetchWaterLeakReportsEvent>(_onFetchWaterLeakReports);
    on<WaterLeakFactoryResetEvent>(_onFactoryReset);
    on<StatusUpdated>(_onStatusUpdated);
  }

  Future<void> _onFetchWaterLeakStatus(
      FetchWaterLeakStatusEvent event, Emitter<WaterLeakState> emit) async {
    emit(WaterLeakLoadingState());
    try {
      final response =
          await DevicesManagementApi().getDeviceStatus(event.deviceId);
      deviceStatus = WaterLeakStatusModel.fromJson(deviceId, response.status);
      _listenToChanges();
      emit(WaterLeakLoadedState(deviceStatus!));
    } catch (e) {
      emit(WaterLeakErrorState(e.toString()));
    }
  }

  _listenToChanges() {
    try {
      DatabaseReference ref =
          FirebaseDatabase.instance.ref('device-status/$deviceId');
      Stream<DatabaseEvent> stream = ref.onValue;

      stream.listen((DatabaseEvent event) {
        Map<dynamic, dynamic> usersMap =
            event.snapshot.value as Map<dynamic, dynamic>;

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

        deviceStatus =
            WaterLeakStatusModel.fromJson(usersMap['productUuid'], statusList);
        if (!isClosed) {
          add(StatusUpdated(deviceStatus!));
        }
      });
    } catch (_) {}
  }

  void _onStatusUpdated(StatusUpdated event, Emitter<WaterLeakState> emit) {
    deviceStatus = event.deviceStatus;
    emit(WaterLeakLoadedState(deviceStatus!));
  }

  Future<void> _onControl(
      WaterLeakControlEvent event, Emitter<WaterLeakState> emit) async {
    final oldValue = deviceStatus!.watersensorState;

    _updateLocalValue(event.code, event.value);
    emit(WaterLeakLoadedState(deviceStatus!));

    await _runDebounce(
      deviceId: event.deviceId,
      code: event.code,
      value: event.value,
      oldValue: oldValue,
      emit: emit,
      isBatch: false,
    );
  }

  Future<void> _onFactoryReset(
      WaterLeakFactoryResetEvent event, Emitter<WaterLeakState> emit) async {
    emit(WaterLeakLoadingState());
    try {
      final response = await DevicesManagementApi().factoryReset(
        event.factoryReset,
        event.deviceId,
      );
      if (response) {
        emit(WaterLeakInitialState());
      } else {
        emit(const WaterLeakErrorState('Factory reset failed'));
      }
    } catch (e) {
      emit(WaterLeakErrorState(e.toString()));
    }
  }

  Future<void> _onBatchControl(
      WaterLeakBatchControlEvent event, Emitter<WaterLeakState> emit) async {
    final oldValue = deviceStatus!.watersensorState;

    _updateLocalValue(event.code, event.value);
    emit(WaterLeakBatchStatusLoadedState(deviceStatus!));

    await _runDebounce(
      deviceId: event.deviceIds,
      code: event.code,
      value: event.value,
      oldValue: oldValue,
      emit: emit,
      isBatch: true,
    );
  }

  Future<void> _onFetchBatchStatus(FetchWaterLeakBatchStatusEvent event,
      Emitter<WaterLeakState> emit) async {
    emit(WaterLeakLoadingState());
    try {
      final response =
          await DevicesManagementApi().getBatchStatus(event.deviceIds);
      deviceStatus = WaterLeakStatusModel.fromJson(deviceId, response.status);
      emit(WaterLeakBatchStatusLoadedState(deviceStatus!));
    } catch (e) {
      emit(WaterLeakErrorState(e.toString()));
    }
  }

  Future<void> _runDebounce({
    required dynamic deviceId,
    required String code,
    required dynamic value,
    required dynamic oldValue,
    required Emitter<WaterLeakState> emit,
    required bool isBatch,
  }) async {
    late String id;
    if (deviceId is List) {
      id = deviceId.first;
    } else {
      id = deviceId;
    }

    if (_timer != null) {
      _timer!.cancel();
    }

    _timer = Timer(const Duration(milliseconds: 500), () 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) {
          _revertValueAndEmit(id, code, oldValue, emit);
        }
      } catch (e) {
        _revertValueAndEmit(id, code, oldValue, emit);
      }
    });
  }

  void _updateLocalValue(String code, dynamic value) {
    if (code == 'watersensor_state') {
      deviceStatus = deviceStatus!.copyWith(watersensorState: value);
    } else if (code == 'battery_percentage') {
      deviceStatus = deviceStatus!.copyWith(batteryPercentage: value);
    }
  }

  void _revertValueAndEmit(String deviceId, String code, dynamic oldValue,
      Emitter<WaterLeakState> emit) {
    _updateLocalValue(code, oldValue);
    emit(WaterLeakLoadedState(deviceStatus!));
  }

  Future<void> _onFetchWaterLeakReports(
      FetchWaterLeakReportsEvent event, Emitter<WaterLeakState> emit) async {
    emit(WaterLeakReportsLoadingState());
    try {
      final from = DateTime.now()
          .subtract(const Duration(days: 30))
          .millisecondsSinceEpoch;
      final to = DateTime.now().millisecondsSinceEpoch;
      final DeviceReport records =
          await DevicesManagementApi.getDeviceReportsByDate(
              event.deviceId, event.code, from.toString(), to.toString());
      emit(WaterLeakReportsLoadedState(records));
    } catch (e) {
      emit(WaterLeakReportsFailedState(e.toString()));
    }
  }
}
