import 'package:hooks_riverpod/hooks_riverpod.dart';

import '../../../common/network/auth_interceptor.dart';
import '../../../common/storage/storage_keys.dart';
import '../../../common/storage/storage_service.dart';
import '../data/auth_models.dart';

final authProvider =
    StateNotifierProvider<AuthController, AsyncValue<AuthState>>(
      (ref) => AuthController(),
    );

class AuthController extends StateNotifier<AsyncValue<AuthState>> {
  AuthController() : super(const AsyncLoading()) {
    _bootstrap();
  }

  Future<void> _bootstrap() async {
    final token = await loadJwt();
    if (token == null || token.isEmpty) {
      state = const AsyncData(GuestAuthState());
      return;
    }
    final phone = StorageService.to.getString(storageJinzhiMockLoggedIn) ?? '';
    state = AsyncData(
      LoggedInAuthState(
        user: JinzhiUser(
          phone: phone.isEmpty ? '13800000000' : phone,
          nickname: '金值用户',
          createdAt: DateTime(2026, 6, 18),
        ),
        token: token,
      ),
    );
  }

  Future<void> sendCode(String phone) async {
    await Future<void>.delayed(const Duration(milliseconds: 200));
  }

  Future<void> verifyCode(String phone, String code) async {
    final token = 'mock-jinzhi-token-$phone-$code';
    await saveJwt(token);
    await StorageService.to.setString(storageJinzhiMockLoggedIn, phone);
    state = AsyncData(
      LoggedInAuthState(
        user: JinzhiUser(
          phone: phone,
          nickname: '金值用户',
          createdAt: DateTime.now(),
        ),
        token: token,
      ),
    );
  }

  Future<void> logout() async {
    await clearJwt();
    await StorageService.to.setString(storageJinzhiMockLoggedIn, '');
    state = const AsyncData(GuestAuthState());
  }

  Future<void> deleteAccount([String? code]) async {
    await logout();
  }

  bool get isLoggedIn => state.valueOrNull is LoggedInAuthState;
}
