import 'dart:async';
import 'package:dio/dio.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_app/features/devices/bloc/water_leak_bloc/water_leak_event.dart';
import 'package:syncrow_app/features/devices/bloc/water_leak_bloc/water_leak_state.dart';
import 'package:syncrow_app/features/devices/model/device_control_model.dart';
import 'package:syncrow_app/features/devices/model/device_report_model.dart';
import 'package:syncrow_app/features/devices/model/status_model.dart';
import 'package:syncrow_app/features/devices/model/water_leak_model.dart';
import 'package:syncrow_app/services/api/devices_api.dart';

class WaterLeakBloc extends Bloc<WaterLeakEvent, WaterLeakState> {
  final String WLId;
  WaterLeakBloc({
    required this.WLId,
  }) : super(const WaterLeakState()) {
    on<WaterLeakInitial>(_fetchStatus);
    on<ReportLogsInitial>(fetchLogsForLastMonth);
    on<ToggleLowBatteryEvent>(_toggleLowBattery);
    on<ToggleClosingReminderEvent>(_toggleClosingReminder);
    on<ToggleWaterLeakAlarmEvent>(_toggleWaterLeakAlarm);
  }
  bool lowBattery = false;
  bool closingReminder = false;
  bool waterAlarm = false;
  WaterLeakModel deviceStatus =
      WaterLeakModel(waterContactState: 'normal', batteryPercentage: 0);

  void _fetchStatus(
      WaterLeakInitial event, Emitter<WaterLeakState> emit) async {
    emit(WaterLeakLoadingState());
    try {
      var response = await DevicesAPI.getDeviceStatus(WLId);
      List<StatusModel> statusModelList = [];
      for (var status in response['status']) {
        statusModelList.add(StatusModel.fromJson(status));
      }
      deviceStatus = WaterLeakModel.fromJson(
        statusModelList,
      );
      emit(UpdateState(waterSensor: deviceStatus));

      Future.delayed(const Duration(milliseconds: 500));
      // _listenToChanges();
    } catch (e) {
      emit(WaterLeakFailedState(errorMessage: e.toString()));
      return;
    }
  }

  void _toggleLowBattery(
      ToggleLowBatteryEvent event, Emitter<WaterLeakState> emit) async {
    emit(LoadingNewSate(waterSensor: deviceStatus));
    try {
      lowBattery = event.isLowBatteryEnabled;
      emit(UpdateState(waterSensor: deviceStatus));
      await DevicesAPI.controlDevice(
        DeviceControlModel(
          deviceId: WLId,
          code: 'low_battery',
          value: lowBattery,
        ),
        WLId,
      );
    } catch (e) {
      emit(WaterLeakFailedState(errorMessage: e.toString()));
    }
  }

  void _toggleClosingReminder(
      ToggleClosingReminderEvent event, Emitter<WaterLeakState> emit) async {
    emit(LoadingNewSate(waterSensor: deviceStatus));
    try {
      closingReminder = event.isClosingReminderEnabled;
      emit(UpdateState(waterSensor: deviceStatus));

      // API call to update the state, if necessary
      await DevicesAPI.controlDevice(
        DeviceControlModel(
          deviceId: WLId,
          code: 'closing_reminder',
          value: closingReminder,
        ),
        WLId,
      );
    } catch (e) {
      emit(WaterLeakFailedState(errorMessage: e.toString()));
    }
  }

  void _toggleWaterLeakAlarm(
      ToggleWaterLeakAlarmEvent event, Emitter<WaterLeakState> emit) async {
    emit(LoadingNewSate(waterSensor: deviceStatus));
    try {
      waterAlarm = event.isWaterLeakAlarmEnabled;
      emit(UpdateState(waterSensor: deviceStatus));
      await DevicesAPI.controlDevice(
        DeviceControlModel(
          deviceId: WLId,
          code: 'water_alarm',
          value: waterAlarm,
        ),
        WLId,
      );
    } catch (e) {
      emit(WaterLeakFailedState(errorMessage: e.toString()));
    }
  }

  DeviceReport recordGroups =
      DeviceReport(startTime: '0', endTime: '0', data: []);

  Future<void> fetchLogsForLastMonth(
      ReportLogsInitial event, Emitter<WaterLeakState> emit) async {
    DateTime now = DateTime.now();
    DateTime lastMonth = DateTime(now.year, now.month - 1, now.day);
    int startTime = lastMonth.millisecondsSinceEpoch;
    int endTime = now.millisecondsSinceEpoch;
    try {
      emit(WaterLeakLoadingState());
      var response = await DevicesAPI.getReportLogs(
        startTime: startTime.toString(),
        endTime: endTime.toString(),
        deviceUuid: WLId,
        code: 'watersensor_state',
      );
      recordGroups = response;
      emit(UpdateState(waterSensor: deviceStatus));
    } on DioException catch (e) {
      final errorData = e.response!.data;
      String errorMessage = errorData['message'];
      emit(WaterLeakFailedState(errorMessage: errorMessage));
    }
  }
  //  Timer? _timer;
  // StreamSubscription<DatabaseEvent>? _streamSubscription;
  // void _listenToChanges() {
  //   try {
  //     _streamSubscription?.cancel();
  //     DatabaseReference ref =
  //         FirebaseDatabase.instance.ref('device-status/$WLId');
  //     Stream<DatabaseEvent> stream = ref.onValue;

  //     _streamSubscription = stream.listen((DatabaseEvent event) async {
  //       if (_timer != null) {
  //         await Future.delayed(const Duration(seconds: 2));
  //       }
  //       Map<dynamic, dynamic> usersMap =
  //           event.snapshot.value as Map<dynamic, dynamic>;
  //       List<StatusModel> statusList = [];
  //       usersMap['status'].forEach((element) {
  //         statusList
  //             .add(StatusModel(code: element['code'], value: element['value']));
  //       });
  //       deviceStatus = WaterLeakModel.fromJson(statusList);
  //       if (!isClosed) {
  //         add(
  //           WaterLeakSwitch(switchD: deviceStatus.waterContactState),
  //         );
  //       }
  //     });
  //   } catch (_) {}
  // }

  // @override
  // Future<void> close() async {
  //   _streamSubscription?.cancel();
  //   _streamSubscription = null;
  //   return super.close();
  // }


}
