import 'package:flutter/foundation.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_riverpod/legacy.dart';
import 'package:recording_tool/core/network/api_exception.dart';
import 'package:recording_tool/features/events/model/model_event_info.dart';
import 'package:recording_tool/features/events/server/server_events.dart';
import 'package:recording_tool/features/events/state/state_event_info.dart';
import 'package:recording_tool/shared/widgets/app_toast.dart';

final eventInfoProvider =
    StateNotifierProvider<EventInfoViewModel, EventInfoState>((ref) {
      return EventInfoViewModel(ref);
    });

class EventInfoViewModel extends StateNotifier<EventInfoState> {
  EventInfoViewModel(this._ref) : super(const EventInfoState());

  static const defaultRegistrationRequest = PlayerRegistrationListReq(
    userId: '',
    status: '',
  );

  static const _fallbackEventId = '';
  static const _fallbackItemId = '';
  static const _fallbackStreamUserId = '';

  final Ref _ref;

  Future<bool> loadRegistrationList({
    PlayerRegistrationListReq request = defaultRegistrationRequest,
  }) async {
    if (request.userId.isEmpty) {
      return false;
    }
    try {
      final result = await _ref
          .read(eventsServerProvider)
          .fetchPlayerRegistrationList(request);
      debugPrint('报名列表请求成功: $result');
      state = state.copyWith(
        profile: result.toProfile(),
        total: result.total,
        items: result.items,
      );
      return true;
    } catch (error) {
      debugPrint('报名列表请求失败: $error');
      AppToast.show('报名列表加载失败');
      return false;
    }
  }

  Future<void> requestStreamKey(EventRegistrationItem item) async {
    state = state.copyWith(isRequestingStreamKey: true);
    final req = StreamKeyReq(
      eventId: item.eventId.isNotEmpty ? item.eventId : _fallbackEventId,
      itemId: item.itemId.isNotEmpty ? item.itemId : _fallbackItemId,
      userId: item.userId.isNotEmpty ? item.userId : _fallbackStreamUserId,
    );

    try {
      final response = await _ref
          .read(eventsServerProvider)
          .fetchStreamKey(req);
      debugPrint('推流 Key 接口响应: $response');
      state = state.copyWith(isRequestingStreamKey: false);
    } on ApiException catch (error) {
      debugPrint('推流 Key 接口请求失败: ${error.message}');
      state = state.copyWith(isRequestingStreamKey: false);
      AppToast.show(error.message);
    } catch (error) {
      debugPrint('推流 Key 接口请求失败: $error');
      state = state.copyWith(isRequestingStreamKey: false);
      AppToast.show('推流 Key 获取失败');
    }
  }
}
