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 '../../../../core/di/injection_container.dart';
import '../../../../routes/route_paths.dart';
import '../../data/kyc_service.dart';

/// KYC Provider
final kycServiceProvider = Provider<KycService>((ref) {
  final apiClient = ref.read(apiClientProvider);
  return KycService(apiClient);
});

/// KYC 状态 Provider
final kycStatusProvider = FutureProvider.autoDispose<KycStatusResponse>((ref) async {
  final kycService = ref.read(kycServiceProvider);
  final status = await kycService.getKycStatus();
  debugPrint('[KycEntryPage] KYC状态: phoneVerified=${status.phoneVerified}, kycStatus=${status.kycStatus}');
  return status;
});

/// KYC 入口页面 - 支持三层认证
/// 层级1: 实名认证 (二要素: 姓名+身份证号)
/// 层级2: 实人认证 (人脸活体检测)
/// 层级3: KYC (证件照上传验证)
class KycEntryPage extends ConsumerWidget {
  /// 从认种流程跳转时带的订单号，KYC成功后需要跳转到合同签署
  final String? orderNo;

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

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final kycStatusAsync = ref.watch(kycStatusProvider);

    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: kycStatusAsync.when(
        loading: () => const Center(child: CircularProgressIndicator()),
        error: (error, _) => Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(Icons.error_outline, size: 48.sp, color: Colors.red),
              SizedBox(height: 16.h),
              Text('加载失败: $error', style: TextStyle(fontSize: 14.sp)),
              SizedBox(height: 16.h),
              ElevatedButton(
                onPressed: () => ref.invalidate(kycStatusProvider),
                child: const Text('重试'),
              ),
            ],
          ),
        ),
        data: (status) => _buildContent(context, ref, status),
      ),
    );
  }

  Widget _buildContent(BuildContext context, WidgetRef ref, KycStatusResponse status) {
    return SingleChildScrollView(
      padding: EdgeInsets.all(16.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 状态卡片
          _buildStatusCard(status),
          SizedBox(height: 24.h),

          // 认证步骤
          Text(
            '认证步骤',
            style: TextStyle(
              fontSize: 16.sp,
              fontWeight: FontWeight.w600,
              color: const Color(0xFF333333),
            ),
          ),
          SizedBox(height: 12.h),

          // 层级1: 实名认证 (仅当开启时显示)
          if (status.config.level1Enabled)
            _buildLevel1Card(context, ref, status),

          // 层级2: 实人认证 (仅当开启时显示)
          if (status.config.level2Enabled) ...[
            SizedBox(height: 12.h),
            _buildLevel2Card(context, ref, status),
          ],

          // 层级3: KYC证件照 (仅当开启时显示)
          if (status.config.level3Enabled) ...[
            SizedBox(height: 12.h),
            _buildLevel3Card(context, ref, status),
          ],

          SizedBox(height: 24.h),

          // 其他操作
          Text(
            '其他操作',
            style: TextStyle(
              fontSize: 16.sp,
              fontWeight: FontWeight.w600,
              color: const Color(0xFF333333),
            ),
          ),
          SizedBox(height: 12.h),
          _buildActionCard(
            context: context,
            icon: Icons.phone_android,
            title: '验证/更换手机号',
            description: status.phoneVerified
                ? (status.phoneNumber ?? '更换绑定的手机号')
                : '手机号未验证，点击验证',
            onTap: () => context.push(RoutePaths.changePhone),
          ),

          SizedBox(height: 24.h),

          // 树服务
          Text(
            '树服务',
            style: TextStyle(
              fontSize: 16.sp,
              fontWeight: FontWeight.w600,
              color: const Color(0xFF333333),
            ),
          ),
          SizedBox(height: 12.h),
          _buildActionCard(
            context: context,
            icon: Icons.swap_horiz,
            title: '发起转让',
            description: '向其他用户发起树转让',
            onTap: () => context.push(RoutePaths.transferInitiate),
          ),
          SizedBox(height: 8.h),
          _buildActionCard(
            context: context,
            icon: Icons.receipt_long_outlined,
            title: '转让记录',
            description: '查看树转让历史记录',
            onTap: () => context.push(RoutePaths.transferList),
          ),

          SizedBox(height: 24.h),

          // 说明文字
          _buildInfoCard(),
        ],
      ),
    );
  }

  /// 构建状态卡片
  Widget _buildStatusCard(KycStatusResponse status) {
    Color backgroundColor;
    Color textColor;
    IconData icon;
    String statusText;
    String? subText;

    if (status.isCompleted) {
      backgroundColor = const Color(0xFFE8F5E9);
      textColor = const Color(0xFF2E7D32);
      icon = Icons.check_circle;
      statusText = '认证完成';
      subText = _getCompletedLevelsText(status);
    } else if (status.statusType == KycStatusType.rejected) {
      backgroundColor = const Color(0xFFFFEBEE);
      textColor = const Color(0xFFC62828);
      icon = Icons.cancel;
      statusText = '认证被拒绝';
      subText = status.rejectedReason;
    } else {
      backgroundColor = const Color(0xFFFFF3E0);
      textColor = const Color(0xFFE65100);
      icon = Icons.pending;
      statusText = '待完成认证';
      subText = _getPendingStepsText(status);
    }

    return Container(
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: backgroundColor,
        borderRadius: BorderRadius.circular(12.r),
      ),
      child: Row(
        children: [
          Icon(icon, size: 32.sp, color: textColor),
          SizedBox(width: 12.w),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  statusText,
                  style: TextStyle(
                    fontSize: 16.sp,
                    fontWeight: FontWeight.w600,
                    color: textColor,
                  ),
                ),
                if (subText != null) ...[
                  SizedBox(height: 4.h),
                  Text(
                    subText,
                    style: TextStyle(
                      fontSize: 12.sp,
                      color: textColor.withValues(alpha: 0.8),
                    ),
                  ),
                ],
              ],
            ),
          ),
        ],
      ),
    );
  }

  String _getCompletedLevelsText(KycStatusResponse status) {
    final List<String> completed = [];
    if (status.level1.verified) completed.add('实名认证');
    if (status.level2.verified) completed.add('实人认证');
    if (status.level3.verified) completed.add('KYC认证');
    return '已完成: ${completed.join('、')}';
  }

  String _getPendingStepsText(KycStatusResponse status) {
    final List<String> pending = [];
    if (status.config.level1Enabled && !status.level1.verified) pending.add('实名认证');
    if (status.config.level2Enabled && !status.level2.verified) pending.add('实人认证');
    if (status.config.level3Enabled && !status.level3.verified) pending.add('KYC认证');
    return '待完成: ${pending.join('、')}';
  }

  /// 层级1: 实名认证卡片
  Widget _buildLevel1Card(BuildContext context, WidgetRef ref, KycStatusResponse status) {
    final level1 = status.level1;
    final isCompleted = level1.verified;
    // 必须先验证手机号才能进行实名认证
    final needsPhoneVerification = !status.phoneVerified;
    final isEnabled = !isCompleted;

    String description;
    if (isCompleted) {
      description = '${level1.realName ?? ''} (${_maskIdCard(level1.idCardNumber)})';
    } else if (needsPhoneVerification) {
      description = '请先验证手机号';
    } else {
      description = '验证姓名和身份证号';
    }

    return _buildStepCard(
      context: context,
      ref: ref,
      stepNumber: 1,
      title: '实名认证',
      subtitle: '二要素验证',
      description: description,
      isCompleted: isCompleted,
      isEnabled: isEnabled,
      isLocked: needsPhoneVerification && !isCompleted,
      onTap: () {
        if (isEnabled) {
          if (needsPhoneVerification) {
            // 手机号未验证，跳转到验证手机号页面
            _showPhoneVerificationRequiredDialog(context);
          } else {
            // 传递 orderNo 到 KycIdPage
            context.push(RoutePaths.kycId, extra: orderNo);
          }
        }
      },
    );
  }

  /// 显示需要先验证手机号的弹窗
  void _showPhoneVerificationRequiredDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (ctx) => AlertDialog(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(16.r),
        ),
        title: Row(
          children: [
            Icon(Icons.phone_android, color: const Color(0xFF2E7D32), size: 24.sp),
            SizedBox(width: 8.w),
            Text(
              '请先验证手机号',
              style: TextStyle(
                fontSize: 18.sp,
                fontWeight: FontWeight.w600,
              ),
            ),
          ],
        ),
        content: Text(
          '进行实名认证前，需要先验证您的手机号码。',
          style: TextStyle(
            fontSize: 14.sp,
            color: const Color(0xFF666666),
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(ctx).pop(),
            child: Text(
              '稍后验证',
              style: TextStyle(
                fontSize: 14.sp,
                color: const Color(0xFF999999),
              ),
            ),
          ),
          ElevatedButton(
            onPressed: () {
              Navigator.of(ctx).pop();
              context.push(RoutePaths.changePhone);
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: const Color(0xFF2E7D32),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(8.r),
              ),
            ),
            child: Text(
              '去验证',
              style: TextStyle(
                fontSize: 14.sp,
                color: Colors.white,
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 层级2: 实人认证卡片
  Widget _buildLevel2Card(BuildContext context, WidgetRef ref, KycStatusResponse status) {
    final level2 = status.level2;
    final isCompleted = level2.verified;
    // 必须先完成层级1才能进行层级2
    final canStart = level2.canStart && status.level1.verified;
    final isEnabled = !isCompleted && canStart;

    String description;
    if (isCompleted) {
      description = '人脸验证已通过';
    } else if (!status.level1.verified) {
      description = '请先完成实名认证';
    } else {
      description = '进行人脸活体检测';
    }

    return _buildStepCard(
      context: context,
      ref: ref,
      stepNumber: 2,
      title: '实人认证',
      subtitle: '人脸活体检测',
      description: description,
      isCompleted: isCompleted,
      isEnabled: isEnabled,
      isLocked: !status.level1.verified,
      onTap: () {
        if (isEnabled) {
          context.push(RoutePaths.kycFace);
        }
      },
    );
  }

  /// 层级3: KYC认证卡片
  Widget _buildLevel3Card(BuildContext context, WidgetRef ref, KycStatusResponse status) {
    final level3 = status.level3;
    final isCompleted = level3.verified;
    // 必须先完成层级1和层级2(如果开启)才能进行层级3
    final needLevel2 = status.config.level2Enabled;
    final level2Done = !needLevel2 || status.level2.verified;
    final canStart = level3.canStart && status.level1.verified && level2Done;
    final isEnabled = !isCompleted && canStart;

    String description;
    if (isCompleted) {
      description = '证件照验证已通过';
    } else if (!status.level1.verified) {
      description = '请先完成实名认证';
    } else if (needLevel2 && !status.level2.verified) {
      description = '请先完成实人认证';
    } else {
      description = '上传身份证正反面照片';
    }

    return _buildStepCard(
      context: context,
      ref: ref,
      stepNumber: 3,
      title: 'KYC认证',
      subtitle: '证件照验证',
      description: description,
      isCompleted: isCompleted,
      isEnabled: isEnabled,
      isLocked: !status.level1.verified || (needLevel2 && !status.level2.verified),
      onTap: () {
        if (isEnabled) {
          context.push(RoutePaths.kycIdCard);
        }
      },
    );
  }

  /// 构建步骤卡片
  Widget _buildStepCard({
    required BuildContext context,
    required WidgetRef ref,
    required int stepNumber,
    required String title,
    required String subtitle,
    required String description,
    required bool isCompleted,
    required bool isEnabled,
    bool isLocked = false,
    bool isRejected = false,
    String? rejectedReason,
    required VoidCallback onTap,
  }) {
    return GestureDetector(
      onTap: isEnabled ? onTap : null,
      child: Container(
        padding: EdgeInsets.all(16.w),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(12.r),
          border: Border.all(
            color: isCompleted
                ? const Color(0xFF2E7D32)
                : isRejected
                    ? Colors.red
                    : const Color(0xFFE0E0E0),
          ),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withValues(alpha: 0.05),
              blurRadius: 4,
              offset: const Offset(0, 2),
            ),
          ],
        ),
        child: Row(
          children: [
            // 步骤圆圈
            Container(
              width: 40.w,
              height: 40.w,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                color: isCompleted
                    ? const Color(0xFF2E7D32)
                    : isRejected
                        ? Colors.red
                        : isLocked
                            ? const Color(0xFFBDBDBD)
                            : const Color(0xFFE0E0E0),
              ),
              child: Center(
                child: isCompleted
                    ? Icon(Icons.check, size: 20.sp, color: Colors.white)
                    : isRejected
                        ? Icon(Icons.close, size: 20.sp, color: Colors.white)
                        : isLocked
                            ? Icon(Icons.lock, size: 18.sp, color: Colors.white)
                            : Text(
                                '$stepNumber',
                                style: TextStyle(
                                  fontSize: 16.sp,
                                  fontWeight: FontWeight.w600,
                                  color: Colors.white,
                                ),
                              ),
              ),
            ),
            SizedBox(width: 12.w),

            // 内容
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      Text(
                        title,
                        style: TextStyle(
                          fontSize: 15.sp,
                          fontWeight: FontWeight.w600,
                          color: isLocked
                              ? const Color(0xFF999999)
                              : const Color(0xFF333333),
                        ),
                      ),
                      SizedBox(width: 8.w),
                      Container(
                        padding: EdgeInsets.symmetric(horizontal: 6.w, vertical: 2.h),
                        decoration: BoxDecoration(
                          color: isCompleted
                              ? const Color(0xFFE8F5E9)
                              : const Color(0xFFF5F5F5),
                          borderRadius: BorderRadius.circular(4.r),
                        ),
                        child: Text(
                          subtitle,
                          style: TextStyle(
                            fontSize: 10.sp,
                            color: isCompleted
                                ? const Color(0xFF2E7D32)
                                : const Color(0xFF666666),
                          ),
                        ),
                      ),
                    ],
                  ),
                  SizedBox(height: 4.h),
                  Text(
                    isRejected && rejectedReason != null ? rejectedReason : description,
                    style: TextStyle(
                      fontSize: 12.sp,
                      color: isRejected
                          ? Colors.red
                          : isLocked
                              ? const Color(0xFFBDBDBD)
                              : const Color(0xFF999999),
                    ),
                  ),
                ],
              ),
            ),

            // 箭头或状态图标
            if (isEnabled)
              Icon(
                Icons.chevron_right,
                size: 24.sp,
                color: const Color(0xFF999999),
              )
            else if (isCompleted)
              Icon(
                Icons.verified,
                size: 24.sp,
                color: const Color(0xFF2E7D32),
              ),
          ],
        ),
      ),
    );
  }

  /// 构建操作卡片
  Widget _buildActionCard({
    required BuildContext context,
    required IconData icon,
    required String title,
    required String description,
    required VoidCallback onTap,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        padding: EdgeInsets.all(16.w),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(12.r),
          border: Border.all(color: const Color(0xFFE0E0E0)),
        ),
        child: Row(
          children: [
            Container(
              width: 40.w,
              height: 40.w,
              decoration: BoxDecoration(
                color: const Color(0xFFF5F5F5),
                borderRadius: BorderRadius.circular(8.r),
              ),
              child: Icon(icon, size: 24.sp, color: const Color(0xFF666666)),
            ),
            SizedBox(width: 12.w),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    title,
                    style: TextStyle(
                      fontSize: 15.sp,
                      fontWeight: FontWeight.w500,
                      color: const Color(0xFF333333),
                    ),
                  ),
                  SizedBox(height: 2.h),
                  Text(
                    description,
                    style: TextStyle(
                      fontSize: 12.sp,
                      color: const Color(0xFF999999),
                    ),
                  ),
                ],
              ),
            ),
            Icon(
              Icons.chevron_right,
              size: 24.sp,
              color: const Color(0xFF999999),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建说明卡片
  Widget _buildInfoCard() {
    return Container(
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: const Color(0xFFF5F5F5),
        borderRadius: BorderRadius.circular(8.r),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Icon(Icons.info_outline, size: 16.sp, color: const Color(0xFF666666)),
              SizedBox(width: 8.w),
              Text(
                '认证说明',
                style: TextStyle(
                  fontSize: 14.sp,
                  fontWeight: FontWeight.w500,
                  color: const Color(0xFF333333),
                ),
              ),
            ],
          ),
          SizedBox(height: 8.h),
          Text(
            '• 请确保填写的信息与身份证一致\n'
            '• 实名认证: 验证您的姓名和身份证号\n'
            '• 实人认证: 通过人脸活体检测确认本人\n'
            '• KYC认证: 上传身份证正反面照片\n'
            '• 您的信息将被加密存储，不会泄露给第三方',
            style: TextStyle(
              fontSize: 12.sp,
              color: const Color(0xFF666666),
              height: 1.5,
            ),
          ),
        ],
      ),
    );
  }

  /// 脱敏身份证号
  String _maskIdCard(String? idCard) {
    if (idCard == null || idCard.isEmpty) return '';
    if (idCard.length < 8) return '****';
    return '${idCard.substring(0, 4)}****${idCard.substring(idCard.length - 4)}';
  }
}
