import 'package:shared_preferences/shared_preferences.dart';
import 'api_service.dart';

class AuthService {
  final ApiService api;
  SharedPreferences? _prefs;

  AuthService(this.api);

  Future<void> _initPrefs() async {
    _prefs ??= await SharedPreferences.getInstance();
  }

  bool get isLoggedIn => _prefs?.getString('access_token') != null;
  String? get token => _prefs?.getString('access_token');
  String? get userName => _prefs?.getString('userName');
  String? get userEmail => _prefs?.getString('userEmail');
  String? get userCountry => _prefs?.getString('userCountry');
  String? get userPlan => _prefs?.getString('userPlan');
  String? get userId => _prefs?.getString('userId');
  String? get lastUsedEmail => _prefs?.getString('lastUsedEmail');

  Future<void> init() async {
    await _initPrefs();
    final accessToken = _prefs?.getString('access_token');
    final refreshToken = _prefs?.getString('refresh_token');
    // ignore: avoid_print
    print('[REASONABLE DOUBT-AUTH] Loading tokens: access=${accessToken?.length ?? 0} chars, refresh=${refreshToken?.length ?? 0} chars');
    if (accessToken != null) api.setToken(accessToken);
    if (refreshToken != null) api.setRefreshToken(refreshToken);
  }

  Future<Map<String, dynamic>> login(String email, String password) async {
    final result = await api.login(email: email, password: password);
    await _saveAuth(result);
    await _initPrefs();
    await _prefs!.setString('lastUsedEmail', email);
    return result;
  }

  Future<Map<String, dynamic>> register({
    required String email,
    required String password,
    required String name,
    String? country,
    String language = 'en',
  }) async {
    final result = await api.register(
      email: email,
      password: password,
      name: name,
      country: country,
      language: language,
    );
    await _saveAuth(result);
    await _initPrefs();
    await _prefs!.setString('lastUsedEmail', email);
    return result;
  }

  Future<void> _saveAuth(Map<String, dynamic> result) async {
    await _initPrefs();
    // JWT tokens
    final access = result['access'] as String?;
    final refresh = result['refresh'] as String?;
    if (access != null) {
      await _prefs!.setString('access_token', access);
      api.setToken(access);
    }
    if (refresh != null) {
      await _prefs!.setString('refresh_token', refresh);
      api.setRefreshToken(refresh);
    }
    // User data
    final user = result['user'] as Map<String, dynamic>? ?? result;
    if (user['display_name'] != null) {
      await _prefs!.setString('userName', user['display_name'].toString());
    } else if (user['name'] != null) {
      await _prefs!.setString('userName', user['name'].toString());
    }
    if (user['email'] != null) {
      await _prefs!.setString('userEmail', user['email'].toString());
    }
    if (user['country'] != null) {
      await _prefs!.setString('userCountry', user['country'].toString());
    }
    if (user['plan'] != null) {
      await _prefs!.setString('userPlan', user['plan'].toString());
    }
    if (user['id'] != null) {
      await _prefs!.setString('userId', user['id'].toString());
    }
  }

  Future<bool> tryRefreshToken() async {
    try {
      final result = await api.refreshAccessToken();
      final access = result['access'] as String?;
      if (access != null) {
        await _initPrefs();
        await _prefs!.setString('access_token', access);
        return true;
      }
    } catch (_) {}
    return false;
  }

  Future<void> updateLocalToken(String token) async {
    await _initPrefs();
    await _prefs!.setString('access_token', token);
  }

  Future<void> updateLocalProfile(Map<String, dynamic> data) async {
    await _initPrefs();
    if (data['display_name'] != null) {
      await _prefs!.setString('userName', data['display_name'].toString());
    }
    if (data['country'] != null) {
      await _prefs!.setString('userCountry', data['country'].toString());
    }
  }

  Future<void> logout() async {
    await _initPrefs();
    api.clearToken();
    await _prefs!.remove('access_token');
    await _prefs!.remove('refresh_token');
    await _prefs!.remove('userName');
    await _prefs!.remove('userEmail');
    await _prefs!.remove('userCountry');
    await _prefs!.remove('userPlan');
    await _prefs!.remove('userId');
  }

  Future<bool> hasCompletedOnboarding() async {
    await _initPrefs();
    return _prefs!.getBool('onboardingComplete') ?? false;
  }

  Future<void> completeOnboarding() async {
    await _initPrefs();
    await _prefs!.setBool('onboardingComplete', true);
  }

  Future<String> getLanguage() async {
    await _initPrefs();
    return _prefs!.getString('language') ?? 'en';
  }

  Future<void> setLanguage(String lang) async {
    await _initPrefs();
    await _prefs!.setString('language', lang);
  }
}
