import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:be_happy/domain/entities/scooter_order.dart';
import 'package:be_happy/domain/usecase/get_scooter_order_history_usecase.dart';
import 'package:be_happy/core/result.dart';

abstract class OrderHistoryEvent {}

class OrderHistoryFetchRequested extends OrderHistoryEvent {
  final int page;
  OrderHistoryFetchRequested({this.page = 1});
}

class OrderHistoryRefreshRequested extends OrderHistoryEvent {}

enum OrderHistoryStatus { initial, loading, success, failure, empty }

class OrderHistoryState {
  final OrderHistoryStatus status;
  final List<ScooterOrder> orders;
  final String? errorMessage;
  final int currentPage;
  final bool hasMore; // можно оставить, но всегда будет false

  OrderHistoryState({
    required this.status,
    this.orders = const [],
    this.errorMessage,
    this.currentPage = 1,
    this.hasMore = false, // ✅ По умолчанию — нет больше данных
  });

  OrderHistoryState copyWith({
    OrderHistoryStatus? status,
    List<ScooterOrder>? orders,
    String? errorMessage,
    int? currentPage,
    bool? hasMore,
  }) {
    return OrderHistoryState(
      status: status ?? this.status,
      orders: orders ?? this.orders,
      errorMessage: errorMessage ?? this.errorMessage,
      currentPage: currentPage ?? this.currentPage,
      hasMore: hasMore ?? this.hasMore,
    );
  }
}

class OrderHistoryBloc extends Bloc<OrderHistoryEvent, OrderHistoryState> {
  final GetScooterOrderHistoryUsecase _usecase;

  OrderHistoryBloc(this._usecase)
      : super(OrderHistoryState(status: OrderHistoryStatus.initial)) {
    on<OrderHistoryFetchRequested>(_onFetchRequested);
    on<OrderHistoryRefreshRequested>(_onRefreshRequested);
  }

  Future<void> _onFetchRequested(
      OrderHistoryFetchRequested event,
      Emitter<OrderHistoryState> emit,
      ) async {
    if (event.page == 1) {
      emit(state.copyWith(status: OrderHistoryStatus.loading));
    }

    final result = await _usecase.call(
      page: event.page,
      pageSize: 1000,
    );

    if (result is Success<List<ScooterOrder>>) {
      final orders = result.data;

      if (orders == null || orders.isEmpty) {
        emit(state.copyWith(
          status: OrderHistoryStatus.empty,
          orders: [],
        ));
      } else {
        final newOrders = event.page == 1
            ? orders
            : [...state.orders, ...orders];

        emit(state.copyWith(
          status: OrderHistoryStatus.success,
          orders: newOrders,
          currentPage: event.page,
          hasMore: false,
        ));
      }
    } else if (result is Failure<List<ScooterOrder>>) {
      emit(state.copyWith(
        status: OrderHistoryStatus.failure,
        errorMessage: result.failure.message ?? 'Неизвестная ошибка',
      ));
    }
  }

  Future<void> _onRefreshRequested(
      OrderHistoryRefreshRequested event,
      Emitter<OrderHistoryState> emit,
      ) async {
    emit(state.copyWith(status: OrderHistoryStatus.loading));
    add(OrderHistoryFetchRequested(page: 1));
  }
}