import 'package:equatable/equatable.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

import 'package:mitra_corporate/repository/order_repository.dart';

import '../../provider/dio_provider.dart';
import '../../repository/base_repository.dart';

abstract class CancelOrderState extends Equatable {
  final DateTime date;
  const CancelOrderState(this.date);
  @override
  List<Object?> get props => [date];
}

class CancelOrderStateInit extends CancelOrderState {
  CancelOrderStateInit() : super(DateTime.now());
}

class CancelOrderStateLoading extends CancelOrderState {
  CancelOrderStateLoading() : super(DateTime.now());
}

class CancelOrderStateError extends CancelOrderState {
  final String message;
  CancelOrderStateError({
    required this.message,
  }) : super(DateTime.now());
}

class CancelOrderStateDone extends CancelOrderState {
  final String number;
  CancelOrderStateDone({
    required this.number,
  }) : super(DateTime.now());
}

//notifier
class CancelOrderNotifier extends StateNotifier<CancelOrderState> {
  final Ref ref;
  CancelOrderNotifier({
    required this.ref,
  }) : super(CancelOrderStateInit());

  void cancel({required String token, required String orderID}) async {
    try {
      state = CancelOrderStateLoading();
      final dio = ref.read(dioProvider);
      final resp = await OrderRepository(dio: dio)
          .cancelOrder(token: token, orderID: orderID);
      state = CancelOrderStateDone(number: resp);
    } catch (e) {
      if (e is BaseRepositoryException) {
        state = CancelOrderStateError(message: e.message.toString());
      } else {
        state = CancelOrderStateError(message: e.toString());
      }
    }
  }
}

//provider
final CancelOrderProvider =
    StateNotifierProvider<CancelOrderNotifier, CancelOrderState>(
        (ref) => CancelOrderNotifier(ref: ref));
