import 'package:shared_preferences/shared_preferences.dart';
import '../models/user.dart';

class AuthService {
  static const _tokenKey = 'auth_token';
  static const _phoneKey = 'user_phone';
  static const _nicknameKey = 'user_nickname';
  static const _avatarKey = 'user_avatar_path';
  static const _cityKey = 'user_city';
  static const _interestsKey = 'user_interests';
  
  static User? _currentUser;
  static User? get currentUser => _currentUser;
  static bool get isLoggedIn => _currentUser != null;

  static Future<bool> checkLoginStatus() async {
    final prefs = await SharedPreferences.getInstance();
    final token = prefs.getString(_tokenKey);
    if (token != null) {
      _currentUser = User(
        id: '1',
        phone: prefs.getString(_phoneKey) ?? '',
        nickname: prefs.getString(_nicknameKey),
        avatar: prefs.getString(_avatarKey),
        city: prefs.getString(_cityKey) ?? '成都',
        interests: prefs.getStringList(_interestsKey) ?? [],
      );
      return true;
    }
    return false;
  }

  static Future<Map<String, dynamic>> sendCode(String phone) async {
    // Mock: always succeed
    await Future.delayed(const Duration(seconds: 1));
    return {'success': true, 'expiresIn': 120};
  }

  static Future<Map<String, dynamic>> login(String phone, String code) async {
    await Future.delayed(const Duration(seconds: 1));
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(_tokenKey, 'mock_token_${DateTime.now().millisecondsSinceEpoch}');
    await prefs.setString(_phoneKey, phone);
    
    _currentUser = User(
      id: '1',
      phone: phone,
      city: '成都',
    );
    
    return {
      'success': true,
      'isNewUser': true,
      'user': _currentUser,
    };
  }

  static Future<void> updateProfile({
    String? nickname,
    String? avatar,
    int? birthYear,
    String? gender,
    String? city,
    List<String>? interests,
  }) async {
    final prefs = await SharedPreferences.getInstance();
    if (nickname != null) {
      await prefs.setString(_nicknameKey, nickname);
    }
    if (avatar != null) {
      await prefs.setString(_avatarKey, avatar);
    }
    if (city != null) {
      await prefs.setString(_cityKey, city);
    }
    if (interests != null) {
      await prefs.setStringList(_interestsKey, interests);
    }
    _currentUser = User(
      id: _currentUser?.id ?? '1',
      phone: _currentUser?.phone ?? '',
      nickname: nickname ?? _currentUser?.nickname,
      avatar: avatar ?? _currentUser?.avatar,
      birthYear: birthYear ?? _currentUser?.birthYear,
      gender: gender ?? _currentUser?.gender,
      city: city ?? _currentUser?.city ?? '成都',
      interests: interests ?? _currentUser?.interests ?? [],
    );
  }

  static Future<void> logout() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.clear();
    _currentUser = null;
  }
}
