import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:recording_tool/app/config/app_config.dart';
import 'package:recording_tool/app/router/app_navigator.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/model/model_event_info.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_qr_scanner_dialog.dart';
import 'package:recording_tool/shared/widgets/app_toast.dart';
import 'package:recording_tool/shared/widgets/app_webview.dart';

typedef TeamQrScanner = Future<String?> Function(BuildContext context);

class EventTeamMatchPage extends ConsumerStatefulWidget {
  const EventTeamMatchPage({
    super.key,
    required this.playerId,
    this.qrScanner,
    required this.detail,
    required this.item,
  });

  final CompetitionTeamDetail detail;
  final String playerId;
  final TeamQrScanner? qrScanner;
  final EventRegistrationItem item;

  @override
  ConsumerState<EventTeamMatchPage> createState() => _EventTeamMatchPageState();
}

class _EventTeamMatchPageState extends ConsumerState<EventTeamMatchPage> {
  final Set<String> _verifiedUserIds = <String>{};

  /// 0 = 红队(teamA)，1 = 蓝队(teamB)
  int? _winnerSideIndex;

  CompetitionTeamDetail get _detail => widget.detail;

  /// 备注：teamA 为红队，teamB 为蓝队。
  Matchup? get _firstMatchup {
    final matchups = _detail.matchups;
    if (matchups == null || matchups.isEmpty) return null;
    return matchups.first;
  }

  /// 红队（teamA）
  Team? get _redRawTeam {
    final teams = _firstMatchup?.teamA;
    if (teams == null || teams.isEmpty) return null;
    return teams.first;
  }

  /// 蓝队（teamB）
  Team? get _blueRawTeam {
    final teams = _firstMatchup?.teamB;
    if (teams == null || teams.isEmpty) return null;
    return teams.first;
  }

  CompetitionTeam get _redTeam => _toCompetitionTeam(
    _redRawTeam,
    fallbackId: 'red-team',
    fallbackName: '红队',
  );

  CompetitionTeam get _blueTeam => _toCompetitionTeam(
    _blueRawTeam,
    fallbackId: 'blue-team',
    fallbackName: '蓝队',
  );

  List<EventTeamMember> get _redMembers =>
      _toEventMembers(_redRawTeam?.players);

  List<EventTeamMember> get _blueMembers =>
      _toEventMembers(_blueRawTeam?.players);

  CompetitionTeam _toCompetitionTeam(
    Team? team, {
    required String fallbackId,
    required String fallbackName,
  }) {
    final id = team?.leaderUserId ?? '';
    final name = team?.teamName?.trim() ?? '';
    final players = (team?.players ?? const <Player>[])
        .map(
          (player) => CompetitionPlayer(
            id: player.id?.trim() ?? '',
            name: player.name?.trim() ?? '',
          ),
        )
        .toList(growable: false);
    return CompetitionTeam(
      id: id.isNotEmpty ? id : fallbackId,
      name: name.isNotEmpty ? name : fallbackName,
      players: players,
    );
  }

  List<EventTeamMember> _toEventMembers(List<Player>? players) {
    if (players == null || players.isEmpty) return const [];
    return players
        .map(
          (player) => EventTeamMember(
            userId: player.id?.trim() ?? '',
            name: player.name?.trim() ?? '',
            isLeader: player.isLeader ?? false,
          ),
        )
        .toList(growable: false);
  }

  @override
  void initState() {
    super.initState();
    final initialPlayerId = widget.playerId.trim();
    if (_isKnownMember(initialPlayerId)) {
      _verifiedUserIds.add(initialPlayerId);
    }
  }

  bool _isKnownMember(String userId) {
    if (userId.isEmpty) return false;
    return _redMembers.any((member) => member.userId == userId) ||
        _blueMembers.any((member) => member.userId == userId);
  }

  String _memberNameOf(String userId) {
    for (final member in [..._redMembers, ..._blueMembers]) {
      if (member.userId == userId) {
        return member.name.isEmpty ? '参赛成员' : member.name;
      }
    }
    return '';
  }

  Future<void> _continueScan() async {
    final scan = widget.qrScanner ?? AppQrScannerDialog.show;
    final result = (await scan(context))?.trim();
    if (!mounted || result == null || result.isEmpty) return;
    if (!_isKnownMember(result)) {
      AppToast.show('未找到对应参赛成员');
      return;
    }
    if (_verifiedUserIds.contains(result)) {
      AppToast.show('${_memberNameOf(result)}已完成核验');
      return;
    }
    setState(() => _verifiedUserIds.add(result));
    AppToast.show('${_memberNameOf(result)}核验成功');
  }

  Future<void> _manualProcess() async {
    final matchup = _firstMatchup;
    if (matchup == null) {
      AppToast.show('暂无对阵信息');
      return;
    }

    final winnerSide = await ManualWinnerDialog.show(
      context,
      matchup: matchup,
      initialWinnerSideIndex: _winnerSideIndex,
    );
    if (!mounted || winnerSide == null) return;

    final winnerTeam = winnerSide == 0 ? _redRawTeam : _blueRawTeam;
    final loserTeam = winnerSide == 0 ? _blueRawTeam : _redRawTeam;

    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: widget.item.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(() => _winnerSideIndex = winnerSide);
      final winnerName = winnerTeam?.teamName?.trim().isNotEmpty == true
          ? winnerTeam!.teamName!
          : (winnerSide == 0 ? _redTeam.name : _blueTeam.name);
      AppToast.show('已设置$winnerName直接获胜');
    } catch (error) {
      if (!mounted) return;
      final message = error is ApiException && error.message.isNotEmpty
          ? error.message
          : '设置失败，请重试';
      AppToast.show(message);
    }
  }

  void _startDirectly() {
    AppNavigator.push(
      buildTeamScorePage(item: widget.item, playerId: widget.playerId),
      context: context,
    );
  }

  @override
  Widget build(BuildContext context) {
    final redTeam = _redTeam;
    final blueTeam = _blueTeam;
    return Scaffold(
      backgroundColor: const Color(0xFFF6F7F9),
      appBar: myAppBar(
        context: context,
        titleWidget: Text(
          '选手检录',
          style: TextStyle(
            fontSize: 14.sp,
            fontWeight: FontWeight.w500,
            color: Colors.white,
            fontFamily: 'PingFang SC',
          ),
        ),
        actions: [
          TextButton(
            key: const ValueKey('event-team-manual-process'),
            onPressed: _manualProcess,
            style: TextButton.styleFrom(
              foregroundColor: Colors.white,
              padding: EdgeInsets.symmetric(horizontal: 14.w),
              minimumSize: Size(72.w, kToolbarHeight),
              tapTargetSize: MaterialTapTargetSize.shrinkWrap,
            ),
            child: Text(
              '人工处理',
              style: TextStyle(
                fontSize: 14.sp,
                fontWeight: FontWeight.w500,
                color: Colors.white.withValues(alpha: 0.8),
                fontFamily: 'PingFang SC',
              ),
            ),
          ),
        ],
      ),
      body: SafeArea(
        top: false,
        child: Column(
          children: [
            // SizedBox(height: 10.h),
            _MatchMetadata(detail: _detail),
            // SizedBox(height: 12.h),
            Expanded(
              child: SingleChildScrollView(
                padding: EdgeInsets.symmetric(horizontal: 0.w, vertical: 20.h),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    _TeamCard(
                      sideLabel: '红方',
                      team: redTeam,
                      members: _redMembers,
                      backgroundImage: Assets.images.imageRedTeam.path,
                      accentColor: const Color(0xFFE84B5B),
                      verifiedUserIds: _verifiedUserIds,
                      winner: _winnerSideIndex == 0,
                    ),
                    SizedBox(height: 8.h),
                    _TeamCard(
                      sideLabel: '蓝方',
                      team: blueTeam,
                      members: _blueMembers,
                      backgroundImage: Assets.images.imageBlueTeam.path,
                      accentColor: const Color(0xFF287FDD),
                      verifiedUserIds: _verifiedUserIds,
                      winner: _winnerSideIndex == 1,
                      emptyMessage: '暂无蓝队成员数据',
                    ),
                  ],
                ),
              ),
            ),
            Padding(
              padding: EdgeInsets.fromLTRB(16.w, 16.h, 16.w, 24.h),
              child: Column(
                children: [
                  _TeamActionButton(
                    label: '继续扫码',
                    iconPath: Assets.images.imageScan.path,
                    onPressed: _continueScan,
                    filled: true,
                  ),
                  SizedBox(height: 12.h),
                  _TeamActionButton(
                    label: '直接开赛',
                    iconPath: 'assets/images/image_start.png',
                    onPressed: _startDirectly,
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

WebviewPage buildTeamScorePage({
  required EventRegistrationItem item,
  required String playerId,
}) {
  return WebviewPage(
    url: AppConfig.current.mainRefereeScoreH5Url,
    eventRegistrationItem: item,
    playerId: playerId,
  );
}

class _MatchMetadata extends StatelessWidget {
  const _MatchMetadata({required this.detail});

  final CompetitionTeamDetail detail;

  @override
  Widget build(BuildContext context) {
    final itemName = detail.itemName?.trim() ?? '';
    final matchPlace = detail.matchPlace?.trim() ?? '';
    final groupName = detail.groupName?.trim() ?? '';
    return Container(
      width: double.infinity,
      padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 12.h),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.black.withValues(alpha: 0.04),
            blurRadius: 12.r,
            offset: Offset(0, 4.h),
          ),
        ],
      ),
      child: Row(
        children: [
          Expanded(
            child: _MetadataText(label: '场地', value: matchPlace),
          ),
          SizedBox(width: 6.w),
          Expanded(
            child: _MetadataText(label: '赛项', value: itemName),
          ),
          SizedBox(width: 6.w),
          Expanded(
            child: _MetadataText(label: '组别', value: groupName),
          ),
        ],
      ),
    );
  }
}

class _MetadataText extends StatelessWidget {
  const _MetadataText({required this.label, required this.value});

  final String label;
  final String value;

  @override
  Widget build(BuildContext context) {
    return Text(
      '$label：${value.isEmpty ? '暂无' : value}',
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
      style: TextStyle(
        fontSize: 13.sp,
        height: 1.35,
        color: const Color(0xFF858B95),
        fontWeight: FontWeight.w600,
        fontFamily: 'PingFang SC',
      ),
    );
  }
}

class _TeamCard extends StatelessWidget {
  const _TeamCard({
    required this.sideLabel,
    required this.team,
    required this.members,
    required this.backgroundImage,
    required this.accentColor,
    required this.verifiedUserIds,
    required this.winner,
    this.emptyMessage = '暂无成员数据',
  });

  final String sideLabel;
  final CompetitionTeam team;
  final List<EventTeamMember> members;
  final String backgroundImage;
  final Color accentColor;
  final Set<String> verifiedUserIds;
  final bool winner;
  final String emptyMessage;

  @override
  Widget build(BuildContext context) {
    final visibleMembers = members
        .where((member) => member.userId.isNotEmpty || member.name.isNotEmpty)
        .toList(growable: false);
    final leader = _leaderOf(visibleMembers);
    final players = visibleMembers
        .where((member) => !identical(member, leader))
        .toList(growable: false);
    final leaderVerified =
        leader != null && verifiedUserIds.contains(leader.userId);
    return Container(
      width: double.infinity,
      constraints: BoxConstraints(minHeight: 106.h),
      padding: EdgeInsets.fromLTRB(12.w, 16.h, 16.w, 12.h),
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage(backgroundImage),
          fit: BoxFit.fill,
        ),
        color: Colors.white,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Expanded(
                child: Text(
                  '$sideLabel队伍名称：${team.name}队伍',
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    fontSize: 16.sp,
                    fontWeight: FontWeight.w700,
                    color: const Color(0xFF30343B),
                    fontFamily: 'PingFang SC',
                  ),
                ),
              ),
              if (winner)
                Container(
                  key: ValueKey('event-team-winner-${team.id}'),
                  padding: EdgeInsets.symmetric(
                    horizontal: 10.w,
                    vertical: 4.h,
                  ),
                  decoration: BoxDecoration(
                    color: accentColor,
                    borderRadius: BorderRadius.circular(12.r),
                  ),
                  child: Text(
                    '胜方',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 11.sp,
                      fontWeight: FontWeight.w700,
                      fontFamily: 'PingFang SC',
                    ),
                  ),
                ),
            ],
          ),
          SizedBox(height: 6.h),
          if (visibleMembers.isEmpty)
            Text(
              emptyMessage,
              style: TextStyle(
                fontSize: 13.sp,
                color: const Color(0xFF747D89),
                fontFamily: 'PingFang SC',
              ),
            )
          else ...[
            if (leader != null)
              _TeamTextLine(
                label: '队长',
                text: _formatMember(leader),
                showOk: verifiedUserIds.contains(leader.userId),
              ),
            if (players.isNotEmpty)
              Row(
                children: [
                  Text(
                    '选手：',
                    style: TextStyle(
                      fontSize: 13.sp,
                      height: 1.35,
                      color: const Color(0xFF747B86),
                      fontWeight: FontWeight.w500,
                      fontFamily: 'PingFang SC',
                    ),
                  ),
                  ...players.map(
                    (member) => Row(
                      children: [
                        Text(
                          _formatMember(member),

                          style: TextStyle(
                            fontSize: 13.sp,
                            height: 1.35,
                            color: const Color(0xFF4D545F),
                          ),
                        ),
                        if (verifiedUserIds.contains(member.userId))
                          Padding(
                            padding: EdgeInsets.only(left: 6.w),
                            child: Image.asset(
                              Assets.images.imageOk.path,
                              width: 18.w,
                              height: 14.h,
                              fit: BoxFit.contain,
                            ),
                          ),
                        Text(
                          (member != players.last ? '、' : ''),
                          style: TextStyle(
                            fontSize: 13.sp,
                            height: 1.35,
                            color: const Color(0xFF4D545F),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
          ],
        ],
      ),
    );
  }

  EventTeamMember? _leaderOf(List<EventTeamMember> members) {
    for (final member in members) {
      if (member.isLeader) return member;
    }
    return members.isEmpty ? null : members.first;
  }

  String _formatMember(EventTeamMember member) {
    final name = member.name.trim().isEmpty ? '暂无' : member.name.trim();
    // final id = member.userId.trim();
    // return id.isEmpty ? name : '$name（$id）';
    return name;
  }
}

class _TeamTextLine extends StatelessWidget {
  const _TeamTextLine({
    required this.label,
    required this.text,
    required this.showOk,
  });

  final String label;
  final String text;
  final bool showOk;

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.only(top: 4.h),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Text(
            '$label：',
            style: TextStyle(
              fontSize: 13.sp,
              height: 1.35,
              color: const Color(0xFF747B86),
              fontWeight: FontWeight.w500,
              fontFamily: 'PingFang SC',
            ),
          ),
          Flexible(
            child: Text(
              text.isEmpty ? '暂无' : text,
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(
                fontSize: 13.sp,
                height: 1.35,
                color: const Color(0xFF4D545F),
                fontWeight: FontWeight.w500,
                fontFamily: 'PingFang SC',
              ),
            ),
          ),
          if (showOk)
            Padding(
              padding: EdgeInsets.only(left: 6.w),
              child: Image.asset(
                Assets.images.imageOk.path,
                width: 18.w,
                height: 14.h,
                fit: BoxFit.contain,
              ),
            ),
        ],
      ),
    );
  }
}

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

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

  @override
  Widget build(BuildContext context) {
    final radius = BorderRadius.circular(28.r);
    final content = Row(
      mainAxisAlignment: MainAxisAlignment.center,
      mainAxisSize: MainAxisSize.min,
      children: [
        Image.asset(
          iconPath,
          width: filled ? 18.w : 18.w,
          height: filled ? 18.h : 18.h,
          fit: BoxFit.contain,
        ),
        SizedBox(width: 4.w),
        Text(
          label,
          style: TextStyle(
            color: filled ? Colors.white : const Color(0xFF359FED),
            fontSize: 16.sp,
            fontWeight: FontWeight.w700,
            fontFamily: 'PingFang SC',
          ),
        ),
      ],
    );

    return SizedBox(
      width: double.infinity,
      height: 45.h,
      child: DecoratedBox(
        decoration: BoxDecoration(
          gradient: filled
              ? const LinearGradient(
                  colors: [Color(0xFF2F8DFF), Color(0xFF57D2EE)],
                )
              : null,
          color: filled ? null : Colors.white,
          borderRadius: radius,
          border: filled
              ? null
              : Border.all(color: const Color(0xFF9FD0F5), width: 1.w),
          boxShadow: filled
              ? [
                  BoxShadow(
                    color: const Color(0xFF2F8DFF).withValues(alpha: 0.24),
                    blurRadius: 10.r,
                    offset: Offset(0, 5.h),
                  ),
                ]
              : null,
        ),
        child: Material(
          color: Colors.transparent,
          child: InkWell(
            onTap: onPressed,
            borderRadius: radius,
            child: Center(child: content),
          ),
        ),
      ),
    );
  }
}
