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_bar.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: const Color(0xFFF5F6F8),
      appBar: AppPageBar(title: '参赛队伍'),
      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(10.w, 10.h, 10.w, 24.h),
              separator: SizedBox(height: 8.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) {
    return Material(
      key: ValueKey('competition-team-item-${item.itemId}'),
      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: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      item.title,
                      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(_formatScheduleTime(item)),
                  ],
                ),
              ),
              SizedBox(width: 12.w),
              Icon(
                Icons.chevron_right,
                size: 20.r,
                color: const Color(0xFF9AA3AF),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

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,
      ),
    );
  }
}

String _formatScheduleTime(CompetitionTeamListItem item) {
  final start = DateTime.tryParse(item.matchStartTime);
  final end = DateTime.tryParse(item.matchEndTime);
  if (start == null && end == null) {
    return item.scheduleTime.isEmpty ? '时间待定' : 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')}';
}
