import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../../../core/di/injection_container.dart';
import '../../../../core/services/wallet_service.dart';
import '../../../../routes/route_paths.dart';
import 'withdraw_fiat_page.dart';

/// 法币提现确认页面
/// 进行短信验证和密码验证后提交提现申请
class WithdrawFiatConfirmPage extends ConsumerStatefulWidget {
  final WithdrawFiatParams params;

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

  @override
  ConsumerState<WithdrawFiatConfirmPage> createState() => _WithdrawFiatConfirmPageState();
}

class _WithdrawFiatConfirmPageState extends ConsumerState<WithdrawFiatConfirmPage> {
  /// 短信验证码控制器
  final TextEditingController _smsCodeController = TextEditingController();

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

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

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

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

  /// 倒计时定时器
  Timer? _countdownTimer;

  /// 是否显示密码
  bool _obscurePassword = true;

  @override
  void dispose() {
    _smsCodeController.dispose();
    _passwordController.dispose();
    _countdownTimer?.cancel();
    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.sendFiatWithdrawalSmsCode();

      if (mounted) {
        _showSuccessSnackBar('验证码已发送');
        _startCountdown();
      }
    } catch (e) {
      if (mounted) {
        _showErrorSnackBar(e.toString().replaceFirst('Exception: ', ''));
      }
    } finally {
      if (mounted) {
        setState(() {
          _isSendingSms = false;
        });
      }
    }
  }

  /// 开始倒计时
  void _startCountdown() {
    setState(() {
      _countdown = 60;
    });

    _countdownTimer?.cancel();
    _countdownTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (_countdown <= 1) {
        timer.cancel();
        setState(() {
          _countdown = 0;
        });
      } else {
        setState(() {
          _countdown--;
        });
      }
    });
  }

  /// 提交提现申请
  Future<void> _onSubmit() async {
    final smsCode = _smsCodeController.text.trim();
    final password = _passwordController.text;

    // 验证输入
    if (smsCode.isEmpty) {
      _showErrorSnackBar('请输入短信验证码');
      return;
    }

    if (smsCode.length != 6) {
      _showErrorSnackBar('请输入6位验证码');
      return;
    }

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

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

    try {
      final walletService = ref.read(walletServiceProvider);
      final result = await walletService.withdrawFiat(
        amount: widget.params.amount,
        paymentMethod: widget.params.paymentMethod,
        bankName: widget.params.bankName,
        bankCardNo: widget.params.bankCardNo,
        cardHolderName: widget.params.cardHolderName,
        alipayAccount: widget.params.alipayAccount,
        alipayRealName: widget.params.alipayRealName,
        wechatAccount: widget.params.wechatAccount,
        wechatRealName: widget.params.wechatRealName,
        smsCode: smsCode,
        password: password,
      );

      if (mounted) {
        _showSuccessDialog(result.orderNo);
      }
    } catch (e) {
      if (mounted) {
        _showErrorSnackBar(e.toString().replaceFirst('Exception: ', ''));
      }
    } finally {
      if (mounted) {
        setState(() {
          _isSubmitting = false;
        });
      }
    }
  }

  /// 显示成功对话框
  void _showSuccessDialog(String orderNo) {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => AlertDialog(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(16),
        ),
        title: const Row(
          children: [
            Icon(
              Icons.check_circle,
              color: Color(0xFF52C41A),
              size: 28,
            ),
            SizedBox(width: 12),
            Text(
              '提现申请已提交',
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.w600,
              ),
            ),
          ],
        ),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '订单号：$orderNo',
              style: const TextStyle(
                fontSize: 14,
                color: Color(0xFF666666),
              ),
            ),
            const SizedBox(height: 12),
            const Text(
              '您的提现申请已提交，将在1-3个工作日内完成审核和打款。',
              style: TextStyle(
                fontSize: 14,
                color: Color(0xFF666666),
              ),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () {
              Navigator.of(context).pop();
              // 返回到交易页面
              context.go(RoutePaths.trading);
            },
            child: const Text(
              '确定',
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w600,
                color: Color(0xFFD4AF37),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 显示成功提示
  void _showSuccessSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: const Color(0xFF52C41A),
      ),
    );
  }

  /// 显示错误提示
  void _showErrorSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: Colors.red,
      ),
    );
  }

  /// 获取支付方式名称
  String _getPaymentMethodName(PaymentMethod method) {
    switch (method) {
      case PaymentMethod.BANK_CARD:
        return '银行卡';
      case PaymentMethod.ALIPAY:
        return '支付宝';
      case PaymentMethod.WECHAT:
        return '微信';
    }
  }

  @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: [
                      // 订单信息
                      _buildOrderInfo(),
                      const SizedBox(height: 24),

                      // 短信验证码
                      _buildSmsCodeInput(),
                      const SizedBox(height: 24),

                      // 密码输入
                      _buildPasswordInput(),
                      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 _buildOrderInfo() {
    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: 16,
              fontFamily: 'Inter',
              fontWeight: FontWeight.w600,
              color: Color(0xFF5D4037),
            ),
          ),
          const SizedBox(height: 16),
          _buildInfoRow('提现金额', '¥${widget.params.amount.toStringAsFixed(2)}', isHighlight: true),
          const SizedBox(height: 12),
          _buildInfoRow('收款方式', _getPaymentMethodName(widget.params.paymentMethod)),
          const SizedBox(height: 12),
          // 根据支付方式显示不同信息
          if (widget.params.paymentMethod == PaymentMethod.BANK_CARD) ...[
            _buildInfoRow('银行名称', widget.params.bankName ?? ''),
            const SizedBox(height: 12),
            _buildInfoRow('银行卡号', _maskCardNo(widget.params.bankCardNo ?? '')),
            const SizedBox(height: 12),
            _buildInfoRow('持卡人', widget.params.cardHolderName ?? ''),
          ] else if (widget.params.paymentMethod == PaymentMethod.ALIPAY) ...[
            _buildInfoRow('支付宝账号', widget.params.alipayAccount ?? ''),
            const SizedBox(height: 12),
            _buildInfoRow('实名姓名', widget.params.alipayRealName ?? ''),
          ] else if (widget.params.paymentMethod == PaymentMethod.WECHAT) ...[
            _buildInfoRow('微信号', widget.params.wechatAccount ?? ''),
            const SizedBox(height: 12),
            _buildInfoRow('实名姓名', widget.params.wechatRealName ?? ''),
          ],
        ],
      ),
    );
  }

  /// 遮掩卡号中间部分
  String _maskCardNo(String cardNo) {
    if (cardNo.length < 8) return cardNo;
    final start = cardNo.substring(0, 4);
    final end = cardNo.substring(cardNo.length - 4);
    return '$start **** **** $end';
  }

  /// 构建信息行
  Widget _buildInfoRow(String label, String value, {bool isHighlight = false}) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text(
          label,
          style: const TextStyle(
            fontSize: 14,
            fontFamily: 'Inter',
            color: Color(0xFF745D43),
          ),
        ),
        Text(
          value,
          style: TextStyle(
            fontSize: isHighlight ? 18 : 14,
            fontFamily: 'Inter',
            fontWeight: isHighlight ? FontWeight.w700 : FontWeight.w500,
            color: isHighlight ? const Color(0xFFD4AF37) : const Color(0xFF5D4037),
          ),
        ),
      ],
    );
  }

  /// 构建短信验证码输入
  Widget _buildSmsCodeInput() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          '短信验证码',
          style: TextStyle(
            fontSize: 16,
            fontFamily: 'Inter',
            fontWeight: FontWeight.w600,
            color: Color(0xFF5D4037),
          ),
        ),
        const SizedBox(height: 12),
        Container(
          width: double.infinity,
          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: Row(
            children: [
              Expanded(
                child: TextField(
                  controller: _smsCodeController,
                  keyboardType: TextInputType.number,
                  maxLength: 6,
                  style: const TextStyle(
                    fontSize: 16,
                    fontFamily: 'Inter',
                    fontWeight: FontWeight.w600,
                    height: 1.4,
                    color: Color(0xFF5D4037),
                    letterSpacing: 8,
                  ),
                  decoration: const InputDecoration(
                    contentPadding: EdgeInsets.all(16),
                    border: InputBorder.none,
                    hintText: '请输入验证码',
                    hintStyle: TextStyle(
                      fontSize: 16,
                      fontFamily: 'Inter',
                      height: 1.4,
                      color: Color(0x995D4037),
                      letterSpacing: 0,
                    ),
                    counterText: '',
                  ),
                ),
              ),
              // 发送验证码按钮
              GestureDetector(
                onTap: _countdown > 0 || _isSendingSms ? null : _sendSmsCode,
                child: Container(
                  padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                  margin: const EdgeInsets.only(right: 8),
                  decoration: BoxDecoration(
                    color: _countdown > 0 || _isSendingSms
                        ? const Color(0x40D4AF37)
                        : const Color(0xFFD4AF37),
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: Text(
                    _isSendingSms
                        ? '发送中...'
                        : _countdown > 0
                            ? '${_countdown}s'
                            : '获取验证码',
                    style: const TextStyle(
                      fontSize: 14,
                      fontFamily: 'Inter',
                      fontWeight: FontWeight.w600,
                      color: Colors.white,
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  /// 构建密码输入
  Widget _buildPasswordInput() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          '登录密码',
          style: TextStyle(
            fontSize: 16,
            fontFamily: 'Inter',
            fontWeight: FontWeight.w600,
            color: Color(0xFF5D4037),
          ),
        ),
        const SizedBox(height: 12),
        Container(
          width: double.infinity,
          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: _passwordController,
            obscureText: _obscurePassword,
            style: const TextStyle(
              fontSize: 16,
              fontFamily: 'Inter',
              height: 1.4,
              color: Color(0xFF5D4037),
            ),
            decoration: InputDecoration(
              contentPadding: const EdgeInsets.all(16),
              border: InputBorder.none,
              hintText: '请输入登录密码',
              hintStyle: const TextStyle(
                fontSize: 16,
                fontFamily: 'Inter',
                height: 1.4,
                color: Color(0x995D4037),
              ),
              suffixIcon: IconButton(
                icon: Icon(
                  _obscurePassword ? Icons.visibility_off : Icons.visibility,
                  color: const Color(0xFF8B5A2B),
                  size: 22,
                ),
                onPressed: () {
                  setState(() {
                    _obscurePassword = !_obscurePassword;
                  });
                },
              ),
            ),
          ),
        ),
      ],
    );
  }

  /// 构建提交按钮
  Widget _buildSubmitButton() {
    return GestureDetector(
      onTap: _isSubmitting ? null : _onSubmit,
      child: Container(
        width: double.infinity,
        height: 56,
        decoration: BoxDecoration(
          color: _isSubmitting ? const Color(0x80D4AF37) : const Color(0xFFD4AF37),
          borderRadius: BorderRadius.circular(12),
          boxShadow: _isSubmitting
              ? null
              : const [
                  BoxShadow(
                    color: Color(0x4DD4AF37),
                    blurRadius: 14,
                    offset: Offset(0, 4),
                  ),
                ],
        ),
        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,
                  ),
                ),
        ),
      ),
    );
  }
}
