import 'dart:convert';

import 'package:equatable/equatable.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../app/constant.dart';
import '../../model/auth_model.dart';
import '../../provider/current_user_provider.dart';
import '../../provider/dio_provider.dart';
import '../../repository/auth_repository.dart';
import '../../repository/base_repository.dart';

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

// 2. notifier
class LoginNotifier extends StateNotifier<LoginState> {
  final Ref ref;
  LoginNotifier({required this.ref}) : super(LoginStateInit());
  void login({
    required String email,
    // required String dokterId,
    required String password,
  }) async {
    try {
      state = LoginStateLoading();
      final resp = await AuthRepository(dio: ref.read(dioProvider))
          .login(email: email, password: password);
      
      // print(resp);
      state = LoginStateDone(model: resp);
      //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;

      // print(shared.getString(Constant.bearerName));
    } catch (e) {
      if (e is BaseRepositoryException) {
        state = LoginStateError(message: e.message);
      } else {
        state = LoginStateError(message: e.toString());
      }
    }
  }
}

// 1. state
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());
}
