import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

import '../../providers/match_rules_provider.dart';
import '../../providers/score_provider.dart';
import '../../shared/scoring/match_scoring_rules.dart';
import '../../shared/widgets/score_outcome_dialogs.dart';

/// Gestione regole punteggio, dialoghi set/partita e sync.
class LiveScoreActions {
  LiveScoreActions(this.ref);

  final WidgetRef ref;
  bool _dialogOpen = false;

  MatchScoringRules get _rules => ref.read(matchScoringRulesProvider);

  Future<void> afterPointChange(
    BuildContext context, {
    required String homeName,
    required String awayName,
    required Future<void> Function() onCloseSetConfirmed,
  }) async {
    if (_dialogOpen || !context.mounted) return;
    final score = ref.read(scoreProvider);
    final winner = _rules.setWinnerFromPoints(
      homePoints: score.homePoints,
      awayPoints: score.awayPoints,
      currentSet: score.currentSet,
    );
    if (winner == null) return;

    _dialogOpen = true;
    final close = await showSetWonDialog(
      context,
      winner: winner,
      homeName: homeName,
      awayName: awayName,
      homePoints: score.homePoints,
      awayPoints: score.awayPoints,
    );
    _dialogOpen = false;
    if (close && context.mounted) {
      await onCloseSetConfirmed();
    }
  }

  Future<void> requestCloseSet(
    BuildContext context, {
    required Future<void> Function() onCloseSetConfirmed,
  }) async {
    if (_dialogOpen || !context.mounted) return;
    final score = ref.read(scoreProvider);
    final winner = _rules.setWinnerFromPoints(
      homePoints: score.homePoints,
      awayPoints: score.awayPoints,
      currentSet: score.currentSet,
    );
    if (winner == null) {
      final ok = await showCloseSetAnywayDialog(context);
      if (!ok) return;
    }
    await onCloseSetConfirmed();
  }

  Future<void> afterCloseSet(
    BuildContext context, {
    required String homeName,
    required String awayName,
    required Future<void> Function() onStopStream,
  }) async {
    if (_dialogOpen || !context.mounted) return;
    final score = ref.read(scoreProvider);
    final winner = _rules.matchWinner(
      homeSets: score.homeSets,
      awaySets: score.awaySets,
    );
    if (winner == null) return;

    _dialogOpen = true;
    final stop = await showMatchWonDialog(
      context,
      winner: winner,
      homeName: homeName,
      awayName: awayName,
      homeSets: score.homeSets,
      awaySets: score.awaySets,
    );
    _dialogOpen = false;
    if (stop && context.mounted) {
      await onStopStream();
    }
  }
}
