import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_riverpod/legacy.dart';
import 'package:jwt_decoder/jwt_decoder.dart';
import 'package:recording_tool/core/cache/app_storage.dart';
import 'package:recording_tool/core/cache/storage_keys.dart';
import 'package:recording_tool/core/network/api_exception.dart';
import 'package:recording_tool/features/auth/model/model_jwt.dart';
import 'package:recording_tool/features/auth/server/server_auth.dart';
import 'package:recording_tool/features/auth/state/state_auth.dart';

final authProvider =
    StateNotifierProvider.autoDispose<AuthViewModel, AuthState>((ref) {
      return AuthViewModel(ref);
    });

class AuthViewModel extends StateNotifier<AuthState> {
  AuthViewModel(this._ref) : super(const AuthState());
  final Ref _ref;

  /// 鉴权获取 token
  Future<bool> auth(String code) async {
    final passCode = code.trim();
    if (passCode.isEmpty) {
      state = const AuthState(errorMessage: '请输入执裁口令');
      return false;
    }

    state = const AuthState(isLoading: true);
    try {
      final data = await AuthServer.login(passCode, _ref);
      await AppStorage.setString(StorageKeys.authToken, data.deviceAccessToken);
      state = const AuthState();
      if (data.deviceAccessToken.isNotEmpty) {
        parseTokenSetState(data.deviceAccessToken);
      }
      return true;
    } on FormatException catch (error) {
      state = AuthState(errorMessage: error.message);
      return false;
    } on ApiException catch (error) {
      state = AuthState(errorMessage: error.message);
      return false;
    } catch (_) {
      state = const AuthState(errorMessage: '认证失败，请重试');
      return false;
    }
  }

  /// 解析 TOKEN，并更新状态
  Future<bool> parseTokenSetState(String token) async {
    final decoded = JwtDecoder.decode(token);
    if (decoded['data'] != null && decoded['data'] is Map<String, dynamic>) {
      final data = JwtDecodedData.fromJson(decoded['data']);
      state = state.copyWith(jwtDecodedData: data);
      return true;
    }
    return false;
  }

  /// 获取赛事列表
  Future<bool> getRecordList(String eventName) async {
    if (eventName.isEmpty) return false;
    final data = await AuthServer.getRecordList(_ref, eventName);
    if (data.items == null || data.items!.isEmpty) return false;
    state = state.copyWith(recordList: data.items);
    return true;
  }

  /// 清空授权信息（本地 token + 内存状态）
  Future<void> clearAuth() async {
    await AppStorage.remove(StorageKeys.authToken);
    state = const AuthState();
  }
}
