import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:recording_tool/features/competition_teams/model/model_competition_team_detail.dart';
import 'package:recording_tool/gen/assets.gen.dart';

/// 弹窗回传选中侧索引：0 = teamA（红队），1 = teamB（蓝队）
class ManualWinnerDialog extends StatefulWidget {
  const ManualWinnerDialog({
    super.key,
    required this.matchup,
    this.initialWinnerSideIndex,
  });

  final Matchup matchup;
  final int? initialWinnerSideIndex;

  static Future<int?> show(
    BuildContext context, {
    required Matchup matchup,
    int? initialWinnerSideIndex,
  }) {
    return showDialog<int>(
      context: context,
      barrierDismissible: false,
      builder: (_) => ManualWinnerDialog(
        matchup: matchup,
        initialWinnerSideIndex: initialWinnerSideIndex,
      ),
    );
  }

  @override
  State<ManualWinnerDialog> createState() => _ManualWinnerDialogState();
}

class _ManualWinnerDialogState extends State<ManualWinnerDialog> {
  /// 0 = teamA，1 = teamB
  int? _selectedSideIndex;

  Team? get _teamA {
    final teams = widget.matchup.teamA;
    if (teams == null || teams.isEmpty) return null;
    return teams.first;
  }

  Team? get _teamB {
    final teams = widget.matchup.teamB;
    if (teams == null || teams.isEmpty) return null;
    return teams.first;
  }

  @override
  void initState() {
    super.initState();
    final initial = widget.initialWinnerSideIndex;
    if (initial == 0 || initial == 1) {
      _selectedSideIndex = initial;
    }
  }

  @override
  Widget build(BuildContext context) {
    final teamA = _teamA;
    final teamB = _teamB;
    final maxHeight = MediaQuery.sizeOf(context).height * 0.78;

    return Dialog(
      insetPadding: EdgeInsets.symmetric(horizontal: 48.w),
      backgroundColor: Colors.transparent,
      elevation: 0,
      child: ConstrainedBox(
        constraints: BoxConstraints(maxWidth: 380.w, maxHeight: maxHeight),
        child: Stack(
          clipBehavior: Clip.none,
          children: [
            ClipRRect(
              borderRadius: BorderRadius.circular(16.r),
              child: Material(
                color: Colors.white,
                child: SingleChildScrollView(
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Padding(
                        padding: EdgeInsets.fromLTRB(18.w, 18.h, 18.w, 18.h),
                        child: Column(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            SizedBox(height: 26.h),
                            Text(
                              '请在比赛结束前处理',
                              key: const ValueKey('manual-winner-dialog-title'),
                              textAlign: TextAlign.center,
                              style: TextStyle(
                                fontSize: 18.sp,
                                height: 1.3,
                                fontWeight: FontWeight.w700,
                                color: const Color(0xFF20242B),
                                fontFamily: 'PingFang SC',
                              ),
                            ),
                            SizedBox(height: 16.h),
                            if (teamA != null) ...[
                              _TeamChoice(
                                team: teamA,
                                sideIndex: 0,
                                color: const Color(0xFFFF6575),
                                selected: _selectedSideIndex == 0,
                                onTap: () =>
                                    setState(() => _selectedSideIndex = 0),
                              ),
                              SizedBox(height: 10.h),
                            ],
                            if (teamB != null)
                              _TeamChoice(
                                team: teamB,
                                sideIndex: 1,
                                color: const Color(0xFF21C5AC),
                                selected: _selectedSideIndex == 1,
                                onTap: () =>
                                    setState(() => _selectedSideIndex = 1),
                              ),
                            SizedBox(height: 18.h),
                            Row(
                              children: [
                                Expanded(
                                  child: _DialogActionButton(
                                    label: '取消',
                                    onPressed: () =>
                                        Navigator.of(context).pop(),
                                  ),
                                ),
                                SizedBox(width: 14.w),
                                Expanded(
                                  child: _DialogActionButton(
                                    label: '确定',
                                    filled: true,
                                    onPressed: _selectedSideIndex == null
                                        ? null
                                        : () => Navigator.of(
                                            context,
                                          ).pop(_selectedSideIndex),
                                  ),
                                ),
                              ],
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
            Positioned(
              top: -90.h,
              left: 0,
              right: 0,
              child: Image.asset(
                Assets.images.imageDialogBg.path,
                width: double.infinity,
                height: 112.h,
                fit: BoxFit.cover,
                alignment: Alignment.topCenter,
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class _TeamChoice extends StatelessWidget {
  const _TeamChoice({
    required this.team,
    required this.sideIndex,
    required this.color,
    required this.selected,
    required this.onTap,
  });

  final Team team;
  final int sideIndex;
  final Color color;
  final bool selected;
  final VoidCallback onTap;

  @override
  Widget build(BuildContext context) {
    final name = team.teamName?.trim().isNotEmpty == true
        ? team.teamName!
        : '未命名队伍';
    final players = team.playerNames;
    final backgroundColor = selected
        ? color.withValues(alpha: 0.13)
        : color.withValues(alpha: 0.07);
    return Semantics(
      selected: selected,
      button: true,
      label: '选择$name直接获胜',
      child: Material(
        color: backgroundColor,
        borderRadius: BorderRadius.circular(12.r),
        child: InkWell(
          key: ValueKey('winner-choice-side-$sideIndex'),
          onTap: onTap,
          borderRadius: BorderRadius.circular(12.r),
          child: Container(
            width: double.infinity,
            padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 12.h),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(12.r),
              border: Border.all(
                color: selected ? color : color.withValues(alpha: 0.32),
                width: 1,
              ),
            ),
            child: Row(
              children: [
                AnimatedContainer(
                  duration: const Duration(milliseconds: 160),
                  width: 22.r,
                  height: 22.r,
                  decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    border: Border.all(
                      color: selected ? color : const Color(0xFFB0B4BB),
                      width: 1.2.r,
                    ),
                    color: Colors.transparent,
                  ),
                  child: selected
                      ? Center(
                          child: Container(
                            width: 10.r,
                            height: 10.r,
                            decoration: BoxDecoration(
                              color: color,
                              shape: BoxShape.circle,
                            ),
                          ),
                        )
                      : null,
                ),
                SizedBox(width: 12.w),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        name,
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                          fontSize: 17.sp,
                          height: 1.25,
                          fontWeight: FontWeight.w700,
                          color: const Color(0xFF20242B),
                          fontFamily: 'PingFang SC',
                        ),
                      ),
                      if (players.isNotEmpty) ...[
                        SizedBox(height: 4.h),
                        Text(
                          players,
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                            fontSize: 15.sp,
                            height: 1.25,
                            color: const Color(0xFF69717E),
                            fontFamily: 'PingFang SC',
                          ),
                        ),
                      ],
                    ],
                  ),
                ),
                SizedBox(width: 8.w),
                Text(
                  '直接获胜',
                  maxLines: 1,
                  style: TextStyle(
                    fontSize: 15.sp,
                    fontWeight: FontWeight.w700,
                    color: color,
                    fontFamily: 'PingFang SC',
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

class _DialogActionButton extends StatelessWidget {
  const _DialogActionButton({
    required this.label,
    required this.onPressed,
    this.filled = false,
  });

  final String label;
  final VoidCallback? onPressed;
  final bool filled;

  @override
  Widget build(BuildContext context) {
    final enabled = onPressed != null;
    final radius = BorderRadius.circular(24.r);
    final backgroundColor = filled
        ? (enabled ? null : const Color(0xFFD2D3D8))
        : const Color(0xFFF1F1F1);
    final gradient = filled && enabled
        ? const LinearGradient(colors: [Color(0xFF2F8DFF), Color(0xFF58D1EE)])
        : null;

    return SizedBox(
      height: 40.h,
      child: DecoratedBox(
        decoration: BoxDecoration(
          color: backgroundColor,
          gradient: gradient,
          borderRadius: radius,
        ),
        child: Material(
          color: Colors.transparent,
          child: InkWell(
            onTap: onPressed,
            borderRadius: radius,
            child: Center(
              child: Text(
                label,
                style: TextStyle(
                  fontSize: 15.sp,
                  fontWeight: FontWeight.w500,
                  color: filled
                      ? (enabled ? Colors.white : const Color(0xFF8D9098))
                      : const Color(0xFF343941),
                  fontFamily: 'PingFang SC',
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}
