import 'package:equatable/equatable.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:mitra_corporate/model/order_model.dart';
import 'package:mitra_corporate/repository/surat_jalan_repository.dart';

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

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

class GetOrderListStateInit extends GetOrderListState {
  GetOrderListStateInit() : super(DateTime.now());
}

class GetOrderListStateLoading extends GetOrderListState {
  GetOrderListStateLoading() : super(DateTime.now());
}

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

class GetOrderListStateDone extends GetOrderListState {
  final List<OrderModel> model;
  GetOrderListStateDone({
    required this.model,
  }) : super(DateTime.now());
}

//notifier
class GetOrderListNotifier extends StateNotifier<GetOrderListState> {
  final Ref ref;
  GetOrderListNotifier({
    required this.ref,
  }) : super(GetOrderListStateInit());

  void getData(
      {required String token,
      required String company_id,
      required String regional_id}) async {
    try {
      state = GetOrderListStateLoading();
      final dio = ref.read(dioProvider);
      final resp = await SuratJalanRepository(dio: dio).getOrder(
          token: token, company_id: company_id, regional_id: regional_id);
      state = GetOrderListStateDone(model: resp);
    } catch (e) {
      if (e is BaseRepositoryException) {
        state = GetOrderListStateError(message: e.message.toString());
      } else {
        state = GetOrderListStateError(message: e.toString());
      }
    }
  }
}

//provider
final GetOrderListProvider =
    StateNotifierProvider<GetOrderListNotifier, GetOrderListState>(
        (ref) => GetOrderListNotifier(ref: ref));
