import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_riverpod/legacy.dart';
import 'package:recording_tool/features/competition_teams/model/model_competition_team.dart';
import 'package:recording_tool/features/competition_teams/server/server_competition_teams.dart';
import 'package:recording_tool/features/competition_teams/state/state_competition_teams.dart';

final competitionTeamsProvider =
    StateNotifierProvider<CompetitionTeamsViewModel, CompetitionTeamsState>((
      ref,
    ) {
      return CompetitionTeamsViewModel(ref);
    });

class CompetitionTeamsViewModel extends StateNotifier<CompetitionTeamsState> {
  CompetitionTeamsViewModel(this._ref) : super(const CompetitionTeamsState());

  static const pageSize = 5;

  final Ref _ref;

  Future<void> loadInitial() async {
    state = state.copyWith(
      isInitialLoading: true,
      isLoadingMore: false,
      isRefreshing: false,
      clearError: true,
    );
    await _loadPage(page: 1, replace: true);
  }

  Future<void> refresh() async {
    if (state.isRefreshing) return;
    state = state.copyWith(isRefreshing: true, clearError: true);
    await _loadPage(page: 1, replace: true);
  }

  Future<void> loadMore() async {
    if (!state.hasMore || state.isLoadingMore || state.isInitialLoading) return;
    state = state.copyWith(isLoadingMore: true, clearError: true);
    await _loadPage(page: state.page + 1, replace: false);
  }

  void selectWinner({
    required String itemId,
    required String matchupId,
    required String winnerTeamId,
  }) {
    final updatedItems = state.items
        .map((item) {
          if (item.itemId != itemId) return item;
          final updatedMatchups = item.matchups
              .map((matchup) {
                if (matchup.id != matchupId) return matchup;
                final validWinner =
                    winnerTeamId == matchup.teamA.id ||
                    winnerTeamId == matchup.teamB.id;
                return validWinner
                    ? matchup.copyWith(winnerTeamId: winnerTeamId)
                    : matchup;
              })
              .toList(growable: false);
          return item.copyWith(matchups: updatedMatchups);
        })
        .toList(growable: false);
    state = state.copyWith(items: updatedItems);
  }

  CompetitionTeamListItem? findItem(String itemId) {
    for (final item in state.items) {
      if (item.itemId == itemId) return item;
    }
    return null;
  }

  Future<void> _loadPage({required int page, required bool replace}) async {
    try {
      final result = await _ref
          .read(competitionTeamsServerProvider)
          .fetchPage(page: page, pageSize: pageSize);
      state = state.copyWith(
        items: replace ? result.items : [...state.items, ...result.items],
        page: result.page,
        hasMore: result.hasMore,
        isInitialLoading: false,
        isRefreshing: false,
        isLoadingMore: false,
        clearError: true,
      );
    } catch (error) {
      state = state.copyWith(
        isInitialLoading: false,
        isRefreshing: false,
        isLoadingMore: false,
        errorMessage: '参赛队伍加载失败，请重试',
      );
    }
  }
}
