import 'dart:convert';

import 'package:absensi_sas/provider/google_login_provider.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../app/constant.dart';
import '../../model/auth_model.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../provider/current_user_provider.dart';
import '../../provider/dio_provider.dart';
import '../../provider/graphql_provider.dart';
import '../../repository/auth_repository.dart';
import '../../repository/base_repository.dart';

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

class LoginStateInit extends LoginState {
  LoginStateInit() : super(DateTime.now());
}

class LoginStateLoading extends LoginState {
  LoginStateLoading() : super(DateTime.now());
}

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

class LoginStateDone extends LoginState {
  final AuthModel model;
  LoginStateDone({
    required this.model,
  }) : super(DateTime.now());
}

//notifier
class LoginNotifier extends StateNotifier<LoginState> {
  final Ref ref;
  LoginNotifier({
    required this.ref,
  }) : super(LoginStateInit());

  void login(
    String email,
    String idGoogleSignIn,
  ) async {
    try {
      state = LoginStateLoading();
      final graphql = ref.read(graphqlProvider(''));
      final dio = ref.read(dioProvider);
      final resp = await AuthRepository(graphql: graphql, dio: dio).login(
        email,
        idGoogleSignIn,
      );

      //Simpan ke token
      final shared = await SharedPreferences.getInstance();
      final token = jsonEncode({
        "date": DateTime.now().toString(),
        "model": resp.model,
        "token": resp.token
      });
      await shared.setString(Constant.bearerName, token);
      ref.read(currentUserProvider.notifier).state = resp;

      // // set google sign in account
      //  final accountEncode = jsonEncode({
      //   "account": account,
      // });
      // await shared.setString(Constant.accountGoogle, accountEncode);
      // ref.read(currentUserGoogleProvider.notifier).state = acc
      
      
      state = LoginStateDone(model: resp);
    } catch (e) {
      if (e is BaseRepositoryException) {
        state = LoginStateError(message: e.message ?? "");
      } else {
        state = LoginStateError(message: e.toString());
      }
    }
  }
}

// provider
final loginProvider = StateNotifierProvider<LoginNotifier, LoginState>(
  (ref) => LoginNotifier(ref: ref),
);
