import 'package:absensi_sas/model/check_presensi_jam_model.dart';
import 'package:absensi_sas/repository/presensi_repository.dart';

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

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

class CheckPresensiJamStateInit extends CheckPresensiJamState {
  CheckPresensiJamStateInit() : super(DateTime.now());
}

class CheckPresensiJamStateLoading extends CheckPresensiJamState {
  CheckPresensiJamStateLoading() : super(DateTime.now());
}

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

class CheckPresensiJamStateDone extends CheckPresensiJamState {
  final CheckPresensiJamModel model;
  CheckPresensiJamStateDone({
    required this.model,
  }) : super(DateTime.now());
}

//notifier
class CheckPresensiJamNotifier extends StateNotifier<CheckPresensiJamState> {
  final Ref ref;
  CheckPresensiJamNotifier({
    required this.ref,
  }) : super(CheckPresensiJamStateInit());

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

// provider
final checkPresensiJamProvider =
    StateNotifierProvider<CheckPresensiJamNotifier, CheckPresensiJamState>(
  (ref) => CheckPresensiJamNotifier(ref: ref),
);
