import 'package:equatable/equatable.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:mitra_corporate/model/search_patient_model.dart';
import 'package:mitra_corporate/repository/patient_repository.dart';

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

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

class SearchPatientStateInit extends SearchPatientState {
  SearchPatientStateInit() : super(DateTime.now());
}

class SearchPatientStateLoading extends SearchPatientState {
  SearchPatientStateLoading() : super(DateTime.now());
}

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

class SearchPatientStateDone extends SearchPatientState {
  final SearchPatientModel model;
  SearchPatientStateDone({
    required this.model,
  }) : super(DateTime.now());
}

//notifier
class SearchPatientNotifier extends StateNotifier<SearchPatientState> {
  final Ref ref;
  SearchPatientNotifier({
    required this.ref,
  }) : super(SearchPatientStateInit());

  void getData(
      {required String token,
      required String page,
      required String keyword,
      required String rpp,
      required String companyID}) async {
    try {
      state = SearchPatientStateLoading();
      final dio = ref.read(dioProvider);
      final resp = await PatientRepository(dio: dio).search(
          companyID: companyID,
          keyword: keyword,
          page: page,
          rpp: rpp,
          token: token);
      state = SearchPatientStateDone(model: resp);
    } catch (e) {
      if (e is BaseRepositoryException) {
        state = SearchPatientStateError(message: e.message.toString());
      } else {
        state = SearchPatientStateError(message: e.toString());
      }
    }
  }
}

//provider
final SearchPatientProvider =
    StateNotifierProvider<SearchPatientNotifier, SearchPatientState>(
        (ref) => SearchPatientNotifier(ref: ref));
