import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:recording_tool/core/network/api_exception.dart';
import 'package:recording_tool/features/competition_teams/model/model_competition_team.dart';
import 'package:recording_tool/features/competition_teams/model/model_competition_team_detail.dart';
import 'package:recording_tool/features/competition_teams/widgets/widget_manual_winner_dialog.dart';
import 'package:recording_tool/features/events/request_model/request_model_event.dart';
import 'package:recording_tool/features/events/server/server_events.dart';
import 'package:recording_tool/gen/assets.gen.dart';
import 'package:recording_tool/shared/widgets/app_bar.dart';
import 'package:recording_tool/shared/widgets/app_empty_view.dart';
import 'package:recording_tool/shared/widgets/app_toast.dart';

class CompetitionTeamDetailPage extends ConsumerStatefulWidget {
  const CompetitionTeamDetailPage({super.key, required this.detail});

  final CompetitionTeamDetail detail;

  @override
  ConsumerState<CompetitionTeamDetailPage> createState() =>
      _CompetitionTeamDetailPageState();
}

class _CompetitionTeamDetailPageState
    extends ConsumerState<CompetitionTeamDetailPage> {
  /// matchupIndex -> winner side index（0=teamA，1=teamB）
  final Map<int, int> _winners = {};

  CompetitionTeamDetail get _detail => widget.detail;

  String get _title {
    final name = _detail.itemName?.trim() ?? '';
    final group = _detail.groupName?.trim() ?? '';
    if (name.isEmpty) return '参赛队伍';
    return group.isEmpty ? name : '$name （$group）';
  }

  List<Matchup> get _matchups => _detail.matchups ?? const <Matchup>[];

  CompetitionTeam _toCompetitionTeam(Team team, {required String fallbackId}) {
    return CompetitionTeam(
      id: team.leaderUserId ?? fallbackId,
      name: team.teamName?.trim().isNotEmpty == true ? team.teamName! : '未命名队伍',
      players: (team.players ?? const <Player>[])
          .map(
            (player) => CompetitionPlayer(
              id: player.id?.trim() ?? '',
              name: player.name?.trim().isNotEmpty == true
                  ? player.name!
                  : '选手',
            ),
          )
          .toList(growable: false),
    );
  }

  CompetitionMatchup? _toCompetitionMatchup(Matchup matchup, int index) {
    final teamA = matchup.teamA;
    final teamB = matchup.teamB;
    if (teamA == null || teamA.isEmpty || teamB == null || teamB.isEmpty) {
      return null;
    }
    final winnerSide = _winners[index];
    final convertedA = _toCompetitionTeam(teamA.first, fallbackId: 'team-a');
    final convertedB = _toCompetitionTeam(teamB.first, fallbackId: 'team-b');
    return CompetitionMatchup(
      id: '${_detail.scheduleId ?? _detail.itemId ?? 'match'}-$index',
      teamA: convertedA,
      teamB: convertedB,
      winnerTeamId: winnerSide == 0
          ? convertedA.id
          : winnerSide == 1
          ? convertedB.id
          : null,
    );
  }

  @override
  Widget build(BuildContext context) {
    final matchups = _matchups;

    return Scaffold(
      backgroundColor: const Color(0xFFF2F4F7),
      appBar: AppPageBar(title: _title),
      body: matchups.isEmpty
          ? const AppEmptyView(message: '暂无对阵信息')
          : ListView.separated(
              padding: EdgeInsets.only(bottom: 36.h),
              itemCount: matchups.length,
              separatorBuilder: (_, _) => SizedBox(height: 12.h),
              itemBuilder: (context, index) {
                final raw = matchups[index];
                final matchup = _toCompetitionMatchup(raw, index);
                if (matchup == null) {
                  return const SizedBox.shrink();
                }
                return _MatchupCard(
                  matchup: matchup,
                  onManualProcess: () => _handleManualProcess(raw, index),
                );
              },
            ),
    );
  }

  Team? _sideTeam(Matchup matchup, {required bool isTeamA}) {
    final list = isTeamA ? matchup.teamA : matchup.teamB;
    if (list == null || list.isEmpty) return null;
    return list.first;
  }

  Future<void> _handleManualProcess(Matchup raw, int index) async {
    final winnerSide = await ManualWinnerDialog.show(
      context,
      matchup: raw,
      initialWinnerSideIndex: _winners[index],
    );
    if (winnerSide == null || !mounted) return;

    final teamA = _sideTeam(raw, isTeamA: true);
    final teamB = _sideTeam(raw, isTeamA: false);
    final winnerTeam = winnerSide == 0 ? teamA : teamB;
    final loserTeam = winnerSide == 0 ? teamB : teamA;

    final winnerLeaderId = winnerTeam?.leaderUserId;
    final loserLeaderId = loserTeam?.leaderUserId;
    if (winnerLeaderId == null ||
        winnerLeaderId.isEmpty ||
        loserLeaderId == null ||
        loserLeaderId.isEmpty) {
      AppToast.show('无法识别双方队长');
      return;
    }

    try {
      await ref
          .read(eventsServerProvider)
          .setTeamStatus(
            req: SetTeamStatusReq(
              scheduleId: _detail.scheduleId ?? '',
              opponentId: raw.opponentId ?? '',
              teamScore: [
                TeamScore(
                  userId: winnerLeaderId,
                  firstHalfScore: 0,
                  secondHalfScore: 0,
                  decisiveScore: 0,
                  ifWithdraw: true,
                ),
                TeamScore(
                  userId: loserLeaderId,
                  firstHalfScore: 0,
                  secondHalfScore: 0,
                  decisiveScore: 0,
                  ifWithdraw: false,
                ),
              ],
            ),
          );
      if (!mounted) return;
      setState(() => _winners[index] = winnerSide);
      final winnerName = winnerTeam?.teamName?.trim().isNotEmpty == true
          ? winnerTeam!.teamName!
          : '胜方';
      AppToast.show('已设置$winnerName直接获胜');
    } catch (error) {
      if (!mounted) return;
      final message = error is ApiException && error.message.isNotEmpty
          ? error.message
          : '设置失败，请重试';
      AppToast.show(message);
    }
  }
}

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

  /// 背景图 image_team_vs_bg.png 的原始宽高比（1920 x 318）。
  static const double _vsBgAspectRatio = 1920 / 318;

  final CompetitionMatchup matchup;
  final VoidCallback onManualProcess;

  @override
  Widget build(BuildContext context) {
    return Container(
      key: ValueKey('competition-matchup-${matchup.id}'),
      color: Colors.white,
      padding: EdgeInsets.fromLTRB(12.w, 4.h, 12.w, 24.h),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Align(
            alignment: Alignment.centerRight,
            child: TextButton(
              key: ValueKey('manual-process-${matchup.id}'),
              onPressed: onManualProcess,
              style: TextButton.styleFrom(
                padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.h),
                minimumSize: Size.zero,
                tapTargetSize: MaterialTapTargetSize.shrinkWrap,
              ),
              child: Text(
                '人工处理',
                style: TextStyle(
                  fontSize: 15.sp,
                  fontWeight: FontWeight.w500,
                  color: const Color(0xFF078AF2),
                ),
              ),
            ),
          ),
          SizedBox(height: 8.h),
          AspectRatio(
            aspectRatio: _vsBgAspectRatio,
            child: DecoratedBox(
              decoration: BoxDecoration(
                image: DecorationImage(
                  image: AssetImage(Assets.images.imageTeamVsBg.path),
                  fit: BoxFit.fill,
                ),
              ),
              child: Row(
                children: [
                  Expanded(
                    child: _TeamPanel(
                      team: matchup.teamA,
                      isLeft: true,
                      winner: matchup.winnerTeamId == matchup.teamA.id,
                      accentColor: const Color(0xFFFF6B75),
                    ),
                  ),
                  Expanded(
                    child: _TeamPanel(
                      team: matchup.teamB,
                      isLeft: false,
                      winner: matchup.winnerTeamId == matchup.teamB.id,
                      accentColor: const Color(0xFF12A6C8),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}

class _TeamPanel extends StatelessWidget {
  const _TeamPanel({
    required this.team,
    required this.isLeft,
    required this.winner,
    required this.accentColor,
  });

  final CompetitionTeam team;

  /// 左半区（红色面板，右对齐、略偏上）；右半区（蓝色面板，左对齐、略偏下）。
  final bool isLeft;
  final bool winner;
  final Color accentColor;

  @override
  Widget build(BuildContext context) {
    final textAlign = isLeft ? TextAlign.end : TextAlign.start;

    final nameRow = Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Flexible(
          child: Text(
            team.name,
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            textAlign: textAlign,
            style: TextStyle(
              fontSize: 15.sp,
              fontWeight: FontWeight.w600,
              color: const Color(0xFF282E37),
            ),
          ),
        ),
        if (winner) ...[
          SizedBox(width: 4.w),
          Icon(
            Icons.emoji_events,
            key: ValueKey('winner-${team.id}'),
            size: 14.r,
            color: accentColor,
          ),
        ],
      ],
    );

    return Padding(
      // 中线两侧留出 VS 图案空间，外侧避开斜切边缘。
      padding: isLeft
          ? EdgeInsets.only(left: 16.w, right: 30.w, bottom: 10.h)
          : EdgeInsets.only(left: 30.w, right: 16.w, top: 10.h),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: isLeft
            ? CrossAxisAlignment.end
            : CrossAxisAlignment.start,
        children: [
          nameRow,
          SizedBox(height: 4.h),
          Text(
            team.playerNames,
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            textAlign: textAlign,
            style: TextStyle(fontSize: 13.sp, color: const Color(0xFF4E5662)),
          ),
        ],
      ),
    );
  }
}
