import 'package:equatable/equatable.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:mitra_corporate/model/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 SearchResultState extends Equatable {
  final DateTime date;
  const SearchResultState(this.date);
  @override
  List<Object?> get props => [date];
}

class SearchResultStateInit extends SearchResultState {
  SearchResultStateInit() : super(DateTime.now());
}

class SearchResultStateLoading extends SearchResultState {
  SearchResultStateLoading() : super(DateTime.now());
}

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

class SearchResultStateDone extends SearchResultState {
  final SearchSuratJalanModel model;
  SearchResultStateDone({
    required this.model,
  }) : super(DateTime.now());
}

//notifier
class SearchResultNotifier extends StateNotifier<SearchResultState> {
  final Ref ref;
  SearchResultNotifier({
    required this.ref,
  }) : super(SearchResultStateInit());

  void getData({
    required String token,
    required String company_id,
    required String rpp,
    required String keyword,
    required String page,
    required String sd,
    required String ed,
  }) async {
    try {
      state = SearchResultStateLoading();
      final dio = ref.read(dioProvider);
      final resp = await SuratJalanRepository(dio: dio).getSuratJalan(
          dateType: "1",
          token: token,
          company_id: company_id,
          rpp: rpp,
          keyword: keyword,
          endDate: ed,
          startDate: sd,
          page: page);
      state = SearchResultStateDone(model: resp);
    } catch (e) {
      if (e is BaseRepositoryException) {
        state = SearchResultStateError(message: e.message.toString());
      } else {
        state = SearchResultStateError(message: e.toString());
      }
    }
  }
}

//provider
final SearchResultProvider =
    StateNotifierProvider<SearchResultNotifier, SearchResultState>(
        (ref) => SearchResultNotifier(ref: ref));
