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

import '../../app/theme.dart';
import '../../features/shared/live_score_actions.dart';
import '../../providers/score_provider.dart';
import '../websocket_service.dart';
import 'score_overlay_bar.dart';

/// Tabellone interattivo: aggiorna punteggio via WebSocket (senza link regia).
class LiveScoreControls extends ConsumerWidget {
  const LiveScoreControls({
    super.key,
    required this.homeName,
    required this.awayName,
    this.compact = false,
    this.lastDelta,
    this.pointsTarget,
    this.onStopStream,
  });

  final String homeName;
  final String awayName;
  final bool compact;
  final int? lastDelta;
  final int? pointsTarget;
  final Future<void> Function()? onStopStream;

  void _sync(WidgetRef ref) {
    if (!ref.read(websocketServiceProvider).isConnected) return;
    ref.read(websocketServiceProvider).sendScoreUpdate(ref.read(scoreProvider));
  }

  Future<void> _pointHome(BuildContext context, WidgetRef ref) async {
    ref.read(scoreProvider.notifier).incrementHome();
    _sync(ref);
    if (!context.mounted) return;
    await LiveScoreActions(ref).afterPointChange(
      context,
      homeName: homeName,
      awayName: awayName,
      onCloseSetConfirmed: () => _closeSet(context, ref),
    );
  }

  Future<void> _pointAway(BuildContext context, WidgetRef ref) async {
    ref.read(scoreProvider.notifier).incrementAway();
    _sync(ref);
    if (!context.mounted) return;
    await LiveScoreActions(ref).afterPointChange(
      context,
      homeName: homeName,
      awayName: awayName,
      onCloseSetConfirmed: () => _closeSet(context, ref),
    );
  }

  Future<void> _closeSet(BuildContext context, WidgetRef ref) async {
    await LiveScoreActions(ref).requestCloseSet(
      context,
      onCloseSetConfirmed: () async {
        ref.read(scoreProvider.notifier).closeSet();
        _sync(ref);
        if (!context.mounted) return;
        await LiveScoreActions(ref).afterCloseSet(
          context,
          homeName: homeName,
          awayName: awayName,
          onStopStream: onStopStream ?? () async {},
        );
      },
    );
  }

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final score = ref.watch(scoreProvider);
    final target = pointsTarget ?? 25;
    final btnStyle = compact
        ? const ButtonStyle(
            padding: WidgetStatePropertyAll(EdgeInsets.symmetric(horizontal: 10, vertical: 6)),
            minimumSize: WidgetStatePropertyAll(Size(44, 32)),
            tapTargetSize: MaterialTapTargetSize.shrinkWrap,
          )
        : null;

    Widget teamControls({
      required String label,
      required int points,
      required VoidCallback onPlus,
      required VoidCallback onMinus,
    }) {
      return Expanded(
        child: Column(
          children: [
            Text(
              label,
              style: Theme.of(context).textTheme.labelMedium?.copyWith(
                    color: compact ? Colors.white70 : null,
                    fontSize: compact ? 10 : null,
                  ),
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 4),
            Text(
              '$points',
              style: Theme.of(context).textTheme.headlineSmall?.copyWith(
                    color: compact ? Colors.white : AppTheme.primaryRed,
                    fontWeight: FontWeight.bold,
                    fontSize: compact ? 22 : null,
                  ),
            ),
            const SizedBox(height: 6),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                FilledButton(
                  style: btnStyle?.merge(FilledButton.styleFrom(
                    backgroundColor: AppTheme.primaryRed,
                    foregroundColor: Colors.white,
                  )),
                  onPressed: onPlus,
                  child: Text(compact ? '+1' : '+1 punto', style: TextStyle(fontSize: compact ? 12 : 13)),
                ),
                const SizedBox(width: 6),
                OutlinedButton(
                  style: btnStyle,
                  onPressed: onMinus,
                  child: Text('−', style: TextStyle(fontSize: compact ? 16 : 18)),
                ),
              ],
            ),
          ],
        ),
      );
    }

    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      mainAxisSize: MainAxisSize.min,
      children: [
        ScoreOverlayBar(
          homeName: homeName,
          awayName: awayName,
          homePoints: score.homePoints,
          awayPoints: score.awayPoints,
          currentSet: score.currentSet,
          homeSets: score.homeSets,
          awaySets: score.awaySets,
          compact: compact,
          lastDelta: lastDelta,
          pointsTarget: pointsTarget,
        ),
        SizedBox(height: compact ? 8 : 12),
        Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            teamControls(
              label: homeName,
              points: score.homePoints,
              onPlus: () => _pointHome(context, ref),
              onMinus: () {
                ref.read(scoreProvider.notifier).decrementHome();
                _sync(ref);
              },
            ),
            Padding(
              padding: EdgeInsets.only(top: compact ? 18 : 24),
              child: Text(
                '$target pt',
                style: Theme.of(context).textTheme.labelSmall?.copyWith(
                      color: compact ? Colors.white54 : AppTheme.textSecondary,
                    ),
              ),
            ),
            teamControls(
              label: awayName,
              points: score.awayPoints,
              onPlus: () => _pointAway(context, ref),
              onMinus: () {
                ref.read(scoreProvider.notifier).decrementAway();
                _sync(ref);
              },
            ),
          ],
        ),
        SizedBox(height: compact ? 6 : 10),
        OutlinedButton(
          style: compact
              ? OutlinedButton.styleFrom(
                  foregroundColor: Colors.white,
                  side: const BorderSide(color: Colors.white54),
                  padding: const EdgeInsets.symmetric(vertical: 8),
                )
              : null,
          onPressed: () => _closeSet(context, ref),
          child: Text(compact ? 'Chiudi set' : 'CHIUDI SET'),
        ),
      ],
    );
  }
}
