import 'dart:convert';
import 'package:flutter/material.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) {
    _checkAuth();
  }

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

  /// 检查登录状态
  Future<void> _checkAuth() async {
    _isLoading = true;
    notifyListeners();

    _token = LocalStorage.getToken();
    _isLoggedIn = _token != null && _token!.isNotEmpty;

    if (_isLoggedIn) {
      final userJson = LocalStorage.getUserInfo();
      if (userJson != null) {
        _user = User.fromJson(userJson);
      }
    }

    _isLoading = false;
    notifyListeners();
  }

  /// 登录
  Future<ApiResponse<User>> login(String username, String password) async {
    _isLoading = true;
    notifyListeners();

    try {
      final response = await _userService.login(username, password);

      if (response.success && response.data != null) {
        _token = response.data!['token'] as String?;
        final userJson = response.data!['user'] as Map<String, dynamic>? ??
            response.data!['userInfo'] as Map<String, dynamic>?;

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

        _isLoggedIn = true;
        notifyListeners();
        return ApiResponse.success(_user!, response.message);
      }

      _isLoading = false;
      notifyListeners();
      return ApiResponse.fail(response.message ?? '登录失败');
    } catch (e) {
      _isLoading = false;
      notifyListeners();
      return ApiResponse.fail('登录失败: $e');
    }
  }

  /// 注册
  Future<ApiResponse<User>> register(String username, String password) async {
    _isLoading = true;
    notifyListeners();

    try {
      final response = await _userService.register(username, password);

      if (response.success && response.data != null) {
        _token = response.data!['token'] as String?;
        final userJson = response.data!['userInfo'] as Map<String, dynamic>?;

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

        _isLoggedIn = true;
        notifyListeners();
        return ApiResponse.success(_user!, response.message);
      }

      _isLoading = false;
      notifyListeners();
      return ApiResponse.fail(response.message ?? '注册失败');
    } catch (e) {
      _isLoading = false;
      notifyListeners();
      return ApiResponse.fail('注册失败: $e');
    }
  }

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

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

    await LocalStorage.clearUserData();
    _user = null;
    _token = null;
    _isLoggedIn = false;
    _isLoading = false;
    notifyListeners();
  }

  /// 刷新用户信息
  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 (_) {
      // 忽略错误
    }
  }
}
