import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import 'package:url_launcher/url_launcher.dart';
import 'kyc_entry_page.dart';

/// KYC 层级2: 实人认证页面 (人脸活体检测)
class KycFacePage extends ConsumerStatefulWidget {
  const KycFacePage({super.key});

  @override
  ConsumerState<KycFacePage> createState() => _KycFacePageState();
}

class _KycFacePageState extends ConsumerState<KycFacePage> {
  bool _isInitializing = false;
  bool _isQuerying = false;
  String? _errorMessage;
  String? _certifyId;
  String? _certifyUrl;

  Timer? _queryTimer;
  int _queryCount = 0;
  static const int _maxQueryCount = 30; // 最多查询30次 (1分钟)

  @override
  void dispose() {
    _queryTimer?.cancel();
    super.dispose();
  }

  /// 初始化人脸认证
  Future<void> _initFaceVerification() async {
    setState(() {
      _isInitializing = true;
      _errorMessage = null;
    });

    try {
      final kycService = ref.read(kycServiceProvider);
      final result = await kycService.initFaceVerification();

      if (!mounted) return;

      if (result.success && result.certifyUrl != null) {
        setState(() {
          _certifyId = result.certifyId;
          _certifyUrl = result.certifyUrl;
        });

        // 打开认证URL
        await _openCertifyUrl(result.certifyUrl!);

        // 开始轮询查询结果
        _startQueryingResult();
      } else {
        setState(() {
          _errorMessage = '初始化人脸认证失败，请稍后重试';
        });
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _errorMessage = e.toString().replaceAll('Exception: ', '');
        });
      }
    } finally {
      if (mounted) {
        setState(() {
          _isInitializing = false;
        });
      }
    }
  }

  /// 打开认证URL
  Future<void> _openCertifyUrl(String url) async {
    final uri = Uri.parse(url);
    if (await canLaunchUrl(uri)) {
      await launchUrl(uri, mode: LaunchMode.externalApplication);
    } else {
      setState(() {
        _errorMessage = '无法打开认证页面';
      });
    }
  }

  /// 开始轮询查询结果
  void _startQueryingResult() {
    _queryCount = 0;
    _queryTimer?.cancel();
    _queryTimer = Timer.periodic(const Duration(seconds: 2), (timer) {
      _queryResult();
    });
  }

  /// 查询认证结果
  Future<void> _queryResult() async {
    if (_certifyId == null || _isQuerying) return;

    _queryCount++;
    if (_queryCount > _maxQueryCount) {
      _queryTimer?.cancel();
      setState(() {
        _errorMessage = '认证超时，请重新开始';
        _certifyId = null;
        _certifyUrl = null;
      });
      return;
    }

    setState(() {
      _isQuerying = true;
    });

    try {
      final kycService = ref.read(kycServiceProvider);
      final result = await kycService.queryFaceVerification(_certifyId!);

      if (!mounted) return;

      if (result.passed) {
        _queryTimer?.cancel();
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('实人认证成功', style: TextStyle(fontSize: 14.sp)),
            backgroundColor: const Color(0xFF2E7D32),
            behavior: SnackBarBehavior.floating,
          ),
        );
        ref.invalidate(kycStatusProvider);
        context.pop(true);
      } else if (result.status == 'FAILED') {
        _queryTimer?.cancel();
        setState(() {
          _errorMessage = result.errorMessage ?? '认证失败，请重新尝试';
          _certifyId = null;
          _certifyUrl = null;
        });
      }
      // PENDING 状态继续轮询
    } catch (e) {
      // 查询失败继续轮询，不中断
    } finally {
      if (mounted) {
        setState(() {
          _isQuerying = false;
        });
      }
    }
  }

  /// 手动查询结果
  Future<void> _manualQueryResult() async {
    if (_certifyId == null) return;

    setState(() {
      _isQuerying = true;
      _errorMessage = null;
    });

    try {
      final kycService = ref.read(kycServiceProvider);
      final result = await kycService.queryFaceVerification(_certifyId!);

      if (!mounted) return;

      if (result.passed) {
        _queryTimer?.cancel();
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('实人认证成功', style: TextStyle(fontSize: 14.sp)),
            backgroundColor: const Color(0xFF2E7D32),
            behavior: SnackBarBehavior.floating,
          ),
        );
        ref.invalidate(kycStatusProvider);
        context.pop(true);
      } else if (result.status == 'FAILED') {
        setState(() {
          _errorMessage = result.errorMessage ?? '认证失败，请重新尝试';
          _certifyId = null;
          _certifyUrl = null;
        });
      } else {
        setState(() {
          _errorMessage = '认证尚未完成，请完成人脸识别后再试';
        });
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _errorMessage = e.toString().replaceAll('Exception: ', '');
        });
      }
    } finally {
      if (mounted) {
        setState(() {
          _isQuerying = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios, color: Color(0xFF333333)),
          onPressed: () {
            _queryTimer?.cancel();
            context.pop();
          },
        ),
        title: Text(
          '实人认证',
          style: TextStyle(
            fontSize: 18.sp,
            fontWeight: FontWeight.w600,
            color: const Color(0xFF333333),
          ),
        ),
        centerTitle: true,
      ),
      body: SafeArea(
        child: SingleChildScrollView(
          padding: EdgeInsets.symmetric(horizontal: 24.w),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              SizedBox(height: 24.h),

              // 步骤指示
              _buildStepIndicator(),
              SizedBox(height: 40.h),

              // 人脸图标
              Container(
                width: 120.w,
                height: 120.w,
                decoration: BoxDecoration(
                  color: const Color(0xFFF5F5F5),
                  shape: BoxShape.circle,
                ),
                child: Icon(
                  Icons.face,
                  size: 60.sp,
                  color: const Color(0xFF2E7D32),
                ),
              ),
              SizedBox(height: 24.h),

              Text(
                '人脸活体检测',
                style: TextStyle(
                  fontSize: 24.sp,
                  fontWeight: FontWeight.w700,
                  color: const Color(0xFF333333),
                ),
              ),
              SizedBox(height: 8.h),
              Text(
                '请确保光线充足，面部无遮挡',
                style: TextStyle(
                  fontSize: 14.sp,
                  color: const Color(0xFF999999),
                ),
              ),
              SizedBox(height: 32.h),

              // 说明步骤
              _buildInstructionCard(),
              SizedBox(height: 24.h),

              // 错误信息
              if (_errorMessage != null) ...[
                Container(
                  padding: EdgeInsets.all(12.w),
                  decoration: BoxDecoration(
                    color: Colors.red.withValues(alpha: 0.1),
                    borderRadius: BorderRadius.circular(8.r),
                  ),
                  child: Row(
                    children: [
                      Icon(Icons.error_outline, color: Colors.red, size: 20.sp),
                      SizedBox(width: 8.w),
                      Expanded(
                        child: Text(
                          _errorMessage!,
                          style: TextStyle(fontSize: 14.sp, color: Colors.red),
                        ),
                      ),
                    ],
                  ),
                ),
                SizedBox(height: 24.h),
              ],

              // 等待验证状态
              if (_certifyId != null && _certifyUrl != null) ...[
                Container(
                  padding: EdgeInsets.all(16.w),
                  decoration: BoxDecoration(
                    color: const Color(0xFFE3F2FD),
                    borderRadius: BorderRadius.circular(8.r),
                  ),
                  child: Column(
                    children: [
                      if (_isQuerying)
                        SizedBox(
                          width: 24.sp,
                          height: 24.sp,
                          child: const CircularProgressIndicator(strokeWidth: 2),
                        )
                      else
                        Icon(Icons.hourglass_empty, size: 24.sp, color: const Color(0xFF1976D2)),
                      SizedBox(height: 8.h),
                      Text(
                        '等待人脸验证结果...',
                        style: TextStyle(
                          fontSize: 14.sp,
                          color: const Color(0xFF1976D2),
                        ),
                      ),
                      SizedBox(height: 4.h),
                      Text(
                        '请在浏览器中完成人脸识别',
                        style: TextStyle(
                          fontSize: 12.sp,
                          color: const Color(0xFF666666),
                        ),
                      ),
                    ],
                  ),
                ),
                SizedBox(height: 16.h),

                // 重新打开链接按钮
                TextButton(
                  onPressed: () => _openCertifyUrl(_certifyUrl!),
                  child: Text(
                    '重新打开认证页面',
                    style: TextStyle(
                      fontSize: 14.sp,
                      color: const Color(0xFF2E7D32),
                    ),
                  ),
                ),
                SizedBox(height: 8.h),

                // 手动查询按钮
                GestureDetector(
                  onTap: _isQuerying ? null : _manualQueryResult,
                  child: Container(
                    width: double.infinity,
                    padding: EdgeInsets.symmetric(vertical: 16.h),
                    decoration: BoxDecoration(
                      color: _isQuerying
                          ? const Color(0xFFCCCCCC)
                          : const Color(0xFF2E7D32),
                      borderRadius: BorderRadius.circular(12.r),
                    ),
                    child: Text(
                      '我已完成认证',
                      style: TextStyle(
                        fontSize: 16.sp,
                        fontWeight: FontWeight.w600,
                        color: Colors.white,
                      ),
                      textAlign: TextAlign.center,
                    ),
                  ),
                ),
              ] else ...[
                // 开始验证按钮
                GestureDetector(
                  onTap: _isInitializing ? null : _initFaceVerification,
                  child: Container(
                    width: double.infinity,
                    padding: EdgeInsets.symmetric(vertical: 16.h),
                    decoration: BoxDecoration(
                      color: _isInitializing
                          ? const Color(0xFFCCCCCC)
                          : const Color(0xFF2E7D32),
                      borderRadius: BorderRadius.circular(12.r),
                    ),
                    child: _isInitializing
                        ? Center(
                            child: SizedBox(
                              width: 24.sp,
                              height: 24.sp,
                              child: const CircularProgressIndicator(
                                strokeWidth: 2,
                                valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                              ),
                            ),
                          )
                        : Text(
                            '开始人脸认证',
                            style: TextStyle(
                              fontSize: 16.sp,
                              fontWeight: FontWeight.w600,
                              color: Colors.white,
                            ),
                            textAlign: TextAlign.center,
                          ),
                  ),
                ),
              ],
              SizedBox(height: 32.h),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildStepIndicator() {
    return Row(
      children: [
        _buildStepDot(1, false, true),
        Expanded(child: _buildStepLine(true)),
        _buildStepDot(2, true, false),
        Expanded(child: _buildStepLine(false)),
        _buildStepDot(3, false, false),
      ],
    );
  }

  Widget _buildStepDot(int step, bool isActive, bool isCompleted) {
    return Container(
      width: 28.w,
      height: 28.w,
      decoration: BoxDecoration(
        shape: BoxShape.circle,
        color: isCompleted
            ? const Color(0xFF2E7D32)
            : isActive
                ? const Color(0xFF2E7D32)
                : const Color(0xFFE0E0E0),
      ),
      child: Center(
        child: isCompleted
            ? Icon(Icons.check, size: 16.sp, color: Colors.white)
            : Text(
                '$step',
                style: TextStyle(
                  fontSize: 12.sp,
                  fontWeight: FontWeight.w600,
                  color: isActive ? Colors.white : const Color(0xFF999999),
                ),
              ),
      ),
    );
  }

  Widget _buildStepLine(bool isCompleted) {
    return Container(
      height: 2.h,
      color: isCompleted ? const Color(0xFF2E7D32) : const Color(0xFFE0E0E0),
    );
  }

  Widget _buildInstructionCard() {
    return Container(
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: const Color(0xFFF5F5F5),
        borderRadius: BorderRadius.circular(12.r),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '认证步骤',
            style: TextStyle(
              fontSize: 14.sp,
              fontWeight: FontWeight.w600,
              color: const Color(0xFF333333),
            ),
          ),
          SizedBox(height: 12.h),
          _buildInstructionItem('1', '点击"开始人脸认证"按钮'),
          SizedBox(height: 8.h),
          _buildInstructionItem('2', '在弹出的页面中完成人脸识别'),
          SizedBox(height: 8.h),
          _buildInstructionItem('3', '返回APP等待验证结果'),
        ],
      ),
    );
  }

  Widget _buildInstructionItem(String number, String text) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          width: 20.w,
          height: 20.w,
          decoration: BoxDecoration(
            color: const Color(0xFF2E7D32),
            shape: BoxShape.circle,
          ),
          child: Center(
            child: Text(
              number,
              style: TextStyle(
                fontSize: 11.sp,
                fontWeight: FontWeight.w600,
                color: Colors.white,
              ),
            ),
          ),
        ),
        SizedBox(width: 8.w),
        Expanded(
          child: Text(
            text,
            style: TextStyle(
              fontSize: 13.sp,
              color: const Color(0xFF666666),
            ),
          ),
        ),
      ],
    );
  }
}
