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

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

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

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

class CancelSuratJalanStateInit extends CancelSuratJalanState {
  CancelSuratJalanStateInit() : super(DateTime.now());
}

class CancelSuratJalanStateLoading extends CancelSuratJalanState {
  CancelSuratJalanStateLoading() : super(DateTime.now());
}

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

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

//notifier
class CancelSuratJalanNotifier extends StateNotifier<CancelSuratJalanState> {
  final Ref ref;
  CancelSuratJalanNotifier({
    required this.ref,
  }) : super(CancelSuratJalanStateInit());

  void cancel({required String token, required String deliveryID}) async {
    try {
      state = CancelSuratJalanStateLoading();
      final dio = ref.read(dioProvider);
      final resp = await SuratJalanRepository(dio: dio)
          .cancelSuratJalan(token: token, deliveryID: deliveryID);
      state = CancelSuratJalanStateDone(number: resp);
    } catch (e) {
      if (e is BaseRepositoryException) {
        state = CancelSuratJalanStateError(message: e.message.toString());
      } else {
        state = CancelSuratJalanStateError(message: e.toString());
      }
    }
  }
}

//provider
final CancelSuratJalanProvider =
    StateNotifierProvider<CancelSuratJalanNotifier, CancelSuratJalanState>(
        (ref) => CancelSuratJalanNotifier(ref: ref));
