import 'dart:async';
import 'package:dio/dio.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/material.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/main_door_sensor/bloc/main_door_sensor_event.dart';
import 'package:syncrow_web/pages/device_managment/main_door_sensor/bloc/main_door_sensor_state.dart';
import 'package:syncrow_web/pages/device_managment/main_door_sensor/models/main_door_status_model.dart';
import 'package:syncrow_web/services/devices_mang_api.dart';

class MainDoorSensorBloc
    extends Bloc<MainDoorSensorEvent, MainDoorSensorState> {
  MainDoorSensorBloc() : super(MainDoorSensorInitial()) {
    on<MainDoorSensorFetchDeviceEvent>(_onFetchDeviceStatus);
    on<MainDoorSensorControl>(_onControl);
    on<MainDoorSensorFetchBatchEvent>(_onFetchBatchStatus);
    on<MainDoorSensorReportsEvent>(_fetchReports);
    on<MainDoorSensorFactoryReset>(_factoryReset);
    on<StatusUpdated>(_onStatusUpdated);
  }

  late MainDoorSensorStatusModel deviceStatus;
  Timer? _timer;

  FutureOr<void> _onFetchDeviceStatus(MainDoorSensorFetchDeviceEvent event,
      Emitter<MainDoorSensorState> emit) async {
    emit(MainDoorSensorLoadingState());
    try {
      final status = await DevicesManagementApi()
          .getDeviceStatus(event.deviceId)
          .then((value) => value.status);
      _listenToChanges(event.deviceId);
      deviceStatus = MainDoorSensorStatusModel.fromJson(event.deviceId, status);
      emit(MainDoorSensorDeviceStatusLoaded(deviceStatus));
    } catch (e) {
      emit(MainDoorSensorFailedState(error: e.toString()));
    }
  }

  FutureOr<void> _onControl(
      MainDoorSensorControl event, Emitter<MainDoorSensorState> emit) async {
    final oldValue = _getValueByCode(event.code);

    _updateLocalValue(event.code, event.value);

    emit(MainDoorSensorDeviceStatusLoaded(deviceStatus));

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

  Future<void> _runDebounce({
    required String deviceId,
    required String code,
    required bool value,
    required bool oldValue,
    required Emitter<MainDoorSensorState> emit,
  }) async {
    if (_timer != null) {
      _timer!.cancel();
    }

    _timer = Timer(const Duration(milliseconds: 500), () async {
      try {
        final response = await DevicesManagementApi()
            .deviceControl(deviceId, Status(code: code, value: value));

        if (!response) {
          _revertValueAndEmit(deviceId, code, oldValue, emit);
        }
      } catch (e) {
        if (e is DioException && e.response != null) {
          debugPrint('Error response: ${e.response?.data}');
        }
        _revertValueAndEmit(deviceId, code, oldValue, emit);
      }
    });
  }

  void _revertValueAndEmit(String deviceId, String code, bool oldValue,
      Emitter<MainDoorSensorState> emit) {
    _updateLocalValue(code, oldValue);
    emit(MainDoorSensorDeviceStatusLoaded(deviceStatus));
  }

  void _updateLocalValue(String code, bool value) {
    switch (code) {
      case 'doorcontact_state':
        deviceStatus = deviceStatus.copyWith(doorContactState: value);
        break;
      default:
        break;
    }
  }

  bool _getValueByCode(String code) {
    switch (code) {
      case 'doorcontact_state':
        return deviceStatus.doorContactState;
      default:
        return false;
    }
  }

  // Fetch batch status for multiple devices (if needed)
  FutureOr<void> _onFetchBatchStatus(MainDoorSensorFetchBatchEvent event,
      Emitter<MainDoorSensorState> emit) async {
    emit(MainDoorSensorLoadingState());
    try {
      // final batchStatus =
      //     await DevicesManagementApi().getBatchDeviceStatus(event.deviceIds);
      // Assuming you need to update multiple devices status here
      // You might need a list or map of MainDoorSensorStatusModel for batch processing
      // emit(MainDoorSensorBatchStatusLoaded(batchStatus));
    } catch (e) {
      emit(MainDoorSensorBatchFailedState(error: e.toString()));
    }
  }

  FutureOr<void> _fetchReports(MainDoorSensorReportsEvent event,
      Emitter<MainDoorSensorState> emit) async {
    emit(MainDoorSensorLoadingState());
    try {
      final reports = await DevicesManagementApi.getDeviceReportsByDate(
          event.deviceId, event.code, event.from, event.to);
      emit(MainDoorSensorReportLoaded(reports));
    } catch (e) {
      emit(MainDoorSensorFailedState(error: e.toString()));
    }
  }

  @override
  Future<void> close() {
    _timer?.cancel();
    return super.close();
  }

  FutureOr<void> _factoryReset(MainDoorSensorFactoryReset event,
      Emitter<MainDoorSensorState> emit) async {
    emit(MainDoorSensorLoadingState());
    try {
      final response = await DevicesManagementApi().factoryReset(
        event.factoryReset,
        event.deviceId,
      );
      if (!response) {
        emit(MainDoorSensorFailedState(error: 'Failed'));
      } else {
        add(MainDoorSensorFetchDeviceEvent(event.deviceId));
      }
    } catch (e) {
      emit(MainDoorSensorFailedState(error: e.toString()));
    }
  }

  _listenToChanges(deviceId) {
    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 = MainDoorSensorStatusModel.fromJson(
            usersMap['productUuid'], statusList);
        if (!isClosed) {
          add(StatusUpdated(deviceStatus));
        }
      });
    } catch (_) {}
  }

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