import 'package:flutter/material.dart';
import '../core/network/api_response.dart';
import '../core/network/dio_client.dart';
import '../core/storage/local_storage.dart';
import '../data/models/user.dart';
import '../data/services/user_service.dart';

/// 认证状态管理
class AuthProvider extends ChangeNotifier {
  final UserService _userService;

  User? _user;
  bool _isLoggedIn = false;
  bool _isLoading = false;
  String? _token;

  AuthProvider(this._userService) {
    _initAuth();
  }

  // Getters
  User? get user => _user;
  bool get isLoggedIn => _isLoggedIn;
  bool get isLoading => _isLoading;
  String? get token => _token;

  /// 初始化认证状态
  Future<void> _initAuth() async {
    _token = LocalStorage.getToken();
    _isLoggedIn = _token?.isNotEmpty == true;

    if (_isLoggedIn) {
      _user = _loadUserFromStorage();
    }
    notifyListeners();
  }

  User? _loadUserFromStorage() {
    final userJson = LocalStorage.getUserInfo();
    return userJson != null ? User.fromJson(userJson) : null;
  }

  /// 登录
  Future<ApiResponse<User>> login(String username, String password) {
    return _authenticate(() => _userService.login(username, password));
  }

  /// 注册
  Future<ApiResponse<User>> register(String username, String password) {
    return _authenticate(() => _userService.register(username, password));
  }

  /// 统一认证处理
  Future<ApiResponse<User>> _authenticate(
    Future<ApiResponse<Map<String, dynamic>>> Function() action,
  ) async {
    _setLoading(true);

    try {
      final response = await action();

      if (!response.success || response.data == null) {
        return ApiResponse.fail(response.message ?? '操作失败');
      }

      return _handleAuthSuccess(response.data!, response.message);
    } catch (e) {
      return ApiResponse.fail('操作失败: $e');
    } finally {
      _setLoading(false);
    }
  }

  /// 处理认证成功
  ApiResponse<User> _handleAuthSuccess(
    Map<String, dynamic> data,
    String? message,
  ) {
    _token = data['token'] as String?;
    final userJson = data['user'] as Map<String, dynamic>? ??
        data['userInfo'] as Map<String, dynamic>?;

    if (_token != null) {
      LocalStorage.saveToken(_token!);
    }

    if (userJson != null) {
      LocalStorage.saveUserInfo(userJson);
      _user = User.fromJson(userJson);
    }

    _isLoggedIn = true;

    return _user != null
        ? ApiResponse.success(_user!, message)
        : ApiResponse.fail('用户信息获取失败');
  }

  /// 退出登录
  Future<void> logout() async {
    _setLoading(true);

    try {
      await _userService.logout();
    } catch (_) {
      // 忽略退出登录的接口错误
    }

    _clearAuthState();
    _setLoading(false);
  }

  void _clearAuthState() {
    LocalStorage.clearUserData();
    _user = null;
    _token = null;
    _isLoggedIn = false;
  }

  /// 刷新用户信息
  Future<void> refreshUserInfo() async {
    if (!_isLoggedIn) return;

    try {
      final response = await _userService.getUserInfo();
      if (response.success && response.data != null) {
        _user = response.data;
        await LocalStorage.saveUserInfo(_user!.toJson());
        notifyListeners();
      }
    } catch (_) {
      // 忽略错误
    }
  }

  void _setLoading(bool value) {
    _isLoading = value;
    notifyListeners();
  }
}
