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/registration_repository.dart';

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

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

class NewOrderProviderStateInit extends NewOrderProviderState {
  NewOrderProviderStateInit() : super(DateTime.now());
}

class NewOrderProviderStateLoading extends NewOrderProviderState {
  NewOrderProviderStateLoading() : super(DateTime.now());
}

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

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

//notifier
class NewOrderProviderNotifier extends StateNotifier<NewOrderProviderState> {
  final Ref ref;
  NewOrderProviderNotifier({
    required this.ref,
  }) : super(NewOrderProviderStateInit());

  void addOrder({required RegistrationModel prm}) async {
    try {
      state = NewOrderProviderStateLoading();
      final dio = ref.read(dioProvider);
      final resp = await RegistrationRepository(dio: dio).addOrder(prm: prm);
      state = NewOrderProviderStateDone(number: resp);
    } catch (e) {
      if (e is BaseRepositoryException) {
        state = NewOrderProviderStateError(message: e.message.toString());
      } else {
        state = NewOrderProviderStateError(message: e.toString());
      }
    }
  }
}

//provider
final NewOrderProviderProvider =
    StateNotifierProvider<NewOrderProviderNotifier, NewOrderProviderState>(
        (ref) => NewOrderProviderNotifier(ref: ref));
