import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:recording_tool/app/router/app_navigator.dart';
import 'package:recording_tool/features/competition_teams/model/model_competition_team.dart';
import 'package:recording_tool/features/competition_teams/pages/page_competition_team_detail.dart';
import 'package:recording_tool/features/competition_teams/server/server_competition_teams.dart';
import 'package:recording_tool/features/competition_teams/view_model/view_model_competition_teams.dart';
import 'package:recording_tool/shared/widgets/app_empty_view.dart';
import 'package:recording_tool/shared/widgets/app_error_view.dart';
import 'package:recording_tool/shared/widgets/app_loading_view.dart';
import 'package:recording_tool/shared/widgets/app_refresh_list.dart';
import 'package:recording_tool/shared/widgets/app_toast.dart';

class CompetitionTeamListPage extends ConsumerStatefulWidget {
  const CompetitionTeamListPage({super.key});

  @override
  ConsumerState<CompetitionTeamListPage> createState() =>
      _CompetitionTeamListPageState();
}

class _CompetitionTeamListPageState
    extends ConsumerState<CompetitionTeamListPage> {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      ref.read(competitionTeamsProvider.notifier).loadInitial();
    });
  }

  @override
  Widget build(BuildContext context) {
    final state = ref.watch(competitionTeamsProvider);
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(title: const Text('参赛队伍')),
      body: SafeArea(
        top: false,
        child: Builder(
          builder: (context) {
            if (state.isInitialLoading && state.items.isEmpty) {
              return const AppLoadingView(message: '正在加载参赛队伍...');
            }
            if (state.errorMessage != null && state.items.isEmpty) {
              return AppErrorView(
                message: state.errorMessage!,
                onRetry: () =>
                    ref.read(competitionTeamsProvider.notifier).loadInitial(),
              );
            }

            return AppRefreshList<CompetitionTeamListItem>(
              items: state.items,
              onRefresh: ref.read(competitionTeamsProvider.notifier).refresh,
              onLoadMore: ref.read(competitionTeamsProvider.notifier).loadMore,
              enablePullUp: state.hasMore,
              padding: EdgeInsets.fromLTRB(20.w, 18.h, 20.w, 28.h),
              separator: SizedBox(height: 14.h),
              empty: const AppEmptyView(message: '暂无参赛队伍'),
              itemBuilder: (context, item, index) {
                return _CompetitionScheduleCard(
                  item: item,
                  onTap: () async {
                    try {
                      final detail = await ref
                          .read(competitionTeamsServerProvider)
                          .fetchTeamDetail(
                            itemId: item.itemId,
                            eventId: item.eventId,
                          );
                      if (!context.mounted) return;
                      AppNavigator.push(
                        CompetitionTeamDetailPage(detail: detail),
                        context: context,
                      );
                    } catch (error) {
                      AppToast.show('对阵详情加载失败，请重试');
                    }
                  },
                );
              },
            );
          },
        ),
      ),
    );
  }
}

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

  final CompetitionTeamListItem item;
  final VoidCallback onTap;

  @override
  Widget build(BuildContext context) {
    final scheduleText = item.scheduleTime.isEmpty ? '时间待定' : item.scheduleTime;

    return Material(
      key: ValueKey('competition-team-item-${item.itemId}'),
      color: Colors.white,
      borderRadius: BorderRadius.circular(14.r),
      child: InkWell(
        onTap: onTap,
        borderRadius: BorderRadius.circular(14.r),
        child: Container(
          constraints: BoxConstraints(minHeight: 142.h),
          padding: EdgeInsets.all(16.r),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(14.r),
            border: Border.all(color: const Color(0xFFD7DBE2)),
            boxShadow: const [
              BoxShadow(
                color: Color(0x0F1A2230),
                blurRadius: 16,
                offset: Offset(0, 6),
              ),
            ],
          ),
          child: Row(
            children: [
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      item.title,
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                        fontSize: 19.sp,
                        fontWeight: FontWeight.w600,
                        color: const Color(0xFF20242B),
                      ),
                    ),
                    SizedBox(height: 18.h),
                    _InfoLine(
                      icon: Icons.schedule_outlined,
                      text: scheduleText,
                    ),
                  ],
                ),
              ),
              SizedBox(width: 14.w),
              Icon(
                Icons.chevron_right,
                size: 28.r,
                color: const Color(0xFF9AA3AF),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class _InfoLine extends StatelessWidget {
  const _InfoLine({required this.icon, required this.text});

  final IconData icon;
  final String text;

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Icon(icon, size: 18.r, color: const Color(0xFF7B8491)),
        SizedBox(width: 8.w),
        Expanded(
          child: Text(
            text,
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(fontSize: 15.sp, color: const Color(0xFF525B68)),
          ),
        ),
      ],
    );
  }
}
