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 'kyc_entry_page.dart' show kycStatusProvider, kycServiceProvider;
import '../../../../routes/route_paths.dart';

/// KYC 层级1: 实名认证页面 (三要素验证: 姓名+身份证号+手机号)
class KycIdPage extends ConsumerStatefulWidget {
  /// 从认种流程跳转时带的订单号，KYC成功后需要跳转到合同签署
  final String? orderNo;

  const KycIdPage({super.key, this.orderNo});

  @override
  ConsumerState<KycIdPage> createState() => _KycIdPageState();
}

class _KycIdPageState extends ConsumerState<KycIdPage> {
  final _formKey = GlobalKey<FormState>();
  final _nameController = TextEditingController();
  final _idCardController = TextEditingController();

  bool _isSubmitting = false;
  String? _errorMessage;

  @override
  void dispose() {
    _nameController.dispose();
    _idCardController.dispose();
    super.dispose();
  }

  String? _validateName(String? value) {
    if (value == null || value.isEmpty) {
      return '请输入真实姓名';
    }
    if (value.length < 2) {
      return '姓名至少2个字符';
    }
    // 只允许中文和英文字母
    if (!RegExp(r'^[\u4e00-\u9fa5a-zA-Z·]+$').hasMatch(value)) {
      return '姓名格式不正确';
    }
    return null;
  }

  String? _validateIdCard(String? value) {
    if (value == null || value.isEmpty) {
      return '请输入身份证号';
    }
    // 18位身份证号验证
    final regex = RegExp(
      r'^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$',
    );
    if (!regex.hasMatch(value)) {
      return '身份证号格式不正确';
    }
    return null;
  }

  Future<void> _submit() async {
    if (!_formKey.currentState!.validate()) {
      return;
    }

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

    try {
      final kycService = ref.read(kycServiceProvider);
      final result = await kycService.submitRealNameVerification(
        realName: _nameController.text.trim(),
        idCardNumber: _idCardController.text.trim().toUpperCase(),
      );

      if (!mounted) return;

      if (result.success) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('实名认证成功', style: TextStyle(fontSize: 14.sp)),
            backgroundColor: const Color(0xFF2E7D32),
            behavior: SnackBarBehavior.floating,
          ),
        );
        // 刷新状态
        ref.invalidate(kycStatusProvider);

        // 如果有 orderNo，说明是从认种流程来的，跳转到合同签署页面
        if (widget.orderNo != null) {
          context.go('${RoutePaths.contractSigning}/${widget.orderNo}');
        } else {
          // 否则直接返回
          context.pop(true);
        }
      } else {
        setState(() {
          _errorMessage = result.errorMessage ?? '验证失败，请检查信息是否正确';
        });
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _errorMessage = e.toString().replaceAll('Exception: ', '');
        });
      }
    } finally {
      if (mounted) {
        setState(() {
          _isSubmitting = 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: () => context.pop(),
        ),
        title: Text(
          '实名认证',
          style: TextStyle(
            fontSize: 18.sp,
            fontWeight: FontWeight.w600,
            color: const Color(0xFF333333),
          ),
        ),
        centerTitle: true,
      ),
      body: GestureDetector(
        onTap: () => FocusScope.of(context).unfocus(),
        child: SafeArea(
          child: SingleChildScrollView(
            padding: EdgeInsets.symmetric(horizontal: 24.w),
            child: Form(
              key: _formKey,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  SizedBox(height: 24.h),

                  // 步骤指示
                  _buildStepIndicator(),
                  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),

                  // 姓名输入
                  _buildInputField(
                    label: '真实姓名',
                    hint: '请输入身份证上的姓名',
                    controller: _nameController,
                    validator: _validateName,
                    keyboardType: TextInputType.text,
                  ),
                  SizedBox(height: 16.h),

                  // 身份证号输入
                  _buildInputField(
                    label: '身份证号',
                    hint: '请输入18位身份证号',
                    controller: _idCardController,
                    validator: _validateIdCard,
                    keyboardType: TextInputType.text,
                    maxLength: 18,
                  ),

                  // 错误信息
                  if (_errorMessage != null) ...[
                    SizedBox(height: 16.h),
                    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: 32.h),

                  // 提示信息
                  Container(
                    padding: EdgeInsets.all(12.w),
                    decoration: BoxDecoration(
                      color: const Color(0xFFFFF3E0),
                      borderRadius: BorderRadius.circular(8.r),
                    ),
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Icon(
                          Icons.security,
                          size: 18.sp,
                          color: const Color(0xFFE65100),
                        ),
                        SizedBox(width: 8.w),
                        Expanded(
                          child: Text(
                            '您的身份信息（姓名+身份证号+手机号）将通过权威数据源进行三要素验证，信息将被加密存储，不会泄露给任何第三方。',
                            style: TextStyle(
                              fontSize: 12.sp,
                              color: const Color(0xFFE65100),
                              height: 1.5,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),

                  SizedBox(height: 40.h),

                  // 提交按钮
                  GestureDetector(
                    onTap: _isSubmitting ? null : _submit,
                    child: Container(
                      width: double.infinity,
                      padding: EdgeInsets.symmetric(vertical: 16.h),
                      decoration: BoxDecoration(
                        color: _isSubmitting
                            ? const Color(0xFFCCCCCC)
                            : const Color(0xFF2E7D32),
                        borderRadius: BorderRadius.circular(12.r),
                      ),
                      child: _isSubmitting
                          ? 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, true, false),
        Expanded(child: _buildStepLine(false)),
        _buildStepDot(2, false, 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 _buildInputField({
    required String label,
    required String hint,
    required TextEditingController controller,
    required String? Function(String?) validator,
    TextInputType keyboardType = TextInputType.text,
    int? maxLength,
  }) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          label,
          style: TextStyle(
            fontSize: 14.sp,
            fontWeight: FontWeight.w500,
            color: const Color(0xFF333333),
          ),
        ),
        SizedBox(height: 8.h),
        TextFormField(
          controller: controller,
          validator: validator,
          keyboardType: keyboardType,
          maxLength: maxLength,
          decoration: InputDecoration(
            hintText: hint,
            hintStyle: TextStyle(
              fontSize: 16.sp,
              color: const Color(0xFF999999),
            ),
            counterText: '',
            filled: true,
            fillColor: const Color(0xFFF5F5F5),
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(12.r),
              borderSide: BorderSide.none,
            ),
            focusedBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(12.r),
              borderSide: const BorderSide(color: Color(0xFF2E7D32), width: 2),
            ),
            errorBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(12.r),
              borderSide: const BorderSide(color: Colors.red, width: 1),
            ),
            focusedErrorBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(12.r),
              borderSide: const BorderSide(color: Colors.red, width: 2),
            ),
            contentPadding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 16.h),
          ),
          style: TextStyle(
            fontSize: 16.sp,
            color: const Color(0xFF333333),
          ),
        ),
      ],
    );
  }
}
