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

import '../model/service_model.dart';
import '../repository/base_repository.dart';
import '../repository/service_repository.dart';
import 'dio_provider.dart';

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

class ServiceListStateInit extends ServiceListState {
  ServiceListStateInit() : super(DateTime.now());
}

class ServiceListStateLoading extends ServiceListState {
  ServiceListStateLoading() : super(DateTime.now());
}

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

class ServiceListStateDone extends ServiceListState {
  final List<Layanan> model;
  ServiceListStateDone({
    required this.model,
  }) : super(DateTime.now());
}

//notifier
class ServiceListNotifier extends StateNotifier<ServiceListState> {
  final Ref ref;
  ServiceListNotifier({
    required this.ref,
  }) : super(ServiceListStateInit());

  void list(String branchID) async {
    try {
      state = ServiceListStateLoading();
      final dio = ref.read(dioProvider);
      final resp = await ServiceRepository(dio: dio).getData(branchID);
      state = ServiceListStateDone(model: resp);
    } catch (e) {
      if (e is BaseRepositoryException) {
        state = ServiceListStateError(message: e.message);
      } else {
        state = ServiceListStateError(message: e.toString());
      }
    }
  }
}

//provider
final serviceProvider =
    StateNotifierProvider<ServiceListNotifier, ServiceListState>(
        (ref) => ServiceListNotifier(ref: ref));
