import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.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/core/cache/app_storage.dart';
import 'package:recording_tool/core/cache/storage_keys.dart';
import 'package:recording_tool/features/auth/pages/page_auth.dart';
import 'package:recording_tool/features/auth/view_model_auth/view_model_auth.dart';
import 'package:recording_tool/features/competition_teams/pages/page_competition_team_list.dart';
import 'package:recording_tool/features/events/model/model_event_info.dart';
import 'package:recording_tool/features/events/pages/page_event_info.dart';
import 'package:recording_tool/features/events/view_model/view_model_event_info.dart';
import 'package:recording_tool/features/recording/model/model_recording_context.dart';
import 'package:recording_tool/shared/widgets/app_bar.dart';
import 'package:recording_tool/shared/widgets/app_button.dart';
import 'package:recording_tool/shared/widgets/app_qr_scanner_dialog.dart';
import 'package:recording_tool/shared/widgets/app_toast.dart';

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

  static const mockRtmpUrl =
      'rtmp://192.168.1.245:19090/蔡依婷vs夏志豪_空中格斗赛_高中组/蔡依婷vs夏志豪_空中格斗赛_高中组';

  static const mockRecordingContext = RecordingContext(
    eventTitle: '全国青少年无人机大赛',
    matchName: '空中格斗赛',
    group: '高中组',
    venue: '场地 1',
    time: '7月1日 12:00-15:00',
    playerName: '蔡依婷vs夏志豪',
    playerPhone: '',
  );

  @override
  ConsumerState<ScanQrCodePage> createState() => _AuthPageWidgetState();
}

class _AuthPageWidgetState extends ConsumerState<ScanQrCodePage> {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      final token = AppStorage.getString(StorageKeys.authToken);
      if (token?.isNotEmpty ?? false) {
        final success = await ref
            .read(authProvider.notifier)
            .parseTokenSetState(token!);
        if (!success) {
          AppToast.show('请重新鉴权');
          AppNavigator.pushAndRemoveUntil(const AuthPageWidget());
          return;
        }
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return PopScope(
      canPop: true,
      onPopInvokedWithResult: (didPop, result) async {
        if (!didPop) return;
        await ref.read(authProvider.notifier).clearAuth();
      },
      child: Scaffold(
        appBar: myAppBar(context: context, title: '扫码'),
        body: Center(
          child: Column(
            children: [
              SizedBox(height: 100.h),
              Text(
                '裁判工作台',
                style: TextStyle(fontSize: 30, color: Colors.black),
              ),
              SizedBox(height: 100.h),
              Text(
                '扫描选手参赛凭证进行执裁',
                style: TextStyle(fontSize: 30, color: Colors.black),
              ),
              SizedBox(height: 20.h),

              Consumer(
                builder: (context, ref, child) {
                  return SizedBox(
                    width: 280.w,
                    height: 80.h,
                    child: AppButton(
                      label: '查看录像',
                      onPressed: () async {
                        final data = ref.watch(
                          authProvider.select((state) => state.jwtDecodedData),
                        );
                        if (data == null) return;
                        debugPrint('赛事名字： ${data.eventName}');
                        final eventName = data.eventName ?? '';
                        await ref
                            .read(authProvider.notifier)
                            .getRecordList(eventName);
                      },
                      variant: AppButtonVariant.secondary,
                    ),
                  );
                },
              ),
              SizedBox(height: 16.h),

              Consumer(
                builder: (context, ref, child) {
                  return SizedBox(
                    width: 280.w,
                    height: 80.h,
                    child: AppButton(
                      label: '参赛队伍',
                      onPressed: () async {
                        await AppNavigator.push(
                          const CompetitionTeamListPage(),
                          context: context,
                        );
                      },
                      variant: AppButtonVariant.secondary,
                    ),
                  );
                },
              ),
              SizedBox(height: 16.h),
              SizedBox(
                width: 280.w,
                height: 80.h,
                child: AppButton(
                  label: '扫码',
                  onPressed: () async {
                    final String? playerId = await AppQrScannerDialog.show(
                      context,
                    );
                    if (playerId == null || playerId.isEmpty) {
                      AppToast.show('查询选手信息失败');
                      return;
                    }
                    EasyLoading.show(status: '查询选手信息...');
                    try {
                      final success = await ref
                          .read(eventInfoProvider.notifier)
                          .loadRegistrationList(
                            request: PlayerRegistrationListReq(
                              userId: playerId,
                            ),
                          );
                      EasyLoading.dismiss();
                      if (!success) {
                        AppToast.show('查询选手信息失败');
                        return;
                      }
                      if (!mounted) return;

                      AppNavigator.push(EventInfoPage(playerId: playerId));
                    } catch (error) {
                      AppToast.show('查询选手信息失败');
                      EasyLoading.dismiss();
                    }
                  },
                  variant: AppButtonVariant.secondary,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
