import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:recording_tool/features/competition_teams/model/model_competition_team.dart';
import 'package:recording_tool/features/competition_teams/view_model/view_model_competition_teams.dart';
import 'package:recording_tool/features/competition_teams/widgets/widget_manual_winner_dialog.dart';
import 'package:recording_tool/shared/widgets/app_empty_view.dart';
import 'package:recording_tool/shared/widgets/app_toast.dart';

class CompetitionTeamDetailPage extends ConsumerWidget {
  const CompetitionTeamDetailPage({super.key, required this.itemId});

  final String itemId;

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final items = ref.watch(
      competitionTeamsProvider.select((state) => state.items),
    );
    CompetitionTeamListItem? item;
    for (final candidate in items) {
      if (candidate.id == itemId) {
        item = candidate;
        break;
      }
    }

    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(title: Text(item?.title ?? '参赛队伍')),
      body: item == null
          ? const AppEmptyView(message: '未找到对阵信息')
          : ListView.separated(
              padding: EdgeInsets.fromLTRB(20.w, 24.h, 20.w, 36.h),
              itemCount: item.matchups.length,
              separatorBuilder: (_, _) => SizedBox(height: 22.h),
              itemBuilder: (context, index) {
                final matchup = item!.matchups[index];
                return _MatchupCard(
                  matchup: matchup,
                  index: index,
                  onManualProcess: () => _handleManualProcess(
                    context,
                    ref,
                    itemId: item!.id,
                    matchup: matchup,
                  ),
                );
              },
            ),
    );
  }

  Future<void> _handleManualProcess(
    BuildContext context,
    WidgetRef ref, {
    required String itemId,
    required CompetitionMatchup matchup,
  }) async {
    final winnerTeamId = await ManualWinnerDialog.show(
      context,
      matchup: matchup,
    );
    if (winnerTeamId == null || !context.mounted) return;

    ref
        .read(competitionTeamsProvider.notifier)
        .selectWinner(
          itemId: itemId,
          matchupId: matchup.id,
          winnerTeamId: winnerTeamId,
        );
    final winnerName = winnerTeamId == matchup.teamA.id
        ? matchup.teamA.name
        : matchup.teamB.name;
    AppToast.show('已设置$winnerName直接获胜');
  }
}

class _MatchupCard extends StatelessWidget {
  const _MatchupCard({
    required this.matchup,
    required this.index,
    required this.onManualProcess,
  });

  final CompetitionMatchup matchup;
  final int index;
  final VoidCallback onManualProcess;

  @override
  Widget build(BuildContext context) {
    return Container(
      key: ValueKey('competition-matchup-${matchup.id}'),
      padding: EdgeInsets.fromLTRB(16.w, 10.h, 16.w, 18.h),
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border.all(color: const Color(0xFFC7CCD4)),
        borderRadius: BorderRadius.circular(12.r),
      ),
      child: Column(
        children: [
          Row(
            children: [
              Text(
                '第 ${index + 1} 场',
                style: TextStyle(
                  fontSize: 14.sp,
                  color: const Color(0xFF7A828E),
                ),
              ),
              const Spacer(),
              TextButton(
                key: ValueKey('manual-process-${matchup.id}'),
                onPressed: onManualProcess,
                child: Text(
                  '人工处理',
                  style: TextStyle(
                    fontSize: 17.sp,
                    fontWeight: FontWeight.w600,
                    color: const Color(0xFF078AF2),
                  ),
                ),
              ),
            ],
          ),
          SizedBox(height: 8.h),
          Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Expanded(
                child: _TeamPanel(
                  team: matchup.teamA,
                  alignment: CrossAxisAlignment.start,
                  winner: matchup.winnerTeamId == matchup.teamA.id,
                  accentColor: const Color(0xFFFF6B75),
                ),
              ),
              Padding(
                padding: EdgeInsets.symmetric(horizontal: 12.w),
                child: Text(
                  'VS',
                  style: TextStyle(
                    fontSize: 21.sp,
                    fontWeight: FontWeight.w700,
                    color: const Color(0xFF303640),
                  ),
                ),
              ),
              Expanded(
                child: _TeamPanel(
                  team: matchup.teamB,
                  alignment: CrossAxisAlignment.end,
                  textAlign: TextAlign.end,
                  winner: matchup.winnerTeamId == matchup.teamB.id,
                  accentColor: const Color(0xFF20BFA9),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }
}

class _TeamPanel extends StatelessWidget {
  const _TeamPanel({
    required this.team,
    required this.alignment,
    required this.winner,
    required this.accentColor,
    this.textAlign = TextAlign.start,
  });

  final CompetitionTeam team;
  final CrossAxisAlignment alignment;
  final TextAlign textAlign;
  final bool winner;
  final Color accentColor;

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: alignment,
      children: [
        AnimatedContainer(
          duration: const Duration(milliseconds: 180),
          padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.h),
          decoration: BoxDecoration(
            color: winner
                ? accentColor.withValues(alpha: 0.14)
                : Colors.transparent,
            borderRadius: BorderRadius.circular(8.r),
          ),
          child: Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              Flexible(
                child: Text(
                  team.name,
                  textAlign: textAlign,
                  style: TextStyle(
                    fontSize: 18.sp,
                    fontWeight: FontWeight.w600,
                    color: const Color(0xFF282E37),
                  ),
                ),
              ),
              if (winner) ...[
                SizedBox(width: 5.w),
                Icon(Icons.emoji_events, size: 17.r, color: accentColor),
              ],
            ],
          ),
        ),
        SizedBox(height: 10.h),
        Text(
          team.playerNames,
          textAlign: textAlign,
          style: TextStyle(
            fontSize: 15.sp,
            height: 1.45,
            color: const Color(0xFF4E5662),
          ),
        ),
        if (winner) ...[
          SizedBox(height: 8.h),
          Container(
            key: ValueKey('winner-${team.id}'),
            padding: EdgeInsets.symmetric(horizontal: 9.w, vertical: 3.h),
            decoration: BoxDecoration(
              color: accentColor,
              borderRadius: BorderRadius.circular(10.r),
            ),
            child: Text(
              '胜方',
              style: TextStyle(
                fontSize: 12.sp,
                fontWeight: FontWeight.w700,
                color: Colors.white,
              ),
            ),
          ),
        ],
      ],
    );
  }
}
