import 'dart:io';
import 'package:be_happy/domain/entities/scooter_order.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../domain/usecase/finish_ride_usecase.dart';
import '../../domain/usecase/upload_scooter_photos_usecase.dart';
import '../event/send_photo_event.dart';
import '../state/send_photo_state.dart';
import '../../core/result.dart';
import '../../core/failures.dart';

class SendPhotoBloc extends Bloc<SendPhotoEvent, SendPhotoState> {
  final UploadScooterPhotosUsecase uploadScooterPhotosUsecase;
  final FinishRideUsecase _finishRideUsecase;


  SendPhotoBloc(this.uploadScooterPhotosUsecase, this._finishRideUsecase) : super(const SendPhotoState()) {
    on<PhotoSelected>(_onPhotoSelected);
    on<PhotoUploadSubmitted>(_onPhotoUploadSubmitted);
  }

  void _onPhotoSelected(PhotoSelected event, Emitter<SendPhotoState> emit) {
    emit(state.copyWith(selectedImages: event.imagePaths));
  }

  Future<void> _onPhotoUploadSubmitted(
      PhotoUploadSubmitted event, Emitter<SendPhotoState> emit) async {
    if (state.selectedImages.isEmpty) {
      emit(state.copyWith(
        status: SendPhotoStatus.failure,
        errorMessage: 'Выберите хотя бы одно фото',
      ));
      return;
    }

    emit(state.copyWith(status: SendPhotoStatus.loading));

    final imageFiles = state.selectedImages.map((path) => File(path)).toList();

    final result = await uploadScooterPhotosUsecase(imageFiles);

    switch (result) {
      case Success<List<int>>():
      // ✅ Защита: если data null или пустой — не вызываем finish
        if (result.data == null || result.data!.isEmpty) {
          emit(state.copyWith(
            status: SendPhotoStatus.failure,
            errorMessage: 'Не удалось получить ID загруженных фото',
          ));
          return;
        }

        // ✅ Передаём два параметра в UseCase
        final finishResult = await _finishRideUsecase(
            event.orderId,
            result.data!  // ✅ ! т.к. проверили выше
        );

        switch (finishResult) {
          case Success<ScooterOrder>():
            emit(state.copyWith(
              status: SendPhotoStatus.success,
              recievedPhotoIds: result.data,
            ));
          case Failure():
            print("❌ FINISH ERROR: ${finishResult.failure.message}");
            emit(state.copyWith(
              status: SendPhotoStatus.failure,
              errorMessage: 'Ошибка завершения поездки',
            ));
        }
      case Failure():
        emit(state.copyWith(
          status: SendPhotoStatus.failure,
          errorMessage: 'Ошибка загрузки фото: ${result.failure.message}',
        ));
    }
  }
}
