import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_riverpod/legacy.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_auth.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) {
        final ok = await parseTokenSetState();
        if (!ok) {
          state = const AuthState(errorMessage: '获取赛事信息失败，请重试');
          return false;
        }
      }
      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() async {
    final data = await AuthServer.getLoginDeviceInfo(_ref);
    if (data == null) return false;
    state = state.copyWith(jwtDecodedData: data);
    return true;
    // final decoded = JwtDecoder.decode(token);
    // final rawData = decoded['data'];
    // if (rawData is! Map) return false;
    // try {
    //   final data = JwtDecodedData.fromJson(Map<String, dynamic>.from(rawData));
    //   state = state.copyWith(jwtDecodedData: data);
    //   return true;
    // } catch (error) {
    //   debugPrint('认证失败，请重试: $error');
    //   return false;
    // }
  }

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

  /// 获取指定目录的录像列表（不更新 state，用于目录下钻）
  Future<List<RecordListItem>?> fetchRecordList(String path) async {
    if (path.isEmpty) return null;
    final nasIpAddr = state.jwtDecodedData?.nasIpAddr?.trim() ?? '';
    if (nasIpAddr.isEmpty) return null;
    final data = await AuthServer.getRecordList(
      _ref,
      path: path,
      nasIpAddr: nasIpAddr,
    );
    return data?.items;
  }

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