import 'package:baseproject/core/common/index.dart';
import 'package:baseproject/features/repositories/hra_repository_models.dart';
import 'package:baseproject/features/usecases/order/order_use_cases.dart';

class OrderListViewModel {
  const OrderListViewModel({
    this.isLoading = false,
    this.orders = const <OrderDto>[],
    this.totalRows = 0,
    this.pageIndex = 1,
    this.pageSize = 10,
  });

  final bool isLoading;
  final List<OrderDto> orders;
  final int totalRows;
  final int pageIndex;
  final int pageSize;

  OrderListViewModel copyWith({
    bool? isLoading,
    List<OrderDto>? orders,
    int? totalRows,
    int? pageIndex,
    int? pageSize,
  }) {
    return OrderListViewModel(
      isLoading: isLoading ?? this.isLoading,
      orders: orders ?? this.orders,
      totalRows: totalRows ?? this.totalRows,
      pageIndex: pageIndex ?? this.pageIndex,
      pageSize: pageSize ?? this.pageSize,
    );
  }
}

class OrderListBloc extends BaseCubit<BaseStateBloc<OrderListViewModel>> {
  OrderListBloc(this._orderUseCases)
      : super(
          InitState<OrderListViewModel>(
            const OrderListViewModel(),
          ),
        );

  final OrderUseCases _orderUseCases;

  Future<void> loadFirstPage() async {
    final currentModel = state.model;

    emit(
      LoadingState<OrderListViewModel>(
        currentModel.copyWith(isLoading: true, pageIndex: 1),
      ),
    );

    final result = await _orderUseCases.getMyOrders(
      pageIndex: 1,
      pageSize: currentModel.pageSize,
    );

    result.fold(
      (error) {
        emit(
          LoadedState<OrderListViewModel>(
            currentModel.copyWith(
              isLoading: false,
            ),
          ),
        );
      },
      (data) {
        emit(
          LoadedState<OrderListViewModel>(
            currentModel.copyWith(
              isLoading: false,
              pageIndex: 1,
              totalRows: data.totalRows ?? 0,
              orders: data.data ?? <OrderDto>[],
            ),
          ),
        );
      },
    );
  }

  Future<List<OrderDto>> loadMore() async {
    final currentModel = state.model;
    final nextPage = currentModel.pageIndex + 1;

    final result = await _orderUseCases.getMyOrders(
      pageIndex: nextPage,
      pageSize: currentModel.pageSize,
    );

    return result.fold(
      (error) => <OrderDto>[],
      (data) {
        final List<OrderDto> newOrders = data.data ?? <OrderDto>[];
        final List<OrderDto> updatedOrders = <OrderDto>[
          ...currentModel.orders,
          ...newOrders,
        ];

        emit(
          LoadedState<OrderListViewModel>(
            currentModel.copyWith(
              pageIndex: nextPage,
              totalRows: data.totalRows ?? currentModel.totalRows,
              orders: updatedOrders,
            ),
          ),
        );

        return newOrders;
      },
    );
  }

  Future<void> refreshList() async {
    await loadFirstPage();
  }
}

