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/features/competition_teams/pages/page_event_team_match.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/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 {
    // debugPrint('item tapped: ${item.itemName}');
    // await ref.read(eventInfoProvider.notifier).requestStreamKey(item);
    if (!mounted) return;
    // final profile = ref.read(eventInfoProvider).profile;

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

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

    return Scaffold(
      backgroundColor: Colors.white,
      body: SafeArea(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _Header(onBack: () => AppNavigator.pop(context: context)),
            Expanded(
              child: SingleChildScrollView(
                padding: EdgeInsets.fromLTRB(62.w, 8.h, 62.w, 40.h),
                child: Column(
                  children: [
                    _ProfileSection(profile: profile),
                    SizedBox(height: 20.h),
                    Text(
                      state.eventTitle,
                      style: TextStyle(
                        fontSize: 20.sp,
                        height: 1.2,
                        color: const Color(0xFF2F2F2F),
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                    SizedBox(height: 24.h),
                    SizedBox(
                      height: 400.h,
                      child: _ScheduleList(
                        state: state,
                        onRetry: () => ref
                            .read(eventInfoProvider.notifier)
                            .loadRegistrationList(),
                        onItemTap: onItemTap,
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

Widget buildEventRegistrationDestination({
  required EventRegistrationItem item,
  required String playerId,
}) {
  if (item.opponentId.isNotEmpty) {
    return EventTeamMatchPage(item: item, playerId: playerId);
  }
  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: 52.h,
      child: Align(
        alignment: Alignment.centerLeft,
        child: IconButton(
          onPressed: onBack,
          icon: Icon(Icons.arrow_back_ios_new, size: 32.r),
          color: Colors.black,
          tooltip: '返回',
          padding: EdgeInsets.only(left: 16.w),
          constraints: BoxConstraints(minWidth: 56.w, minHeight: 52.h),
        ),
      ),
    );
  }
}

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

  final EventProfile profile;

  @override
  Widget build(BuildContext context) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        profile.avatarUrl.isEmpty
            ? AppAvatar(size: 50.r)
            : AppAvatar(size: 50.r, imageUrl: profile.avatarUrl),

        SizedBox(width: 28.w),
        Expanded(
          child: Padding(
            padding: EdgeInsets.only(top: 30.h),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  profile.name,
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    fontSize: 22.sp,
                    height: 1.2,
                    color: const Color(0xFF2F2F2F),
                  ),
                ),
                SizedBox(height: 36.h),
                Text(
                  profile.phone,
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    fontSize: 22.sp,
                    height: 1.2,
                    color: const Color(0xFF2F2F2F),
                  ),
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }
}

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: 18.sp, color: const Color(0xFF2F2F2F)),
            ),
            SizedBox(height: 18.h),
            TextButton(onPressed: onRetry, child: const Text('重新加载')),
          ],
        ),
      );
    }

    return ListView.builder(
      itemCount: state.items.length,
      itemBuilder: (context, index) {
        final item = state.items[index];
        return _ScheduleCard(item: item, onTap: () => onItemTap(item));
      },
    );
  }
}

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

  final EventRegistrationItem item;
  final VoidCallback onTap;

  @override
  Widget build(BuildContext context) {
    return Material(
      color: Colors.white,
      child: InkWell(
        onTap: onTap,
        child: Container(
          constraints: BoxConstraints(minHeight: 138.h),
          padding: EdgeInsets.fromLTRB(10.w, 14.h, 14.w, 0),
          decoration: BoxDecoration(
            border: Border.all(color: const Color(0xFF7A7A7A)),
          ),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      item.groupName.isEmpty
                          ? item.itemName
                          : '${item.itemName} （${item.groupName}）',
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                        fontSize: 20.sp,
                        height: 1.2,
                        color: const Color(0xFF2F2F2F),
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                    SizedBox(height: 26.h),
                    Text(
                      item.matchPlace,
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                        fontSize: 20.sp,
                        height: 1.2,
                        color: const Color(0xFF2F2F2F),
                      ),
                    ),
                    SizedBox(height: 26.h),
                    Text(
                      item.scheduleTime,
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                        fontSize: 20.sp,
                        height: 1.2,
                        color: const Color(0xFF2F2F2F),
                      ),
                    ),
                  ],
                ),
              ),
              SizedBox(width: 12.w),
              SizedBox(
                width: 148.w,
                height: 120.h,
                child: Align(
                  alignment: Alignment.center,
                  child: _ScheduleBadge(item: item),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

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

  final EventRegistrationItem item;

  @override
  Widget build(BuildContext context) {
    if (item.statusLabel != null) {
      return CustomPaint(
        painter: _CutCornerBorderPainter(color: const Color(0xFF7A7A7A)),
        child: SizedBox(
          width: 148.w,
          height: 90.h,
          child: Center(
            child: Text(
              item.statusLabel!,
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(fontSize: 20.sp, color: const Color(0xFF2F2F2F)),
            ),
          ),
        ),
      );
    }

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

class _CutCornerBorderPainter extends CustomPainter {
  const _CutCornerBorderPainter({required this.color});

  final Color color;

  @override
  void paint(Canvas canvas, Size size) {
    final side = 12.r;
    final path = Path()
      ..moveTo(side, 0)
      ..lineTo(size.width - side, 0)
      ..lineTo(size.width, side)
      ..lineTo(size.width, size.height - side)
      ..lineTo(size.width - side, size.height)
      ..lineTo(side, size.height)
      ..lineTo(0, size.height - side)
      ..lineTo(0, side)
      ..close();
    final paint = Paint()
      ..style = PaintingStyle.stroke
      ..strokeWidth = 1
      ..color = color;
    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(covariant _CutCornerBorderPainter oldDelegate) {
    return oldDelegate.color != color;
  }
}
