import 'package:app_petty_cash/model/company_model.dart';
import 'package:app_petty_cash/repository/company_repository.dart';

import '../../model/list_category_model.dart';
import '../../repository/transaksi_repository.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

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

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

class ListCompanyStateInit extends ListCompanyState {
  ListCompanyStateInit() : super(DateTime.now());
}

class ListCompanyStateLoading extends ListCompanyState {
  ListCompanyStateLoading() : super(DateTime.now());
}

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

class ListCompanyStateDone extends ListCompanyState {
  final List<CompanyModel> model;
  ListCompanyStateDone({
    required this.model,
  }) : super(DateTime.now());
}

//notifier
class ListCompanyNotifier extends StateNotifier<ListCompanyState> {
  final Ref ref;
  ListCompanyNotifier({
    required this.ref,
  }) : super(ListCompanyStateInit());

  void getListCompany({required String userID}) async {
    try {
      state = ListCompanyStateLoading();
      final dio = ref.read(dioProvider);
      final resp =
          await CompanyRepository(dio: dio).getListCompany(userID: userID);
      state = ListCompanyStateDone(model: resp);
    } catch (e) {
      if (e is BaseRepositoryException) {
        state = ListCompanyStateError(message: e.message.toString());
      } else {
        state = ListCompanyStateError(message: e.toString());
      }
    }
  }
}

//provider
final ListCompanyProvider =
    StateNotifierProvider<ListCompanyNotifier, ListCompanyState>(
  (ref) => ListCompanyNotifier(ref: ref),
);
