import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:qr_flutter/qr_flutter.dart';

/// 谷歌验证器页面
/// 用于绑定/解绑谷歌验证器，提供二维码扫描和密钥复制功能
class GoogleAuthPage extends ConsumerStatefulWidget {
  const GoogleAuthPage({super.key});

  @override
  ConsumerState<GoogleAuthPage> createState() => _GoogleAuthPageState();
}

class _GoogleAuthPageState extends ConsumerState<GoogleAuthPage> {
  /// 验证码输入控制器
  final TextEditingController _codeController = TextEditingController();

  /// 是否正在加载
  bool _isLoading = true;

  /// 是否已绑定谷歌验证器
  bool _isBound = false;

  /// 谷歌验证器密钥（用于生成二维码）
  String? _secret;

  /// 谷歌验证器 URI（用于生成二维码）
  String? _otpAuthUri;

  /// 是否正在提交
  bool _isSubmitting = false;

  /// 错误信息
  String? _errorMessage;

  @override
  void initState() {
    super.initState();
    _loadGoogleAuthStatus();
  }

  @override
  void dispose() {
    _codeController.dispose();
    super.dispose();
  }

  /// 加载谷歌验证器状态
  Future<void> _loadGoogleAuthStatus() async {
    setState(() {
      _isLoading = true;
      _errorMessage = null;
    });

    try {
      // TODO: 调用API获取谷歌验证器状态
      // final accountService = ref.read(accountServiceProvider);
      // final status = await accountService.getGoogleAuthStatus();

      // 模拟数据
      await Future.delayed(const Duration(milliseconds: 500));

      if (mounted) {
        setState(() {
          _isBound = false; // 模拟未绑定状态
          _secret = 'JBSWY3DPEHPK3PXP'; // 模拟密钥
          _otpAuthUri = 'otpauth://totp/RWADurian:user@example.com?secret=JBSWY3DPEHPK3PXP&issuer=RWADurian';
          _isLoading = false;
        });
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _errorMessage = '加载失败: ${e.toString()}';
          _isLoading = false;
        });
      }
    }
  }

  /// 返回上一页
  void _goBack() {
    context.pop();
  }

  /// 复制密钥到剪贴板
  void _copySecret() {
    if (_secret != null) {
      Clipboard.setData(ClipboardData(text: _secret!));
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('密钥已复制到剪贴板'),
          backgroundColor: Color(0xFFD4AF37),
        ),
      );
    }
  }

  /// 绑定谷歌验证器
  Future<void> _bindGoogleAuth() async {
    final code = _codeController.text.trim();

    if (code.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('请输入验证码'),
          backgroundColor: Colors.red,
        ),
      );
      return;
    }

    if (code.length != 6 || !RegExp(r'^\d{6}$').hasMatch(code)) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('验证码格式错误，请输入6位数字'),
          backgroundColor: Colors.red,
        ),
      );
      return;
    }

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

    try {
      // TODO: 调用API绑定谷歌验证器
      // final accountService = ref.read(accountServiceProvider);
      // await accountService.bindGoogleAuth(code);

      // 模拟请求
      await Future.delayed(const Duration(seconds: 1));

      if (mounted) {
        setState(() {
          _isBound = true;
          _isSubmitting = false;
        });

        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('谷歌验证器绑定成功'),
            backgroundColor: Color(0xFF4CAF50),
          ),
        );
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _isSubmitting = false;
        });

        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('绑定失败: ${e.toString()}'),
            backgroundColor: Colors.red,
          ),
        );
      }
    }
  }

  /// 解绑谷歌验证器
  Future<void> _unbindGoogleAuth() async {
    final code = _codeController.text.trim();

    if (code.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('请输入验证码'),
          backgroundColor: Colors.red,
        ),
      );
      return;
    }

    // 显示确认对话框
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        backgroundColor: Colors.white,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(16),
        ),
        title: const Text(
          '确认解绑',
          style: TextStyle(
            fontSize: 18,
            fontFamily: 'Inter',
            fontWeight: FontWeight.w600,
            color: Color(0xFF5D4037),
          ),
        ),
        content: const Text(
          '解绑后将降低账户安全性，确定要解绑谷歌验证器吗？',
          style: TextStyle(
            fontSize: 14,
            fontFamily: 'Inter',
            color: Color(0xFF745D43),
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context, false),
            child: const Text(
              '取消',
              style: TextStyle(
                color: Color(0xFF8B5A2B),
              ),
            ),
          ),
          TextButton(
            onPressed: () => Navigator.pop(context, true),
            child: const Text(
              '确认解绑',
              style: TextStyle(
                color: Colors.red,
              ),
            ),
          ),
        ],
      ),
    );

    if (confirmed != true) return;

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

    try {
      // TODO: 调用API解绑谷歌验证器
      // final accountService = ref.read(accountServiceProvider);
      // await accountService.unbindGoogleAuth(code);

      // 模拟请求
      await Future.delayed(const Duration(seconds: 1));

      if (mounted) {
        setState(() {
          _isBound = false;
          _isSubmitting = false;
        });

        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('谷歌验证器已解绑'),
            backgroundColor: Color(0xFFD4AF37),
          ),
        );

        // 重新加载状态（获取新的密钥）
        _loadGoogleAuthStatus();
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _isSubmitting = false;
        });

        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('解绑失败: ${e.toString()}'),
            backgroundColor: Colors.red,
          ),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: const BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [
              Color(0xFFFFF5E6),
              Color(0xFFFFE4B5),
            ],
          ),
        ),
        child: SafeArea(
          child: Column(
            children: [
              // 顶部导航栏
              _buildAppBar(),
              // 内容区域
              Expanded(
                child: _isLoading
                    ? const Center(
                        child: CircularProgressIndicator(
                          valueColor: AlwaysStoppedAnimation<Color>(Color(0xFFD4AF37)),
                        ),
                      )
                    : _errorMessage != null
                        ? _buildErrorView()
                        : SingleChildScrollView(
                            padding: const EdgeInsets.all(16),
                            child: _isBound
                                ? _buildBoundContent()
                                : _buildUnboundContent(),
                          ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建顶部导航栏
  Widget _buildAppBar() {
    return Container(
      height: 64,
      padding: const EdgeInsets.only(top: 16, left: 16, right: 16),
      child: Row(
        children: [
          // 返回按钮
          GestureDetector(
            onTap: _goBack,
            child: Container(
              width: 48,
              height: 48,
              alignment: Alignment.center,
              child: const Icon(
                Icons.arrow_back,
                size: 24,
                color: Color(0xFF5D4037),
              ),
            ),
          ),
          // 标题
          const Expanded(
            child: Text(
              '谷歌验证器',
              style: TextStyle(
                fontSize: 18,
                fontFamily: 'Inter',
                fontWeight: FontWeight.w500,
                height: 1.25,
                letterSpacing: -0.27,
                color: Color(0xFF5D4037),
              ),
              textAlign: TextAlign.center,
            ),
          ),
          // 占位
          const SizedBox(width: 48),
        ],
      ),
    );
  }

  /// 构建错误视图
  Widget _buildErrorView() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const Icon(
            Icons.error_outline,
            size: 64,
            color: Color(0xFF8B5A2B),
          ),
          const SizedBox(height: 16),
          Text(
            _errorMessage!,
            style: const TextStyle(
              fontSize: 16,
              fontFamily: 'Inter',
              color: Color(0xFF745D43),
            ),
            textAlign: TextAlign.center,
          ),
          const SizedBox(height: 24),
          GestureDetector(
            onTap: _loadGoogleAuthStatus,
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
              decoration: BoxDecoration(
                color: const Color(0xFFD4AF37),
                borderRadius: BorderRadius.circular(8),
              ),
              child: const Text(
                '重试',
                style: TextStyle(
                  fontSize: 16,
                  fontFamily: 'Inter',
                  fontWeight: FontWeight.w600,
                  color: Colors.white,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建未绑定状态内容
  Widget _buildUnboundContent() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 状态提示
        _buildStatusCard(
          icon: Icons.security,
          title: '未绑定',
          subtitle: '绑定谷歌验证器可提升账户安全性',
          color: const Color(0xFFFF9800),
        ),
        const SizedBox(height: 24),

        // 步骤说明
        _buildStepCard(
          stepNumber: '1',
          title: '下载谷歌验证器',
          description: '在应用商店搜索 "Google Authenticator" 并下载安装',
        ),
        const SizedBox(height: 16),

        _buildStepCard(
          stepNumber: '2',
          title: '扫描二维码或输入密钥',
          description: '使用谷歌验证器扫描下方二维码，或手动输入密钥',
        ),
        const SizedBox(height: 16),

        // 二维码区域
        _buildQrCodeSection(),
        const SizedBox(height: 16),

        _buildStepCard(
          stepNumber: '3',
          title: '输入验证码完成绑定',
          description: '输入谷歌验证器显示的6位数字验证码',
        ),
        const SizedBox(height: 16),

        // 验证码输入
        _buildCodeInput(),
        const SizedBox(height: 24),

        // 绑定按钮
        _buildSubmitButton(
          text: '绑定谷歌验证器',
          onTap: _bindGoogleAuth,
        ),
      ],
    );
  }

  /// 构建已绑定状态内容
  Widget _buildBoundContent() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 状态提示
        _buildStatusCard(
          icon: Icons.verified_user,
          title: '已绑定',
          subtitle: '您的账户已启用谷歌验证器保护',
          color: const Color(0xFF4CAF50),
        ),
        const SizedBox(height: 24),

        // 提示卡片
        Container(
          width: double.infinity,
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            color: const Color(0x33FFC107),
            borderRadius: BorderRadius.circular(12),
          ),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const Icon(
                Icons.info_outline,
                color: Color(0xFFD4AF37),
                size: 24,
              ),
              const SizedBox(width: 12),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: const [
                    Text(
                      '安全提示',
                      style: TextStyle(
                        fontSize: 16,
                        fontFamily: 'Inter',
                        fontWeight: FontWeight.w600,
                        color: Color(0xFF5D4037),
                      ),
                    ),
                    SizedBox(height: 4),
                    Text(
                      '谷歌验证器已启用，每次登录和重要操作时需要输入验证码。如需解绑，请输入当前验证码。',
                      style: TextStyle(
                        fontSize: 14,
                        fontFamily: 'Inter',
                        color: Color(0xFF745D43),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
        const SizedBox(height: 24),

        // 验证码输入
        const Text(
          '输入验证码以解绑',
          style: TextStyle(
            fontSize: 16,
            fontFamily: 'Inter',
            fontWeight: FontWeight.w500,
            color: Color(0xFF5D4037),
          ),
        ),
        const SizedBox(height: 12),
        _buildCodeInput(),
        const SizedBox(height: 24),

        // 解绑按钮
        _buildSubmitButton(
          text: '解绑谷歌验证器',
          onTap: _unbindGoogleAuth,
          isDanger: true,
        ),
      ],
    );
  }

  /// 构建状态卡片
  Widget _buildStatusCard({
    required IconData icon,
    required String title,
    required String subtitle,
    required Color color,
  }) {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: const Color(0x80FFFFFF),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(
          color: const Color(0x33D4AF37),
          width: 1,
        ),
      ),
      child: Row(
        children: [
          Container(
            width: 48,
            height: 48,
            decoration: BoxDecoration(
              color: color.withValues(alpha: 0.1),
              borderRadius: BorderRadius.circular(24),
            ),
            child: Icon(
              icon,
              color: color,
              size: 24,
            ),
          ),
          const SizedBox(width: 16),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  title,
                  style: TextStyle(
                    fontSize: 18,
                    fontFamily: 'Inter',
                    fontWeight: FontWeight.w600,
                    color: color,
                  ),
                ),
                const SizedBox(height: 4),
                Text(
                  subtitle,
                  style: const TextStyle(
                    fontSize: 14,
                    fontFamily: 'Inter',
                    color: Color(0xFF745D43),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 构建步骤卡片
  Widget _buildStepCard({
    required String stepNumber,
    required String title,
    required String description,
  }) {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: const Color(0x80FFFFFF),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(
          color: const Color(0x33D4AF37),
          width: 1,
        ),
      ),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            width: 32,
            height: 32,
            decoration: BoxDecoration(
              color: const Color(0xFFD4AF37),
              borderRadius: BorderRadius.circular(16),
            ),
            child: Center(
              child: Text(
                stepNumber,
                style: const TextStyle(
                  fontSize: 16,
                  fontFamily: 'Inter',
                  fontWeight: FontWeight.w700,
                  color: Colors.white,
                ),
              ),
            ),
          ),
          const SizedBox(width: 12),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  title,
                  style: const TextStyle(
                    fontSize: 16,
                    fontFamily: 'Inter',
                    fontWeight: FontWeight.w600,
                    color: Color(0xFF5D4037),
                  ),
                ),
                const SizedBox(height: 4),
                Text(
                  description,
                  style: const TextStyle(
                    fontSize: 14,
                    fontFamily: 'Inter',
                    color: Color(0xFF745D43),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 构建二维码区域
  Widget _buildQrCodeSection() {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(
          color: const Color(0x33D4AF37),
          width: 1,
        ),
      ),
      child: Column(
        children: [
          // 二维码
          if (_otpAuthUri != null)
            Container(
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(8),
              ),
              child: QrImageView(
                data: _otpAuthUri!,
                version: QrVersions.auto,
                size: 180,
                backgroundColor: Colors.white,
                eyeStyle: const QrEyeStyle(
                  eyeShape: QrEyeShape.square,
                  color: Color(0xFF5D4037),
                ),
                dataModuleStyle: const QrDataModuleStyle(
                  dataModuleShape: QrDataModuleShape.square,
                  color: Color(0xFF5D4037),
                ),
              ),
            ),
          const SizedBox(height: 16),

          // 密钥显示
          const Text(
            '或手动输入密钥',
            style: TextStyle(
              fontSize: 14,
              fontFamily: 'Inter',
              color: Color(0xFF745D43),
            ),
          ),
          const SizedBox(height: 8),
          GestureDetector(
            onTap: _copySecret,
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
              decoration: BoxDecoration(
                color: const Color(0xFFFFF5E6),
                borderRadius: BorderRadius.circular(8),
                border: Border.all(
                  color: const Color(0x33D4AF37),
                  width: 1,
                ),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    _secret ?? '',
                    style: const TextStyle(
                      fontSize: 16,
                      fontFamily: 'Inter',
                      fontWeight: FontWeight.w600,
                      letterSpacing: 2,
                      color: Color(0xFF5D4037),
                    ),
                  ),
                  const SizedBox(width: 12),
                  const Icon(
                    Icons.copy,
                    size: 20,
                    color: Color(0xFFD4AF37),
                  ),
                ],
              ),
            ),
          ),
          const SizedBox(height: 8),
          const Text(
            '点击复制密钥',
            style: TextStyle(
              fontSize: 12,
              fontFamily: 'Inter',
              color: Color(0xFF8B5A2B),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建验证码输入框
  Widget _buildCodeInput() {
    return Container(
      width: double.infinity,
      height: 54,
      decoration: BoxDecoration(
        color: const Color(0x80FFFFFF),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(
          color: const Color(0x80FFFFFF),
          width: 1,
        ),
        boxShadow: const [
          BoxShadow(
            color: Color(0x0D000000),
            blurRadius: 2,
            offset: Offset(0, 1),
          ),
        ],
      ),
      child: TextField(
        controller: _codeController,
        keyboardType: TextInputType.number,
        maxLength: 6,
        style: const TextStyle(
          fontSize: 20,
          fontFamily: 'Inter',
          fontWeight: FontWeight.w600,
          letterSpacing: 8,
          height: 1.19,
          color: Color(0xFF5D4037),
        ),
        textAlign: TextAlign.center,
        inputFormatters: [
          FilteringTextInputFormatter.digitsOnly,
        ],
        decoration: const InputDecoration(
          counterText: '',
          contentPadding: EdgeInsets.symmetric(horizontal: 16, vertical: 15),
          border: InputBorder.none,
          hintText: '000000',
          hintStyle: TextStyle(
            fontSize: 20,
            fontFamily: 'Inter',
            fontWeight: FontWeight.w600,
            letterSpacing: 8,
            height: 1.19,
            color: Color(0x335D4037),
          ),
        ),
      ),
    );
  }

  /// 构建提交按钮
  Widget _buildSubmitButton({
    required String text,
    required VoidCallback onTap,
    bool isDanger = false,
  }) {
    return GestureDetector(
      onTap: _isSubmitting ? null : onTap,
      child: Container(
        width: double.infinity,
        height: 56,
        decoration: BoxDecoration(
          color: isDanger
              ? (_isSubmitting ? Colors.red.withValues(alpha: 0.5) : Colors.red)
              : (_isSubmitting ? const Color(0xFFD4AF37).withValues(alpha: 0.5) : const Color(0xFFD4AF37)),
          borderRadius: BorderRadius.circular(12),
          boxShadow: [
            BoxShadow(
              color: isDanger
                  ? Colors.red.withValues(alpha: 0.3)
                  : const Color(0x4DD4AF37),
              blurRadius: 14,
              offset: const Offset(0, 4),
            ),
          ],
        ),
        child: Center(
          child: _isSubmitting
              ? const SizedBox(
                  width: 24,
                  height: 24,
                  child: CircularProgressIndicator(
                    strokeWidth: 2,
                    valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                  ),
                )
              : Text(
                  text,
                  style: const TextStyle(
                    fontSize: 16,
                    fontFamily: 'Inter',
                    fontWeight: FontWeight.w700,
                    height: 1.5,
                    letterSpacing: 0.24,
                    color: Colors.white,
                  ),
                ),
        ),
      ),
    );
  }
}
