import 'package:app_petty_cash/provider/current_info_account_balance_provider.dart';
import 'package:app_petty_cash/repository/home_repository.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

import '../../model/info_account_balance.dart';
import '../../provider/dio_provider.dart';
import '../../repository/base_repository.dart';
import 'list_transaksi_home_provider.dart';

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

class InfoAccountBalanceHomeStateInit extends InfoAccountBalanceHomeState {
  InfoAccountBalanceHomeStateInit() : super(DateTime.now());
}

class InfoAccountBalanceHomeStateLoading extends InfoAccountBalanceHomeState {
  InfoAccountBalanceHomeStateLoading() : super(DateTime.now());
}

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

class InfoAccountBalanceHomeStateDone extends InfoAccountBalanceHomeState {
  final InfoAccountBalanceModel model;
  // final String resp;
  InfoAccountBalanceHomeStateDone({
    required this.model,
  }) : super(DateTime.now());
}

//notifier
class InfoAccountBalanceHomeNotifier
    extends StateNotifier<InfoAccountBalanceHomeState> {
  final Ref ref;
  InfoAccountBalanceHomeNotifier({
    required this.ref,
  }) : super(InfoAccountBalanceHomeStateInit());

  void infoAccountBalanceHome(
    String companyid,
  ) async {
    try {
      state = InfoAccountBalanceHomeStateLoading();
      final dio = ref.read(dioProvider);
      final resp = await HomeRepository(dio: dio).getInfoAccountBalance(
        companyid,
      );
      state = InfoAccountBalanceHomeStateDone(model: resp);
      // list transaksi home
      ref.read(listTransaksiHomeProvider.notifier).listTransaksiHome(companyid);
    } catch (e) {
      if (e is BaseRepositoryException) {
        state = InfoAccountBalanceHomeStateError(message: e.message.toString());
      } else {
        state = InfoAccountBalanceHomeStateError(message: e.toString());
      }
    }
  }
}

//provider
final infoAccountBalanceHomeProvider = StateNotifierProvider<
    InfoAccountBalanceHomeNotifier, InfoAccountBalanceHomeState>(
  (ref) => InfoAccountBalanceHomeNotifier(ref: ref),
);
