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 'withdraw_usdt_page.dart';
import '../../../../core/di/injection_container.dart';
import '../../../../core/services/wallet_service.dart';

/// 提取确认页面
/// 显示提取详情并进行谷歌验证器验证
class WithdrawConfirmPage extends ConsumerStatefulWidget {
  final WithdrawUsdtParams params;

  const WithdrawConfirmPage({
    super.key,
    required this.params,
  });

  @override
  ConsumerState<WithdrawConfirmPage> createState() => _WithdrawConfirmPageState();
}

class _WithdrawConfirmPageState extends ConsumerState<WithdrawConfirmPage> {
  /// 验证码输入控制器列表
  final List<TextEditingController> _codeControllers = List.generate(
    6,
    (index) => TextEditingController(),
  );

  /// 焦点节点列表
  final List<FocusNode> _focusNodes = List.generate(
    6,
    (index) => FocusNode(),
  );

  /// 密码输入控制器
  final TextEditingController _passwordController = TextEditingController();

  /// 密码是否可见
  bool _isPasswordVisible = false;

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

  /// 是否正在发送短信
  bool _isSendingSms = false;

  /// 倒计时秒数
  int _countdown = 0;

  /// 用户手机号（脱敏显示）
  String? _maskedPhoneNumber;

  /// 手续费配置
  FeeConfig? _feeConfig;

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

  /// 加载初始数据（手机号和手续费配置）
  Future<void> _loadInitData() async {
    await Future.wait([
      _loadUserPhone(),
      _loadFeeConfig(),
    ]);
  }

  /// 加载手续费配置
  Future<void> _loadFeeConfig() async {
    try {
      final walletService = ref.read(walletServiceProvider);
      final feeConfig = await walletService.getFeeConfig();
      if (mounted) {
        setState(() {
          _feeConfig = feeConfig;
        });
      }
    } catch (e) {
      debugPrint('[WithdrawConfirmPage] 加载手续费配置失败: $e');
    }
  }

  /// 加载用户手机号
  Future<void> _loadUserPhone() async {
    try {
      final accountService = ref.read(accountServiceProvider);
      final meResponse = await accountService.getMe();
      if (meResponse.phoneNumber != null) {
        // 对手机号进行脱敏处理
        final phone = meResponse.phoneNumber!;
        if (phone.length >= 7) {
          setState(() {
            _maskedPhoneNumber = '${phone.substring(0, 3)}****${phone.substring(phone.length - 4)}';
          });
        }
      }
    } catch (e) {
      debugPrint('[WithdrawConfirmPage] 加载用户手机号失败: $e');
    }
  }

  @override
  void dispose() {
    for (final controller in _codeControllers) {
      controller.dispose();
    }
    for (final node in _focusNodes) {
      node.dispose();
    }
    _passwordController.dispose();
    super.dispose();
  }

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

  /// 发送短信验证码
  Future<void> _sendSmsCode() async {
    if (_isSendingSms || _countdown > 0) return;

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

    try {
      final walletService = ref.read(walletServiceProvider);
      await walletService.sendWithdrawSmsCode();

      if (mounted) {
        setState(() {
          _isSendingSms = false;
          _countdown = 60;
        });
        _startCountdown();

        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('验证码已发送'),
            backgroundColor: Color(0xFF4CAF50),
            duration: Duration(seconds: 2),
          ),
        );
      }
    } catch (e) {
      debugPrint('[WithdrawConfirmPage] 发送验证码失败: $e');
      if (mounted) {
        setState(() {
          _isSendingSms = false;
        });
        String errorMsg = e.toString();
        if (errorMsg.contains('Exception:')) {
          errorMsg = errorMsg.replaceAll('Exception:', '').trim();
        }
        _showErrorSnackBar(errorMsg);
      }
    }
  }

  /// 开始倒计时
  void _startCountdown() {
    Future.doWhile(() async {
      await Future.delayed(const Duration(seconds: 1));
      if (!mounted) return false;
      setState(() {
        _countdown--;
      });
      return _countdown > 0;
    });
  }

  /// 获取验证码
  String _getCode() {
    return _codeControllers.map((c) => c.text).join();
  }

  /// 计算手续费
  double _calculateFee() {
    if (_feeConfig != null) {
      return _feeConfig!.calculateFee(widget.params.amount);
    }
    // 默认固定 2 绿积分
    return 2;
  }

  /// 计算实际到账（接收方收到完整金额，手续费由发送方额外承担）
  double _calculateActualAmount() {
    return widget.params.amount;
  }

  /// 获取网络名称
  String _getNetworkName(WithdrawNetwork network) {
    switch (network) {
      case WithdrawNetwork.kava:
        return 'KAVA';
      case WithdrawNetwork.bsc:
        return 'BSC (BNB Chain)';
    }
  }

  /// 格式化地址（显示前后部分）
  String _formatAddress(String address) {
    if (address.length <= 16) return address;
    return '${address.substring(0, 8)}...${address.substring(address.length - 8)}';
  }

  /// 获取链类型字符串
  String _getChainType(WithdrawNetwork network) {
    switch (network) {
      case WithdrawNetwork.kava:
        return 'KAVA';
      case WithdrawNetwork.bsc:
        return 'BSC';
    }
  }

  /// 提交提取
  Future<void> _onSubmit() async {
    final code = _getCode();
    final password = _passwordController.text.trim();

    // 验证验证码
    if (code.length != 6) {
      _showErrorSnackBar('请输入完整的6位验证码');
      return;
    }

    // 验证密码
    if (password.isEmpty) {
      _showErrorSnackBar('请输入登录密码');
      return;
    }

    if (password.length < 6) {
      _showErrorSnackBar('密码长度至少6位');
      return;
    }

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

    try {
      debugPrint('[WithdrawConfirmPage] 开始提取...');
      debugPrint('[WithdrawConfirmPage]   金额: ${widget.params.amount} USDT');
      debugPrint('[WithdrawConfirmPage]   地址: ${widget.params.address}');
      debugPrint('[WithdrawConfirmPage]   网络: ${_getNetworkName(widget.params.network)}');
      debugPrint('[WithdrawConfirmPage]   验证码: $code');

      // 调用钱包服务提交提取请求
      final walletService = ref.read(walletServiceProvider);
      final response = await walletService.withdrawUsdt(
        amount: widget.params.amount,
        toAddress: widget.params.address,
        chainType: _getChainType(widget.params.network),
        smsCode: code,
        password: password,
      );

      debugPrint('[WithdrawConfirmPage] 提取成功: orderNo=${response.orderNo}');

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

        // 显示成功弹窗
        _showSuccessDialog();
      }
    } catch (e) {
      debugPrint('[WithdrawConfirmPage] 提取失败: $e');
      if (mounted) {
        setState(() {
          _isSubmitting = false;
        });
        // 提取更友好的错误信息
        String errorMsg = e.toString();
        if (errorMsg.contains('Exception:')) {
          errorMsg = errorMsg.replaceAll('Exception:', '').trim();
        }
        _showErrorSnackBar(errorMsg);
      }
    }
  }

  /// 显示成功弹窗
  void _showSuccessDialog() {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => AlertDialog(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(16),
        ),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Container(
              width: 64,
              height: 64,
              decoration: const BoxDecoration(
                shape: BoxShape.circle,
                color: Color(0xFF4CAF50),
              ),
              child: const Icon(
                Icons.check,
                size: 40,
                color: Colors.white,
              ),
            ),
            const SizedBox(height: 16),
            const Text(
              '提取申请已提交',
              style: TextStyle(
                fontSize: 18,
                fontFamily: 'Inter',
                fontWeight: FontWeight.w600,
                color: Color(0xFF5D4037),
              ),
            ),
            const SizedBox(height: 8),
            const Text(
              '预计 1-30 分钟内到账',
              style: TextStyle(
                fontSize: 14,
                fontFamily: 'Inter',
                color: Color(0xFF8B5A2B),
              ),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () {
              Navigator.of(context).pop();
              // 返回交易页面
              context.go('/trading');
            },
            child: const Text(
              '确定',
              style: TextStyle(
                fontSize: 16,
                fontFamily: 'Inter',
                fontWeight: FontWeight.w600,
                color: Color(0xFFD4AF37),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 显示错误提示
  void _showErrorSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        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: SingleChildScrollView(
                  padding: const EdgeInsets.all(16),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // 提取详情卡片
                      _buildDetailsCard(),
                      const SizedBox(height: 24),

                      // 短信验证区域
                      _buildAuthenticatorSection(),
                      const SizedBox(height: 24),

                      // 密码验证区域
                      _buildPasswordSection(),
                      const SizedBox(height: 32),

                      // 提交按钮
                      _buildSubmitButton(),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建顶部导航栏
  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 _buildDetailsCard() {
    final fee = _calculateFee();
    final actual = _calculateActualAmount();

    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: const Color(0x80FFFFFF),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(
          color: const Color(0x33D4AF37),
          width: 1,
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            '提取详情',
            style: TextStyle(
              fontSize: 18,
              fontFamily: 'Inter',
              fontWeight: FontWeight.w600,
              color: Color(0xFF5D4037),
            ),
          ),
          const SizedBox(height: 16),
          // 隐藏提取网络显示（保留原有功能）
          // _buildDetailRow('提取网络', _getNetworkName(widget.params.network)),
          // const SizedBox(height: 12),
          _buildDetailRow('接收账号', _formatAddress(widget.params.address)),
          const SizedBox(height: 12),
          _buildDetailRow('提取数量', '${widget.params.amount.toStringAsFixed(2)} 绿积分'),
          const SizedBox(height: 12),
          _buildDetailRow('手续费', '${fee.toStringAsFixed(2)} 绿积分'),
          const Divider(color: Color(0x33D4AF37), height: 24),
          _buildDetailRow(
            '实际到账',
            '${actual.toStringAsFixed(2)} 绿积分',
            isHighlight: true,
          ),
        ],
      ),
    );
  }

  /// 构建详情行
  Widget _buildDetailRow(String label, String value, {bool isHighlight = false}) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          label,
          style: TextStyle(
            fontSize: 14,
            fontFamily: 'Inter',
            color: isHighlight ? const Color(0xFF5D4037) : const Color(0xFF745D43),
            fontWeight: isHighlight ? FontWeight.w600 : FontWeight.normal,
          ),
        ),
        const SizedBox(width: 16),
        Flexible(
          child: Text(
            value,
            style: TextStyle(
              fontSize: isHighlight ? 18 : 14,
              fontFamily: 'Inter',
              fontWeight: isHighlight ? FontWeight.w700 : FontWeight.w500,
              color: isHighlight ? const Color(0xFFD4AF37) : const Color(0xFF5D4037),
            ),
            textAlign: TextAlign.right,
          ),
        ),
      ],
    );
  }

  /// 构建短信验证区域
  Widget _buildAuthenticatorSection() {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: const Color(0x80FFFFFF),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(
          color: const Color(0x33D4AF37),
          width: 1,
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: const [
              Icon(
                Icons.sms_outlined,
                size: 24,
                color: Color(0xFFD4AF37),
              ),
              SizedBox(width: 8),
              Text(
                '短信验证',
                style: TextStyle(
                  fontSize: 18,
                  fontFamily: 'Inter',
                  fontWeight: FontWeight.w600,
                  color: Color(0xFF5D4037),
                ),
              ),
            ],
          ),
          const SizedBox(height: 8),
          Text(
            _maskedPhoneNumber != null
                ? '验证码将发送至 $_maskedPhoneNumber'
                : '请输入短信验证码',
            style: const TextStyle(
              fontSize: 14,
              fontFamily: 'Inter',
              color: Color(0xFF8B5A2B),
            ),
          ),
          const SizedBox(height: 20),
          // 验证码输入框
          _buildCodeInput(),
          const SizedBox(height: 16),
          // 发送验证码按钮
          _buildSendCodeButton(),
        ],
      ),
    );
  }

  /// 构建密码验证区域
  Widget _buildPasswordSection() {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: const Color(0x80FFFFFF),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(
          color: const Color(0x33D4AF37),
          width: 1,
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: const [
              Icon(
                Icons.lock_outline,
                size: 24,
                color: Color(0xFFD4AF37),
              ),
              SizedBox(width: 8),
              Text(
                '密码验证',
                style: TextStyle(
                  fontSize: 18,
                  fontFamily: 'Inter',
                  fontWeight: FontWeight.w600,
                  color: Color(0xFF5D4037),
                ),
              ),
            ],
          ),
          const SizedBox(height: 8),
          const Text(
            '请输入您的登录密码以确认提取操作',
            style: TextStyle(
              fontSize: 14,
              fontFamily: 'Inter',
              color: Color(0xFF8B5A2B),
            ),
          ),
          const SizedBox(height: 16),
          // 密码输入框
          TextField(
            controller: _passwordController,
            obscureText: !_isPasswordVisible,
            style: const TextStyle(
              fontSize: 16,
              fontFamily: 'Inter',
              color: Color(0xFF5D4037),
            ),
            decoration: InputDecoration(
              hintText: '请输入登录密码',
              hintStyle: const TextStyle(
                fontSize: 16,
                fontFamily: 'Inter',
                color: Color(0xFF8B5A2B),
              ),
              filled: true,
              fillColor: const Color(0xFFFFF5E6),
              border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(8),
                borderSide: const BorderSide(
                  color: Color(0x33D4AF37),
                  width: 1,
                ),
              ),
              enabledBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(8),
                borderSide: const BorderSide(
                  color: Color(0x33D4AF37),
                  width: 1,
                ),
              ),
              focusedBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(8),
                borderSide: const BorderSide(
                  color: Color(0xFFD4AF37),
                  width: 2,
                ),
              ),
              contentPadding: const EdgeInsets.symmetric(
                horizontal: 16,
                vertical: 14,
              ),
              suffixIcon: IconButton(
                icon: Icon(
                  _isPasswordVisible
                      ? Icons.visibility_off_outlined
                      : Icons.visibility_outlined,
                  color: const Color(0xFF8B5A2B),
                ),
                onPressed: () {
                  setState(() {
                    _isPasswordVisible = !_isPasswordVisible;
                  });
                },
              ),
            ),
            onChanged: (_) => setState(() {}),
          ),
        ],
      ),
    );
  }

  /// 构建发送验证码按钮
  Widget _buildSendCodeButton() {
    final canSend = !_isSendingSms && _countdown <= 0;

    return GestureDetector(
      onTap: canSend ? _sendSmsCode : null,
      child: Container(
        width: double.infinity,
        height: 44,
        decoration: BoxDecoration(
          color: canSend
              ? const Color(0xFFD4AF37).withValues(alpha: 0.15)
              : const Color(0xFFD4AF37).withValues(alpha: 0.08),
          borderRadius: BorderRadius.circular(8),
          border: Border.all(
            color: canSend
                ? const Color(0xFFD4AF37).withValues(alpha: 0.5)
                : const Color(0xFFD4AF37).withValues(alpha: 0.2),
            width: 1,
          ),
        ),
        child: Center(
          child: _isSendingSms
              ? const SizedBox(
                  width: 20,
                  height: 20,
                  child: CircularProgressIndicator(
                    strokeWidth: 2,
                    valueColor: AlwaysStoppedAnimation<Color>(Color(0xFFD4AF37)),
                  ),
                )
              : Text(
                  _countdown > 0 ? '${_countdown}s 后重新发送' : '获取验证码',
                  style: TextStyle(
                    fontSize: 14,
                    fontFamily: 'Inter',
                    fontWeight: FontWeight.w600,
                    color: canSend
                        ? const Color(0xFFD4AF37)
                        : const Color(0xFFD4AF37).withValues(alpha: 0.5),
                  ),
                ),
        ),
      ),
    );
  }

  /// 构建验证码输入框
  Widget _buildCodeInput() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: List.generate(6, (index) {
        return SizedBox(
          width: 45,
          height: 54,
          child: TextField(
            controller: _codeControllers[index],
            focusNode: _focusNodes[index],
            textAlign: TextAlign.center,
            keyboardType: TextInputType.number,
            maxLength: 1,
            style: const TextStyle(
              fontSize: 24,
              fontFamily: 'Inter',
              fontWeight: FontWeight.w700,
              color: Color(0xFF5D4037),
            ),
            decoration: InputDecoration(
              counterText: '',
              filled: true,
              fillColor: const Color(0xFFFFF5E6),
              border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(8),
                borderSide: const BorderSide(
                  color: Color(0x33D4AF37),
                  width: 1,
                ),
              ),
              enabledBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(8),
                borderSide: const BorderSide(
                  color: Color(0x33D4AF37),
                  width: 1,
                ),
              ),
              focusedBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(8),
                borderSide: const BorderSide(
                  color: Color(0xFFD4AF37),
                  width: 2,
                ),
              ),
              contentPadding: const EdgeInsets.symmetric(vertical: 12),
            ),
            inputFormatters: [
              FilteringTextInputFormatter.digitsOnly,
            ],
            onChanged: (value) {
              if (value.isNotEmpty && index < 5) {
                _focusNodes[index + 1].requestFocus();
              }
              setState(() {});
            },
          ),
        );
      }),
    );
  }

  /// 构建提交按钮
  Widget _buildSubmitButton() {
    final code = _getCode();
    final password = _passwordController.text.trim();
    final isValid = code.length == 6 && password.length >= 6;

    return GestureDetector(
      onTap: (isValid && !_isSubmitting) ? _onSubmit : null,
      child: Container(
        width: double.infinity,
        height: 56,
        decoration: BoxDecoration(
          color: (isValid && !_isSubmitting)
              ? const Color(0xFFD4AF37)
              : const Color(0x80D4AF37),
          borderRadius: BorderRadius.circular(12),
          boxShadow: (isValid && !_isSubmitting)
              ? const [
                  BoxShadow(
                    color: Color(0x4DD4AF37),
                    blurRadius: 14,
                    offset: Offset(0, 4),
                  ),
                ]
              : null,
        ),
        child: Center(
          child: _isSubmitting
              ? const SizedBox(
                  width: 24,
                  height: 24,
                  child: CircularProgressIndicator(
                    strokeWidth: 2,
                    valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                  ),
                )
              : const Text(
                  '确认提取',
                  style: TextStyle(
                    fontSize: 16,
                    fontFamily: 'Inter',
                    fontWeight: FontWeight.w700,
                    height: 1.5,
                    letterSpacing: 0.24,
                    color: Colors.white,
                  ),
                ),
        ),
      ),
    );
  }
}
