import 'package:flutter/material.dart';
import 'package:flutter/services.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/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/scan_qrcode/pages/page_record_list.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});

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

class _ScanQrCodePageState 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) {
    final eventName = ref.watch(
      authProvider.select(
        (state) => state.jwtDecodedData?.eventName?.trim() ?? '',
      ),
    );

    return PopScope(
      canPop: true,
      onPopInvokedWithResult: (didPop, result) async {
        if (!didPop) return;
        await ref.read(authProvider.notifier).clearAuth();
      },
      child: AnnotatedRegion<SystemUiOverlayStyle>(
        value: SystemUiOverlayStyle.dark.copyWith(
          statusBarColor: Colors.transparent,
          systemNavigationBarColor: Colors.white,
        ),
        child: Scaffold(
          backgroundColor: Colors.white,
          body: Stack(
            children: [
              Positioned(
                top: 0,
                left: 0,
                right: 0,
                child: Image.asset(
                  _ScanAssets.pageBg,
                  width: double.infinity,
                  fit: BoxFit.fitWidth,
                ),
              ),
              SafeArea(
                child: Padding(
                  padding: EdgeInsets.fromLTRB(16.w, 12.h, 16.w, 32.h),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      const _BrandHeader(),
                      SizedBox(height: 26.h),
                      Text(
                        eventName.isEmpty ? '赛事信息' : eventName,
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                          color: const Color(0xFF3C3F44),
                          fontSize: 24.sp,
                          fontWeight: FontWeight.w700,
                          height: 1.25,
                        ),
                      ),
                      const Spacer(flex: 134),
                      Center(
                        child: GestureDetector(
                          behavior: HitTestBehavior.opaque,
                          onTap: _handleScan,
                          child: Image.asset(
                            _ScanAssets.scanQrcode,
                            width: 166.w,
                            height: 165.w,
                            fit: BoxFit.contain,
                          ),
                        ),
                      ),
                      SizedBox(height: 28.h),
                      Center(
                        child: Text(
                          '扫描选手参赛凭证进行执裁',
                          style: TextStyle(
                            color: const Color(0xFFABAFB6),
                            fontSize: 16.sp,
                            fontWeight: FontWeight.w400,
                            height: 1.2,
                          ),
                        ),
                      ),
                      const Spacer(flex: 211),
                      Row(
                        children: [
                          Expanded(
                            child: _BottomOutlineButton(
                              label: '查看录像',
                              onPressed: _handleViewRecords,
                            ),
                          ),
                          SizedBox(width: 12.w),
                          Expanded(
                            child: _BottomOutlineButton(
                              label: '参赛队伍',
                              onPressed: () async {
                                await AppNavigator.push(
                                  const CompetitionTeamListPage(),
                                  context: context,
                                );
                              },
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Future<void> _handleScan() 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) {
      EasyLoading.dismiss();
      AppToast.show('查询选手信息失败');
    }
  }

  Future<void> _handleViewRecords() async {
    final eventName = ref.read(authProvider).jwtDecodedData?.eventName ?? '';
    if (eventName.trim().isEmpty) {
      AppToast.show('暂无赛事信息');
      return;
    }

    EasyLoading.show(status: '查询录像...');
    try {
      final success = await ref
          .read(authProvider.notifier)
          .getRecordList(eventName);
      EasyLoading.dismiss();
      if (!success) {
        AppToast.show('暂无录像');
        return;
      }
      if (!mounted) return;

      final items = ref.read(authProvider).recordList ?? const [];
      AppNavigator.push(
        RecordListPage(breadcrumbs: [eventName.trim()], items: items),
        context: context,
      );
    } catch (error) {
      EasyLoading.dismiss();
      AppToast.show('查询录像失败');
    }
  }
}

class _BrandHeader extends StatelessWidget {
  const _BrandHeader();

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Expanded(
          child: Row(
            children: [
              ClipRRect(
                borderRadius: BorderRadius.circular(17.r),
                child: Image.asset(
                  _ScanAssets.appIcon,
                  width: 34.w,
                  height: 34.w,
                  fit: BoxFit.cover,
                ),
              ),
              // SizedBox(width: .w),
              Image.asset(
                _ScanAssets.appNameText,
                width: 117.w,
                height: 29.w,
                fit: BoxFit.contain,
              ),
            ],
          ),
        ),
        GestureDetector(
          onTap: () {
            AppNavigator.pop();
          },
          child: Row(
            children: [
              Icon(
                Icons.chevron_left_rounded,
                color: Colors.black,
                size: 28.sp,
              ),
              Text(
                '返回',
                style: TextStyle(
                  // color: const Color(0xFF53A7F3),
                  color: Colors.black,
                  fontSize: 14.sp,
                  fontWeight: FontWeight.w400,
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }
}

class _BottomOutlineButton extends StatelessWidget {
  const _BottomOutlineButton({required this.label, required this.onPressed});

  final String label;
  final VoidCallback onPressed;

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: 38.h,
      child: Material(
        color: Colors.white.withValues(alpha: 0.08),
        shape: StadiumBorder(
          side: BorderSide(color: const Color(0xFF9CCEFF), width: 1.r),
        ),
        child: InkWell(
          onTap: onPressed,
          customBorder: const StadiumBorder(),
          child: Center(
            child: Text(
              label,
              style: TextStyle(
                color: const Color(0xFF53A7F3),
                fontSize: 14.sp,
                fontWeight: FontWeight.w500,
                height: 1.2,
              ),
            ),
          ),
        ),
      ),
    );
  }
}

class _ScanAssets {
  const _ScanAssets._();

  static const pageBg = 'assets/images/image_page_bg.png';
  static const appIcon = 'assets/images/image_app_icon.png';
  static const appNameText = 'assets/images/image_app_name_text.png';
  static const scanQrcode = 'assets/images/image_scan_qrcode.png';
}
