import 'dart:typed_data';
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:image_picker/image_picker.dart';
import 'kyc_entry_page.dart';
import '../../data/kyc_service.dart';

/// KYC 层级3: 证件照上传页面
class KycIdCardPage extends ConsumerStatefulWidget {
  const KycIdCardPage({super.key});

  @override
  ConsumerState<KycIdCardPage> createState() => _KycIdCardPageState();
}

class _KycIdCardPageState extends ConsumerState<KycIdCardPage> {
  final ImagePicker _picker = ImagePicker();

  Uint8List? _frontImage;
  Uint8List? _backImage;

  bool _isUploadingFront = false;
  bool _isUploadingBack = false;
  bool _isSubmitting = false;
  String? _errorMessage;

  // OCR 识别结果
  IdCardOcrResult? _ocrResult;

  /// 选择并上传图片
  Future<void> _pickAndUploadImage(String side) async {
    try {
      final XFile? image = await _picker.pickImage(
        source: ImageSource.camera,
        imageQuality: 80,
        maxWidth: 1920,
        maxHeight: 1080,
      );

      if (image == null) return;

      final bytes = await image.readAsBytes();
      final fileName = image.name;

      if (side == 'front') {
        setState(() {
          _frontImage = bytes;
          _isUploadingFront = true;
          _errorMessage = null;
        });
      } else {
        setState(() {
          _backImage = bytes;
          _isUploadingBack = true;
          _errorMessage = null;
        });
      }

      // 上传图片
      final kycService = ref.read(kycServiceProvider);
      final result = await kycService.uploadIdCardPhoto(
        side: side,
        imageBytes: bytes,
        fileName: fileName,
      );

      if (!mounted) return;

      if (result.success) {
        if (side == 'front' && result.ocrResult != null) {
          setState(() {
            _ocrResult = result.ocrResult;
          });
        }
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(
              '${side == 'front' ? '正面' : '反面'}照片上传成功',
              style: TextStyle(fontSize: 14.sp),
            ),
            backgroundColor: const Color(0xFF2E7D32),
            behavior: SnackBarBehavior.floating,
            duration: const Duration(seconds: 1),
          ),
        );
      } else {
        setState(() {
          _errorMessage = '照片上传失败，请重试';
          if (side == 'front') {
            _frontImage = null;
          } else {
            _backImage = null;
          }
        });
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _errorMessage = e.toString().replaceAll('Exception: ', '');
        });
      }
    } finally {
      if (mounted) {
        setState(() {
          if (side == 'front') {
            _isUploadingFront = false;
          } else {
            _isUploadingBack = false;
          }
        });
      }
    }
  }

  /// 从相册选择图片
  Future<void> _pickFromGallery(String side) async {
    try {
      final XFile? image = await _picker.pickImage(
        source: ImageSource.gallery,
        imageQuality: 80,
        maxWidth: 1920,
        maxHeight: 1080,
      );

      if (image == null) return;

      final bytes = await image.readAsBytes();
      final fileName = image.name;

      if (side == 'front') {
        setState(() {
          _frontImage = bytes;
          _isUploadingFront = true;
          _errorMessage = null;
        });
      } else {
        setState(() {
          _backImage = bytes;
          _isUploadingBack = true;
          _errorMessage = null;
        });
      }

      // 上传图片
      final kycService = ref.read(kycServiceProvider);
      final result = await kycService.uploadIdCardPhoto(
        side: side,
        imageBytes: bytes,
        fileName: fileName,
      );

      if (!mounted) return;

      if (result.success) {
        if (side == 'front' && result.ocrResult != null) {
          setState(() {
            _ocrResult = result.ocrResult;
          });
        }
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(
              '${side == 'front' ? '正面' : '反面'}照片上传成功',
              style: TextStyle(fontSize: 14.sp),
            ),
            backgroundColor: const Color(0xFF2E7D32),
            behavior: SnackBarBehavior.floating,
            duration: const Duration(seconds: 1),
          ),
        );
      } else {
        setState(() {
          _errorMessage = '照片上传失败，请重试';
          if (side == 'front') {
            _frontImage = null;
          } else {
            _backImage = null;
          }
        });
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _errorMessage = e.toString().replaceAll('Exception: ', '');
        });
      }
    } finally {
      if (mounted) {
        setState(() {
          if (side == 'front') {
            _isUploadingFront = false;
          } else {
            _isUploadingBack = false;
          }
        });
      }
    }
  }

  /// 显示图片来源选择
  void _showImageSourceDialog(String side) {
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.white,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(16.r)),
      ),
      builder: (context) => SafeArea(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            SizedBox(height: 8.h),
            Container(
              width: 40.w,
              height: 4.h,
              decoration: BoxDecoration(
                color: const Color(0xFFE0E0E0),
                borderRadius: BorderRadius.circular(2.r),
              ),
            ),
            SizedBox(height: 16.h),
            Text(
              '选择图片来源',
              style: TextStyle(
                fontSize: 16.sp,
                fontWeight: FontWeight.w600,
                color: const Color(0xFF333333),
              ),
            ),
            SizedBox(height: 16.h),
            ListTile(
              leading: const Icon(Icons.camera_alt, color: Color(0xFF2E7D32)),
              title: Text('拍照', style: TextStyle(fontSize: 16.sp)),
              onTap: () {
                Navigator.pop(context);
                _pickAndUploadImage(side);
              },
            ),
            ListTile(
              leading: const Icon(Icons.photo_library, color: Color(0xFF2E7D32)),
              title: Text('从相册选择', style: TextStyle(fontSize: 16.sp)),
              onTap: () {
                Navigator.pop(context);
                _pickFromGallery(side);
              },
            ),
            SizedBox(height: 16.h),
          ],
        ),
      ),
    );
  }

  /// 提交 KYC
  Future<void> _submit() async {
    if (_frontImage == null || _backImage == null) {
      setState(() {
        _errorMessage = '请上传身份证正反面照片';
      });
      return;
    }

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

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

      if (!mounted) return;

      if (result.success) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('KYC认证提交成功', style: TextStyle(fontSize: 14.sp)),
            backgroundColor: const Color(0xFF2E7D32),
            behavior: SnackBarBehavior.floating,
          ),
        );
        ref.invalidate(kycStatusProvider);
        context.pop(true);
      } else {
        setState(() {
          _errorMessage = result.message;
        });
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _errorMessage = e.toString().replaceAll('Exception: ', '');
        });
      }
    } finally {
      if (mounted) {
        setState(() {
          _isSubmitting = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final canSubmit = _frontImage != null &&
        _backImage != null &&
        !_isUploadingFront &&
        !_isUploadingBack;

    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(
          'KYC认证',
          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.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: 24.h),

              // 身份证正面
              Text(
                '身份证正面（人像面）',
                style: TextStyle(
                  fontSize: 14.sp,
                  fontWeight: FontWeight.w500,
                  color: const Color(0xFF333333),
                ),
              ),
              SizedBox(height: 8.h),
              _buildImageUploadCard(
                side: 'front',
                image: _frontImage,
                isUploading: _isUploadingFront,
                placeholder: '点击拍摄或选择身份证正面',
                icon: Icons.credit_card,
              ),
              SizedBox(height: 16.h),

              // 身份证反面
              Text(
                '身份证反面（国徽面）',
                style: TextStyle(
                  fontSize: 14.sp,
                  fontWeight: FontWeight.w500,
                  color: const Color(0xFF333333),
                ),
              ),
              SizedBox(height: 8.h),
              _buildImageUploadCard(
                side: 'back',
                image: _backImage,
                isUploading: _isUploadingBack,
                placeholder: '点击拍摄或选择身份证反面',
                icon: Icons.credit_card,
              ),

              // OCR 识别结果
              if (_ocrResult != null) ...[
                SizedBox(height: 24.h),
                _buildOcrResultCard(),
              ],

              // 错误信息
              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: 24.h),

              // 提示信息
              Container(
                padding: EdgeInsets.all(12.w),
                decoration: BoxDecoration(
                  color: const Color(0xFFFFF3E0),
                  borderRadius: BorderRadius.circular(8.r),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Icon(
                          Icons.info_outline,
                          size: 18.sp,
                          color: const Color(0xFFE65100),
                        ),
                        SizedBox(width: 8.w),
                        Text(
                          '拍摄提示',
                          style: TextStyle(
                            fontSize: 14.sp,
                            fontWeight: FontWeight.w500,
                            color: const Color(0xFFE65100),
                          ),
                        ),
                      ],
                    ),
                    SizedBox(height: 8.h),
                    Text(
                      '• 请确保证件在有效期内\n'
                      '• 照片清晰完整，四角完整可见\n'
                      '• 避免反光、阴影和遮挡\n'
                      '• 照片仅用于身份验证，我们会严格保护您的隐私',
                      style: TextStyle(
                        fontSize: 12.sp,
                        color: const Color(0xFFE65100),
                        height: 1.5,
                      ),
                    ),
                  ],
                ),
              ),

              SizedBox(height: 32.h),

              // 提交按钮
              GestureDetector(
                onTap: (canSubmit && !_isSubmitting) ? _submit : null,
                child: Container(
                  width: double.infinity,
                  padding: EdgeInsets.symmetric(vertical: 16.h),
                  decoration: BoxDecoration(
                    color: (canSubmit && !_isSubmitting)
                        ? const Color(0xFF2E7D32)
                        : const Color(0xFFCCCCCC),
                    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, false, true),
        Expanded(child: _buildStepLine(true)),
        _buildStepDot(2, false, true),
        Expanded(child: _buildStepLine(true)),
        _buildStepDot(3, true, 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 _buildImageUploadCard({
    required String side,
    required Uint8List? image,
    required bool isUploading,
    required String placeholder,
    required IconData icon,
  }) {
    return GestureDetector(
      onTap: isUploading ? null : () => _showImageSourceDialog(side),
      child: Container(
        width: double.infinity,
        height: 160.h,
        decoration: BoxDecoration(
          color: const Color(0xFFF5F5F5),
          borderRadius: BorderRadius.circular(12.r),
          border: Border.all(
            color: image != null ? const Color(0xFF2E7D32) : const Color(0xFFE0E0E0),
            width: image != null ? 2 : 1,
          ),
        ),
        child: isUploading
            ? Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    SizedBox(
                      width: 32.sp,
                      height: 32.sp,
                      child: const CircularProgressIndicator(strokeWidth: 3),
                    ),
                    SizedBox(height: 12.h),
                    Text(
                      '上传中...',
                      style: TextStyle(
                        fontSize: 14.sp,
                        color: const Color(0xFF666666),
                      ),
                    ),
                  ],
                ),
              )
            : image != null
                ? Stack(
                    children: [
                      ClipRRect(
                        borderRadius: BorderRadius.circular(11.r),
                        child: Image.memory(
                          image,
                          width: double.infinity,
                          height: double.infinity,
                          fit: BoxFit.cover,
                        ),
                      ),
                      Positioned(
                        top: 8.h,
                        right: 8.w,
                        child: Container(
                          padding: EdgeInsets.all(4.w),
                          decoration: const BoxDecoration(
                            color: Color(0xFF2E7D32),
                            shape: BoxShape.circle,
                          ),
                          child: Icon(
                            Icons.check,
                            size: 16.sp,
                            color: Colors.white,
                          ),
                        ),
                      ),
                      Positioned(
                        bottom: 8.h,
                        right: 8.w,
                        child: GestureDetector(
                          onTap: () => _showImageSourceDialog(side),
                          child: Container(
                            padding: EdgeInsets.symmetric(
                              horizontal: 12.w,
                              vertical: 6.h,
                            ),
                            decoration: BoxDecoration(
                              color: Colors.black.withValues(alpha: 0.6),
                              borderRadius: BorderRadius.circular(16.r),
                            ),
                            child: Row(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                Icon(
                                  Icons.refresh,
                                  size: 14.sp,
                                  color: Colors.white,
                                ),
                                SizedBox(width: 4.w),
                                Text(
                                  '重拍',
                                  style: TextStyle(
                                    fontSize: 12.sp,
                                    color: Colors.white,
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),
                      ),
                    ],
                  )
                : Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Icon(
                        icon,
                        size: 48.sp,
                        color: const Color(0xFFBDBDBD),
                      ),
                      SizedBox(height: 12.h),
                      Text(
                        placeholder,
                        style: TextStyle(
                          fontSize: 14.sp,
                          color: const Color(0xFF999999),
                        ),
                      ),
                    ],
                  ),
      ),
    );
  }

  Widget _buildOcrResultCard() {
    return Container(
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: const Color(0xFFE8F5E9),
        borderRadius: BorderRadius.circular(12.r),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Icon(Icons.verified, size: 18.sp, color: const Color(0xFF2E7D32)),
              SizedBox(width: 8.w),
              Text(
                'OCR识别结果',
                style: TextStyle(
                  fontSize: 14.sp,
                  fontWeight: FontWeight.w600,
                  color: const Color(0xFF2E7D32),
                ),
              ),
            ],
          ),
          SizedBox(height: 12.h),
          if (_ocrResult!.name != null)
            _buildOcrItem('姓名', _ocrResult!.name!),
          if (_ocrResult!.idNumber != null)
            _buildOcrItem('身份证号', _maskIdNumber(_ocrResult!.idNumber!)),
          if (_ocrResult!.address != null)
            _buildOcrItem('地址', _ocrResult!.address!),
        ],
      ),
    );
  }

  Widget _buildOcrItem(String label, String value) {
    return Padding(
      padding: EdgeInsets.only(bottom: 4.h),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            width: 60.w,
            child: Text(
              label,
              style: TextStyle(
                fontSize: 12.sp,
                color: const Color(0xFF666666),
              ),
            ),
          ),
          Expanded(
            child: Text(
              value,
              style: TextStyle(
                fontSize: 12.sp,
                color: const Color(0xFF333333),
              ),
            ),
          ),
        ],
      ),
    );
  }

  String _maskIdNumber(String idNumber) {
    if (idNumber.length < 8) return '****';
    return '${idNumber.substring(0, 4)}****${idNumber.substring(idNumber.length - 4)}';
  }
}
