import 'package:equatable/equatable.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:mitra_corporate/model/registration_model.dart';
import 'package:mitra_corporate/repository/order_repository.dart';

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

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

class EditOrderStateInit extends EditOrderState {
  EditOrderStateInit() : super(DateTime.now());
}

class EditOrderStateLoading extends EditOrderState {
  EditOrderStateLoading() : super(DateTime.now());
}

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

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

//notifier
class EditOrderNotifier extends StateNotifier<EditOrderState> {
  final Ref ref;
  EditOrderNotifier({
    required this.ref,
  }) : super(EditOrderStateInit());

  void editOrder({required RegistrationModel prm}) async {
    try {
      state = EditOrderStateLoading();
      final dio = ref.read(dioProvider);
      final resp = await OrderRepository(dio: dio).editOrder(prm: prm);
      state = EditOrderStateDone(number: resp);
    } catch (e) {
      if (e is BaseRepositoryException) {
        state = EditOrderStateError(message: e.message.toString());
      } else {
        state = EditOrderStateError(message: e.toString());
      }
    }
  }
}

//provider
final EditOrderProvider =
    StateNotifierProvider<EditOrderNotifier, EditOrderState>(
        (ref) => EditOrderNotifier(ref: ref));
