import 'package:equatable/equatable.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../models/response_save_pengantaran_hasil_model.dart';
import '../../provider/dio_provider.dart';
import '../../repository/base_repository.dart';
import '../../repository/pengambilan_bahan_repository.dart';
import '../../repository/pengantaran_hasil_dokter_repository.dart';

// 3. state provider
final pengambilanBahanSave = StateNotifierProvider<PengambilanBahanSaveNotifier,
    PengambilanBahanSaveState>((ref) => PengambilanBahanSaveNotifier(ref: ref));

// 2. notifier
class PengambilanBahanSaveNotifier
    extends StateNotifier<PengambilanBahanSaveState> {
  final Ref ref;
  PengambilanBahanSaveNotifier({required this.ref})
      : super(PengambilanBahanSaveStateInit());
  void pengambilanBahanSave({
    required String courierID,
    required String tipeID,
    required String branchID,
    required String branchCode,
    required String name,
    required String destination,
  }) async {
    try {
      state = PengambilanBahanSaveStateLoading();
      final resp = await PengambilanBahanRepository(dio: ref.read(dioProvider))
          .pengambilanBahanSave(
              courierID: courierID,
              tipeID: tipeID,
              branchID: branchID,
              branchCode: branchCode,
              name: name,
              destination: destination);

      state = PengambilanBahanSaveStateDone(model: resp);
    } catch (e) {
      if (e is BaseRepositoryException) {
        state = PengambilanBahanSaveStateError(message: e.message ?? "");
      } else {
        state = PengambilanBahanSaveStateError(message: e.toString());
      }
    }
  }
}

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

class PengambilanBahanSaveStateInit extends PengambilanBahanSaveState {
  PengambilanBahanSaveStateInit() : super(DateTime.now());
}

class PengambilanBahanSaveStateLoading extends PengambilanBahanSaveState {
  PengambilanBahanSaveStateLoading() : super(DateTime.now());
}

class PengambilanBahanSaveStateError extends PengambilanBahanSaveState {
  final String? message;
  PengambilanBahanSaveStateError({
    required this.message,
  }) : super(DateTime.now());
}

class PengambilanBahanSaveStateDone extends PengambilanBahanSaveState {
  final ResponseSavePengantaranHasilModel model;
  PengambilanBahanSaveStateDone({
    required this.model,
  }) : super(DateTime.now());
}
