import 'package:flutter/material.dart';
import 'package:flutter/services.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/features/competition_teams/model/model_competition_team_detail.dart';
import 'package:recording_tool/features/competition_teams/pages/page_event_team_match.dart';
import 'package:recording_tool/features/competition_teams/server/server_competition_teams.dart';
import 'package:recording_tool/features/events/model/model_event_info.dart';
import 'package:recording_tool/features/events/state/state_event_info.dart';
import 'package:recording_tool/features/events/view_model/view_model_event_info.dart';
import 'package:recording_tool/gen/assets.gen.dart';
import 'package:recording_tool/shared/widgets/app_webview.dart';
import 'package:recording_tool/shared/widgets/widgets.dart';

class EventInfoPage extends ConsumerStatefulWidget {
  const EventInfoPage({super.key, required this.playerId});
  final String playerId;

  @override
  ConsumerState<EventInfoPage> createState() => _EventInfoPageState();
}

class _EventInfoPageState extends ConsumerState<EventInfoPage> {
  @override
  void initState() {
    super.initState();
  }

  Future<void> onItemTap(EventRegistrationItem item) async {
    if (!mounted) return;
    CompetitionTeamDetail? detail;
    if (item.opponentId.isNotEmpty && item.opponentId != '0') {
      // allowByeMatch = 0 （直接晋级）
      // allowByeMatch = 1  （和败方对战）
      // allowByeMatch = -1 （个人赛不适用此配置，所以 = -1）
      // 如果比赛已结束 点击反应
      if (item.completed) return;
      final opponent = item.opponentName.trim();
      if (opponent.isEmpty &&
          (item.allowByeMatch == 0 || item.allowByeMatch == 1)) {
        return;
      }
      detail = await ref
          .read(competitionTeamsServerProvider)
          .fetchTeamDetail(
            itemId: item.itemId,
            eventId: item.eventId,
            scheduleId: item.scheduleId,
            opponentId: item.opponentId,
          );
      if (!mounted) return;
      AppNavigator.push(
        buildEventRegistrationDestination(
          item: item,
          playerId: widget.playerId,
          detail: detail,
        ),
        context: context,
      );
      return;
    }
    await ref
        .read(competitionTeamsServerProvider)
        .fetchTeamDetail(
          itemId: item.itemId,
          eventId: item.eventId,
          scheduleId: item.scheduleId,
          opponentId: item.opponentId,
        );

    if (!mounted) return;

    AppNavigator.push(
      buildEventRegistrationDestination(
        item: item,
        playerId: widget.playerId,
        detail: null,
      ),
      context: context,
    );
  }

  @override
  Widget build(BuildContext context) {
    final state = ref.watch(eventInfoProvider);
    final profile = state.profile;

    return AnnotatedRegion<SystemUiOverlayStyle>(
      value: SystemUiOverlayStyle.light.copyWith(
        statusBarColor: Colors.transparent,
        systemNavigationBarColor: const Color(0xFFF5F6F8),
      ),
      child: Scaffold(
        backgroundColor: const Color(0xFFF5F6F8),
        appBar: myAppBar(context: context),
        body: Stack(
          children: [
            const _TopGradientHeader(),
            SafeArea(
              bottom: false,
              child: Column(
                children: [
                  // _Header(onBack: () => AppNavigator.pop(context: context)),
                  SizedBox(height: 10.h),
                  Padding(
                    padding: EdgeInsets.symmetric(horizontal: 10.w),
                    child: _ProfileSection(
                      profile: profile,
                      eventTitle: state.eventTitle,
                    ),
                  ),
                  SizedBox(height: 8.h),
                  Expanded(
                    child: _ScheduleList(
                      state: state,
                      onRetry: () => ref
                          .read(eventInfoProvider.notifier)
                          .loadRegistrationList(),
                      onItemTap: onItemTap,
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class _TopGradientHeader extends StatelessWidget {
  const _TopGradientHeader();

  @override
  Widget build(BuildContext context) {
    return Positioned(
      top: -10.h,
      left: 0,
      right: 0,
      child: SizedBox(
        height: 219.h,
        width: double.infinity,
        child: Image.asset(Assets.images.imageEventInfoBarBg.path),
      ),
    );
  }
}

Widget buildEventRegistrationDestination({
  required EventRegistrationItem item,
  required String playerId,
  required CompetitionTeamDetail? detail,
}) {
  if (detail != null) {
    return EventTeamMatchPage(playerId: playerId, detail: detail, item: item);
  }
  return WebviewPage(
    url: AppConfig.current.mainRefereeScoreH5Url,
    eventRegistrationItem: item,
    playerId: playerId,
  );
}

class _Header extends StatelessWidget {
  const _Header({required this.onBack});

  final VoidCallback onBack;

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: 44.h,
      child: Align(
        alignment: Alignment.centerLeft,
        child: IconButton(
          onPressed: onBack,
          icon: Icon(Icons.chevron_left_rounded, size: 28.r),
          color: Colors.white,
          tooltip: '返回',
          padding: EdgeInsets.only(left: 10.w),
          constraints: BoxConstraints(minWidth: 44.w, minHeight: 44.h),
        ),
      ),
    );
  }
}

class _ProfileSection extends StatelessWidget {
  const _ProfileSection({required this.profile, required this.eventTitle});

  final EventProfile profile;
  final String eventTitle;

  @override
  Widget build(BuildContext context) {
    final title = eventTitle.trim().isEmpty ? '赛事信息' : eventTitle.trim();
    return Container(
      clipBehavior: Clip.antiAlias,
      padding: EdgeInsets.fromLTRB(12.w, 10.h, 12.w, 12.h),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(6.r),
      ),
      child: Stack(
        children: [
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  profile.avatarUrl.isEmpty
                      ? AppAvatar(
                          size: 52.r,
                          initials: profile.name.isEmpty ? 'S' : profile.name,
                        )
                      : AppAvatar(size: 52.r, imageUrl: profile.avatarUrl),
                  SizedBox(width: 12.w),
                  Expanded(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          profile.name.isEmpty ? '参赛选手' : profile.name,
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                            fontSize: 18.sp,
                            height: 1.2,
                            color: const Color(0xFF33363B),
                            fontWeight: FontWeight.w700,
                          ),
                        ),
                        SizedBox(height: 5.h),
                        Text(
                          profile.phone,
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                            fontSize: 10.sp,
                            height: 1.2,
                            color: const Color(0xFF969CA6),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
              SizedBox(height: 10.h),
              Divider(
                height: 1.h,
                thickness: 1.h,
                color: const Color(0xFFE8EAED),
              ),
              SizedBox(height: 10.h),
              _EventTitleHighlight(title: title),
            ],
          ),
        ],
      ),
    );
  }
}

class _EventTitleHighlight extends StatelessWidget {
  const _EventTitleHighlight({required this.title});

  final String title;

  @override
  Widget build(BuildContext context) {
    return Align(
      alignment: Alignment.centerLeft,
      child: IntrinsicWidth(
        child: Stack(
          alignment: Alignment.bottomLeft,
          children: [
            Positioned(
              left: 0,
              right: 0,
              bottom: 2.h,
              child: Container(
                height: 8.h,
                decoration: BoxDecoration(
                  color: const Color(0xFFB8F5E8),
                  borderRadius: BorderRadius.circular(4.r),
                ),
              ),
            ),
            Text(
              title,
              maxLines: 2,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(
                fontSize: 16.sp,
                height: 1.25,
                color: const Color(0xFF33363B),
                fontWeight: FontWeight.w600,
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class _ScheduleList extends StatelessWidget {
  const _ScheduleList({
    required this.state,
    required this.onRetry,
    required this.onItemTap,
  });

  final EventInfoState state;
  final VoidCallback onRetry;
  final ValueChanged<EventRegistrationItem> onItemTap;

  @override
  Widget build(BuildContext context) {
    if (state.items.isEmpty) {
      return Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(
              '暂无赛事报名信息',
              textAlign: TextAlign.center,
              style: TextStyle(fontSize: 16.sp, color: const Color(0xFF3A3D42)),
            ),
            SizedBox(height: 14.h),
            TextButton(onPressed: onRetry, child: const Text('重新加载')),
          ],
        ),
      );
    }

    return ListView.separated(
      padding: EdgeInsets.fromLTRB(10.w, 0, 10.w, 24.h),
      itemCount: state.items.length,
      separatorBuilder: (_, _) => SizedBox(height: 8.h),
      itemBuilder: (context, index) {
        final item = state.items[index];
        return _ScheduleCard(
          item: item,
          scheduleIndex: index + 1,
          onTap: () => onItemTap(item),
        );
      },
    );
  }
}

class _ScheduleCard extends StatelessWidget {
  const _ScheduleCard({
    required this.item,
    required this.scheduleIndex,
    required this.onTap,
  });

  final EventRegistrationItem item;
  final int scheduleIndex;
  final VoidCallback onTap;

  @override
  Widget build(BuildContext context) {
    return Material(
      color: Colors.white,
      borderRadius: BorderRadius.circular(6.r),
      child: InkWell(
        onTap: onTap,
        borderRadius: BorderRadius.circular(6.r),
        child: Container(
          constraints: BoxConstraints(minHeight: 86.h),
          padding: EdgeInsets.fromLTRB(12.w, 10.h, 14.w, 10.h),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(6.r),
          ),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Expanded(
                child: _ScheduleDetails(
                  item: item,
                  scheduleIndex: scheduleIndex,
                ),
              ),
              SizedBox(width: 12.w),
              _ScheduleStatus(item: item),
            ],
          ),
        ),
      ),
    );
  }
}

class _ScheduleDetails extends StatelessWidget {
  const _ScheduleDetails({required this.item, required this.scheduleIndex});

  final EventRegistrationItem item;
  final int scheduleIndex;

  @override
  Widget build(BuildContext context) {
    final memberLine = _formatMemberLine(item);
    final opponentLine = _formatOpponentLine(item);

    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          _formatTitle(item),
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
          style: TextStyle(
            fontSize: 13.sp,
            height: 1.2,
            color: const Color(0xFF30343A),
            fontWeight: FontWeight.w700,
          ),
        ),
        SizedBox(height: 6.h),
        _MetaText(_formatVenue(item, scheduleIndex)),
        SizedBox(height: 3.h),
        _MetaText(_formatScheduleTime(item)),
        if (memberLine.isNotEmpty) ...[
          SizedBox(height: 3.h),
          _MetaText(memberLine),
        ],
        if (opponentLine.isNotEmpty) ...[
          SizedBox(height: 3.h),
          _MetaText(opponentLine),
        ],
      ],
    );
  }
}

class _MetaText extends StatelessWidget {
  const _MetaText(this.text);

  final String text;

  @override
  Widget build(BuildContext context) {
    return Text(
      text,
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
      style: TextStyle(
        fontSize: 10.sp,
        height: 1.2,
        color: const Color(0xFF6E747D),
        fontWeight: FontWeight.w400,
      ),
    );
  }
}

class _ScheduleStatus extends StatelessWidget {
  const _ScheduleStatus({required this.item});

  final EventRegistrationItem item;

  @override
  Widget build(BuildContext context) {
    final status = item.statusLabel;
    if (status != null) {
      return Text(
        status,
        style: TextStyle(
          fontSize: 10.sp,
          height: 1.2,
          color: const Color(0xFF1DBF73),
          fontWeight: FontWeight.w500,
        ),
      );
    }

    return Text(
      _formatNumberBadge(item),
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
      style: TextStyle(
        fontSize: 20.sp,
        height: 1,
        color: const Color(0xFFF27D69),
        fontWeight: FontWeight.w700,
      ),
    );
  }
}

String _formatTitle(EventRegistrationItem item) {
  if (item.groupName.isEmpty) return item.itemName;
  return '${item.itemName} （${item.groupName}）';
}

String _formatVenue(EventRegistrationItem item, int scheduleIndex) {
  final place = item.matchPlace.trim();
  if (place.isEmpty) return '$scheduleIndex号场馆$scheduleIndex区';
  return '$place号场馆$scheduleIndex区';
}

String _formatScheduleTime(EventRegistrationItem item) {
  final start = DateTime.tryParse(item.matchStartTime);
  final end = DateTime.tryParse(item.matchEndTime);
  if (start == null && end == null) return item.scheduleTime;
  if (start != null && end != null) {
    return '${start.month}月${start.day}日 ${_formatClock(start)}-${_formatClock(end)}';
  }
  final value = start ?? end!;
  return '${value.month}月${value.day}日 ${_formatClock(value)}';
}

String _formatClock(DateTime value) {
  return '${value.hour}:${value.minute.toString().padLeft(2, '0')}';
}

String _formatMemberLine(EventRegistrationItem item) {
  final names = item.teamMembers
      .map((member) => member.name.trim())
      .where((name) => name.isNotEmpty)
      .toList(growable: false);
  return names.join('、');
}

String _formatOpponentLine(EventRegistrationItem item) {
  final opponent = item.opponentName.trim();
  if (opponent.isEmpty && item.allowByeMatch == 0) {
    return item.completed ? '对手：轮空' : '';
  }
  if (opponent.isEmpty && item.allowByeMatch == 1) {
    return '对手：待分配';
  }
  return '对手：$opponent';
}

String _formatNumberBadge(EventRegistrationItem item) {
  return item.playerNo.trim().isEmpty ? '' : '${item.playerNo.trim()}号';
  // final place = item.matchPlace.trim();
  // if (place.isEmpty) return '';
  // final match = RegExp(r'\d+').firstMatch(place);
  // if (match != null) return '${match.group(0)}号';
  // return place;
}
