import 'dart:async';

import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_app/features/devices/model/device_control_model.dart';
import 'package:syncrow_app/features/scene/bloc/create_scene/create_scene_bloc.dart';
import 'package:syncrow_app/features/scene/enum/create_scene_enum.dart';
import 'package:syncrow_app/features/scene/enum/operation_dialog_type.dart';
import 'package:syncrow_app/features/scene/model/smart_scene_enable.dart';
import 'package:syncrow_app/generated/assets.dart';
import 'package:syncrow_app/navigation/navigation_service.dart';
part 'smart_scene_select_dart_event.dart';
part 'smart_scene_select_dart_state.dart';

class SmartSceneSelectBloc
    extends Bloc<SmartSceneSelectEvent, SmartSceneSelectState> {
  SmartSceneSelectBloc() : super(SmartSceneSelectInitial()) {
    on<SmartSceneEnableEvent>(_onSmartSceneEnable);
    on<SmartSceneClearEvent>(_smartSceneClear);
    on<SmartSceneConfirmSelectionEvent>(_smartSceneConfirmSelection);
  }

  SmartSceneEnable? smartSceneEnable;

  FutureOr<void> _onSmartSceneEnable(
      SmartSceneEnableEvent event, Emitter<SmartSceneSelectState> emit) {
    smartSceneEnable = event.smartSceneEnable;
  }

  FutureOr<void> _smartSceneClear(
      SmartSceneClearEvent event, Emitter<SmartSceneSelectState> emit) {
    smartSceneEnable = null;
    emit(SmartSceneSelectInitial());
  }

  FutureOr<void> _smartSceneConfirmSelection(
      SmartSceneConfirmSelectionEvent event,
      Emitter<SmartSceneSelectState> emit) {
    final createSceneBloc = NavigationService.navigatorKey.currentState!.context
        .read<CreateSceneBloc>();

    createSceneBloc.add(TempHoldSceneTasksEvent(
      deviceType:smartSceneEnable!.type ,
      deviceControlModel: DeviceControlModel(
        deviceId: smartSceneEnable?.entityId ?? '',
        code: CreateSceneEnum.smartSceneSelect.name,
        value: smartSceneEnable?.actionExecutor ?? '',
      ),
      deviceId: smartSceneEnable?.entityId ?? '',
      operation: smartSceneEnable?.type ?? '',
      icon: smartSceneEnable?.isAutomation == true
          ? Assets.player
          : Assets.handClickIcon,
      deviceName: smartSceneEnable?.sceneORAutomationName ?? '',
      uniqueId: smartSceneEnable?.entityId ?? '',
      operationType: OperationDialogType.none,
      isAutomation: false,
    ));

    emit(SmartSceneSelected(smartSceneEnable: smartSceneEnable!));
    NavigationService.navigatorKey.currentState!.context
        .read<CreateSceneBloc>()
        .add(const AddTaskEvent(isAutomation: false));
  }
}
