import 'package:equatable/equatable.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:mitra_corporate/model/create_surat_jalan_model.dart';
import 'package:mitra_corporate/repository/surat_jalan_repository.dart';

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

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

class CreateSuratJalanStateInit extends CreateSuratJalanState {
  CreateSuratJalanStateInit() : super(DateTime.now());
}

class CreateSuratJalanStateLoading extends CreateSuratJalanState {
  CreateSuratJalanStateLoading() : super(DateTime.now());
}

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

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

//notifier
class CreateSuratJalanNotifier extends StateNotifier<CreateSuratJalanState> {
  final Ref ref;
  CreateSuratJalanNotifier({
    required this.ref,
  }) : super(CreateSuratJalanStateInit());

  void addOrder({required CreateSuratJalanModel prm}) async {
    try {
      state = CreateSuratJalanStateLoading();
      final dio = ref.read(dioProvider);
      final resp =
          await SuratJalanRepository(dio: dio).createSuratJalan(prm: prm);
      state = CreateSuratJalanStateDone(number: resp);
    } catch (e) {
      if (e is BaseRepositoryException) {
        state = CreateSuratJalanStateError(message: e.message.toString());
      } else {
        state = CreateSuratJalanStateError(message: e.toString());
      }
    }
  }
}

//provider
final CreateSuratJalanProvider =
    StateNotifierProvider<CreateSuratJalanNotifier, CreateSuratJalanState>(
        (ref) => CreateSuratJalanNotifier(ref: ref));
