
import '../../model/rekap_kehadiran_home_screen_model.dart';
import '../../provider/current_rekap_kehadiran_home_provider.dart';
import '../../repository/presensi_repository.dart';

import 'package:equatable/equatable.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../provider/dio_provider.dart';
import '../../provider/graphql_provider.dart';
import '../../repository/base_repository.dart';

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

class RekapKehadiranHomeScreenStateInit extends RekapKehadiranHomeScreenState {
  RekapKehadiranHomeScreenStateInit() : super(DateTime.now());
}

class RekapKehadiranHomeScreenStateLoading extends RekapKehadiranHomeScreenState {
  RekapKehadiranHomeScreenStateLoading() : super(DateTime.now());
}

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

class RekapKehadiranHomeScreenStateDone extends RekapKehadiranHomeScreenState {
  final RekapKehadiranHomeScreenModel model;
  RekapKehadiranHomeScreenStateDone({
    required this.model,
  }) : super(DateTime.now());
}

//notifier
class RekapKehadiranHomeScreenNotifier extends StateNotifier<RekapKehadiranHomeScreenState> {
  final Ref ref;
  RekapKehadiranHomeScreenNotifier({
    required this.ref,
  }) : super(RekapKehadiranHomeScreenStateInit());

  void rekapKehadiranHomeScreen(
    String M_StaffID,
    String M_CompanyID,
    String token,
    Map<String, dynamic> paramInpVariables,
  ) async {
    try {
      state = RekapKehadiranHomeScreenStateLoading();
      final graphql = ref.read(graphqlProvider(''));
      final dio = ref.read(dioProvider);
      final resp = await PresensiRepository(graphql: graphql, dio: dio)
          .rekapKehadiranHomeScreen(
        M_StaffID,
        M_CompanyID,
        token,
        paramInpVariables,
      );
      // set ke global state provider currentRekapKehadiranHomeProvider
      ref.read(currentRekapKehadiranHomeProvider.notifier).update((state) => resp);
      state = RekapKehadiranHomeScreenStateDone(model: resp);
    } catch (e) {
      if (e is BaseRepositoryException) {
        print(e.message);
        state = RekapKehadiranHomeScreenStateError(message: e.message ?? "");
      } else {
        state = RekapKehadiranHomeScreenStateError(message: e.toString());
      }
    }
  }
}

// provider
final rekapKehadiranHomeScreenProvider =
    StateNotifierProvider<RekapKehadiranHomeScreenNotifier, RekapKehadiranHomeScreenState>(
  (ref) => RekapKehadiranHomeScreenNotifier(ref: ref),
);
