import 'package:equatable/equatable.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:mitra_corporate/model/search_order_model.dart';
import 'package:mitra_corporate/repository/order_repository.dart';

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

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

class SearchOrderStateInit extends SearchOrderState {
  SearchOrderStateInit() : super(DateTime.now());
}

class SearchOrderStateLoading extends SearchOrderState {
  SearchOrderStateLoading() : super(DateTime.now());
}

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

class SearchOrderStateDone extends SearchOrderState {
  final SearchOrderModel model;
  SearchOrderStateDone({
    required this.model,
  }) : super(DateTime.now());
}

//notifier
class SearchOrderNotifier extends StateNotifier<SearchOrderState> {
  final Ref ref;
  SearchOrderNotifier({
    required this.ref,
  }) : super(SearchOrderStateInit());

  void getData({
    required String token,
    required String companyID,
    required String rpp,
    required String keyword,
    required String page,
    required String startDate,
    required String endDate,
  }) async {
    try {
      state = SearchOrderStateLoading();
      final dio = ref.read(dioProvider);
      final resp = await OrderRepository(dio: dio).searchOrder(
          endDate: endDate,
          startDate: startDate,
          token: token,
          companyID: companyID,
          rpp: rpp,
          keyword: keyword,
          page: page);
      state = SearchOrderStateDone(model: resp);
    } catch (e) {
      if (e is BaseRepositoryException) {
        state = SearchOrderStateError(message: e.message.toString());
      } else {
        state = SearchOrderStateError(message: e.toString());
      }
    }
  }
}

//provider
final SearchOrderProvider =
    StateNotifierProvider<SearchOrderNotifier, SearchOrderState>(
        (ref) => SearchOrderNotifier(ref: ref));
