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/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: Colors.white,
      appBar: AppBar(title: Text(_title)),
      body: matchups.isEmpty
          ? const AppEmptyView(message: '暂无对阵信息')
          : ListView.separated(
              padding: EdgeInsets.fromLTRB(20.w, 24.h, 20.w, 36.h),
              itemCount: matchups.length,
              separatorBuilder: (_, _) => SizedBox(height: 22.h),
              itemBuilder: (context, index) {
                final raw = matchups[index];
                final matchup = _toCompetitionMatchup(raw, index);
                if (matchup == null) {
                  return const SizedBox.shrink();
                }
                return _MatchupCard(
                  matchup: matchup,
                  index: index,
                  matchTitle: raw.matchTitle?.trim() ?? '',
                  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.index,
    required this.matchTitle,
    required this.onManualProcess,
  });

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

  @override
  Widget build(BuildContext context) {
    final title = matchTitle.isEmpty ? '第 ${index + 1} 场' : matchTitle;
    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: [
              Expanded(
                child: Text(
                  title,
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    fontSize: 14.sp,
                    color: const Color(0xFF7A828E),
                  ),
                ),
              ),
              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,
              ),
            ),
          ),
        ],
      ],
    );
  }
}
