import 'dart:convert';

import 'package:equatable/equatable.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:mitra_corporate/provider/auth_provider.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../app/constant.dart';

import '../../model/auth_model.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 username,
      required String password,
      // required String company_id,
      // required String regional_id,
      bool isRememberMe = false}) async {
    try {
      state = LoginStateLoading();
      final resp = await AuthRepository(dio: ref.read(dioProvider)).login(
        username: username,
        password: password,
        // company_id: company_id,
        // regional_id: regional_id
      );

      state = LoginStateDone(model: resp);
      //Simpan ke token jk remember me
      if (isRememberMe == true) {
        final shared = await SharedPreferences.getInstance();
        resp.isRememberMe = isRememberMe;
        final tokenEncode = jsonEncode(resp);
        await shared.setString(Constant.tokenName, tokenEncode);
      } else {
        // share pref di remove karena remember me tidak di centang
        final shared = await SharedPreferences.getInstance();
        await shared.remove("usernameX");
        await shared.remove("passwordX");
        await shared.remove("isRememberMeX");
        await shared.remove(Constant.tokenName);
      }

      resp.isRememberMe = isRememberMe;
      ref.read(authProvider.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());
}
