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

/// 认种数量选择页面
/// 用户可以选择认种的榴莲树数量，根据可用余额自动计算最大可认种数量
class PlantingQuantityPage extends ConsumerStatefulWidget {
  const PlantingQuantityPage({super.key});

  @override
  ConsumerState<PlantingQuantityPage> createState() =>
      _PlantingQuantityPageState();
}

class _PlantingQuantityPageState extends ConsumerState<PlantingQuantityPage> {
  /// 每棵树的价格 (USDT) - 从 admin-service 动态获取
  double _pricePerTree = 15831.0;

  /// 定价配置（用于展示下次涨价信息）
  TreePricingConfig? _pricingConfig;

  /// 可用余额 (USDT) - 从 API 获取
  double _availableBalance = 0.0;

  /// 当前选择的数量
  int _quantity = 0;

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

  /// 是否正在创建订单
  bool _isCreatingOrder = false;

  /// 加载错误信息
  String? _errorMessage;

  /// 数量输入框控制器
  final TextEditingController _quantityController = TextEditingController();

  /// 数量输入框焦点
  final FocusNode _quantityFocusNode = FocusNode();

  /// 是否显示超出警告
  bool _showExceedWarning = false;

  /// 涨价倒计时 timer
  Timer? _priceCountdownTimer;

  /// 距下次涨价的剩余时间
  Duration _timeUntilIncrease = Duration.zero;

  @override
  void initState() {
    super.initState();
    _loadPricingConfig();
    _loadBalance();
    _quantityController.addListener(_onQuantityChanged);
  }

  /// 从 admin-service 加载动态定价配置
  Future<void> _loadPricingConfig() async {
    try {
      final treePricingService = ref.read(treePricingServiceProvider);
      final config = await treePricingService.getConfig();
      if (mounted) {
        setState(() {
          _pricingConfig = config;
          _pricePerTree = config.totalPrice.toDouble();
        });
        _startPriceCountdown();
        debugPrint('[PlantingQuantity] 动态定价: ${config.totalPrice} USDT/棵 (supplement=${config.currentSupplement})');
      }
    } catch (e) {
      debugPrint('[PlantingQuantity] 获取定价失败，使用默认 15831: $e');
      // 安全降级：保持 15831 默认值
    }
  }

  @override
  void dispose() {
    _priceCountdownTimer?.cancel();
    _quantityController.removeListener(_onQuantityChanged);
    _quantityController.dispose();
    _quantityFocusNode.dispose();
    super.dispose();
  }

  /// 启动涨价倒计时
  void _startPriceCountdown() {
    _priceCountdownTimer?.cancel();
    final config = _pricingConfig;
    if (config == null || !config.autoIncreaseEnabled || config.nextAutoIncreaseAt == null) {
      return;
    }
    _updateCountdown();
    _priceCountdownTimer = Timer.periodic(const Duration(minutes: 1), (_) {
      _updateCountdown();
    });
  }

  void _updateCountdown() {
    final nextAt = _pricingConfig?.nextAutoIncreaseAt;
    if (nextAt == null) return;
    final remaining = nextAt.difference(DateTime.now());
    if (mounted) {
      setState(() {
        _timeUntilIncrease = remaining.isNegative ? Duration.zero : remaining;
      });
    }
    if (remaining.isNegative) {
      _priceCountdownTimer?.cancel();
    }
  }

  /// 输入框数量变化监听
  void _onQuantityChanged() {
    final text = _quantityController.text;
    if (text.isEmpty) {
      setState(() {
        _quantity = 0;
        _showExceedWarning = false;
      });
      return;
    }

    final inputQty = int.tryParse(text) ?? 0;
    setState(() {
      _quantity = inputQty;
      _showExceedWarning = inputQty > _maxQuantity;
    });
  }

  /// 更新输入框显示的数量
  void _updateQuantityText(int qty) {
    final newText = qty > 0 ? qty.toString() : '';
    if (_quantityController.text != newText) {
      _quantityController.text = newText;
      // 将光标移到末尾
      _quantityController.selection = TextSelection.fromPosition(
        TextPosition(offset: newText.length),
      );
    }
  }

  /// 加载用户余额
  Future<void> _loadBalance() async {
    setState(() {
      _isLoading = true;
      _errorMessage = null;
    });

    try {
      // 从 wallet-service 获取用户钱包余额
      final walletService = ref.read(walletServiceProvider);
      final walletResponse = await walletService.getMyWallet();

      // 使用钱包中的 USDT 可用余额
      final totalBalance = walletResponse.balances.usdt.available;

      // 计算最大可认种数量并自动填入
      final maxQty = (totalBalance / _pricePerTree).floor();

      setState(() {
        _availableBalance = totalBalance;
        // 自动填入最大可认种数量，至少为1（如果有足够余额）
        _quantity = maxQty > 0 ? maxQty : 0;
        _isLoading = false;
        _showExceedWarning = false;
      });
      // 更新输入框
      _updateQuantityText(_quantity);
    } catch (e) {
      debugPrint('加载余额失败: $e');
      setState(() {
        _isLoading = false;
        _errorMessage = '加载余额失败，请重试';
        _availableBalance = 0.0;
        _quantity = 0;
      });
    }
  }

  /// 最大可认种数量
  int get _maxQuantity {
    return (_availableBalance / _pricePerTree).floor();
  }

  /// 减少数量
  void _decreaseQuantity() {
    if (_quantity > 1) {
      final newQty = _quantity - 1;
      setState(() {
        _quantity = newQty;
        _showExceedWarning = false;
      });
      _updateQuantityText(newQty);
    }
  }

  /// 增加数量
  void _increaseQuantity() {
    if (_quantity < _maxQuantity) {
      final newQty = _quantity + 1;
      setState(() {
        _quantity = newQty;
        _showExceedWarning = false;
      });
      _updateQuantityText(newQty);
    }
  }

  /// 是否可以减少
  bool get _canDecrease => _quantity > 1;

  /// 是否可以增加
  bool get _canIncrease => _quantity < _maxQuantity;

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

  /// 下一步：创建订单并选择省市
  Future<void> _goToNextStep() async {
    if (_quantity <= 0 || _quantity > _maxQuantity || _isCreatingOrder) {
      return;
    }

    setState(() => _isCreatingOrder = true);

    try {
      // 1. 调用 API 创建订单
      final plantingService = ref.read(plantingServiceProvider);
      final response = await plantingService.createOrder(_quantity);

      if (mounted) {
        // 2. 跳转到省市选择页面，传递订单号
        context.push(
          RoutePaths.plantingLocation,
          extra: PlantingLocationParams(
            quantity: _quantity,
            totalPrice: _quantity * _pricePerTree,
            orderNo: response.orderNo,
          ),
        );
      }
    } catch (e) {
      debugPrint('创建订单失败: $e');
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('创建订单失败: $e'),
            backgroundColor: Colors.red,
          ),
        );
      }
    } finally {
      if (mounted) {
        setState(() => _isCreatingOrder = false);
      }
    }
  }

  /// 格式化数字显示
  String _formatNumber(double number) {
    final parts = number.toStringAsFixed(2).split('.');
    final intPart = parts[0].replaceAllMapped(
      RegExp(r'(\d{1,3})(?=(\d{3})+(?!\d))'),
      (Match m) => '${m[1]},',
    );
    return '$intPart.${parts[1]}';
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: const BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [
              Color(0xFFFFF7E6),
              Color(0xFFEAE0C8),
            ],
          ),
        ),
        child: SafeArea(
          child: Column(
            children: [
              // 顶部导航栏
              _buildHeader(),
              // 内容区域
              Expanded(
                child: SingleChildScrollView(
                  child: Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 16),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        const SizedBox(height: 16),
                        // 余额卡片
                        _buildBalanceCard(),
                        const SizedBox(height: 24),
                        // 输入认种数量标题
                        _buildSectionTitle(),
                        const SizedBox(height: 8),
                        // 数量选择器
                        _buildQuantitySelector(),
                        const SizedBox(height: 8),
                        // 价格信息
                        _buildPriceInfo(),
                      ],
                    ),
                  ),
                ),
              ),
              // 底部按钮
              _buildBottomButton(),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建顶部导航栏
  Widget _buildHeader() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      decoration: BoxDecoration(
        color: const Color(0xFFFFF7E6).withValues(alpha: 0.8),
      ),
      child: Row(
        children: [
          // 返回按钮
          GestureDetector(
            onTap: _goBack,
            child: Container(
              width: 32,
              height: 32,
              alignment: Alignment.center,
              child: const Icon(
                Icons.arrow_back_ios,
                color: Color(0xFFD4AF37),
                size: 20,
              ),
            ),
          ),
          const SizedBox(width: 4),
          // 返回文字
          GestureDetector(
            onTap: _goBack,
            child: const Text(
              '返回',
              style: TextStyle(
                fontSize: 16,
                fontFamily: 'Inter',
                height: 1.5,
                color: Color(0xFFD4AF37),
              ),
            ),
          ),
          const SizedBox(width: 42),
          // 标题
          const Expanded(
            child: Text(
              '认种 Planting',
              style: TextStyle(
                fontSize: 18,
                fontFamily: 'Inter',
                fontWeight: FontWeight.w700,
                height: 1.25,
                letterSpacing: -0.27,
                color: Color(0xFF5D4037),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建余额卡片
  Widget _buildBalanceCard() {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: const Color(0x99FFFFFF),
        borderRadius: BorderRadius.circular(12),
        boxShadow: const [
          BoxShadow(
            color: Color(0x1A000000),
            blurRadius: 6,
            offset: Offset(0, 4),
          ),
          BoxShadow(
            color: Color(0x1A000000),
            blurRadius: 4,
            offset: Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 标签行（包含刷新按钮）
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              const Text(
                '可用余额 (绿积分)',
                style: TextStyle(
                  fontSize: 16,
                  fontFamily: 'Inter',
                  height: 1.5,
                  color: Color(0xFF745D43),
                ),
              ),
              // 刷新按钮
              if (!_isLoading)
                GestureDetector(
                  onTap: _loadBalance,
                  child: const Icon(
                    Icons.refresh,
                    color: Color(0xFFD4AF37),
                    size: 20,
                  ),
                ),
            ],
          ),
          const SizedBox(height: 3),
          // 余额数值或错误信息
          _isLoading
              ? const SizedBox(
                  height: 45,
                  child: Center(
                    child: CircularProgressIndicator(
                      strokeWidth: 2,
                      color: Color(0xFFD4AF37),
                    ),
                  ),
                )
              : _errorMessage != null
                  ? GestureDetector(
                      onTap: _loadBalance,
                      child: SizedBox(
                        height: 45,
                        child: Row(
                          children: [
                            const Icon(
                              Icons.error_outline,
                              color: Color(0xFFE65100),
                              size: 24,
                            ),
                            const SizedBox(width: 8),
                            Text(
                              _errorMessage!,
                              style: const TextStyle(
                                fontSize: 14,
                                color: Color(0xFFE65100),
                              ),
                            ),
                            const SizedBox(width: 8),
                            const Text(
                              '点击重试',
                              style: TextStyle(
                                fontSize: 14,
                                color: Color(0xFFD4AF37),
                                fontWeight: FontWeight.w600,
                              ),
                            ),
                          ],
                        ),
                      ),
                    )
                  : FittedBox(
                      fit: BoxFit.scaleDown,
                      child: Text(
                        _formatNumber(_availableBalance),
                        style: const TextStyle(
                          fontSize: 36,
                          fontFamily: 'Inter',
                          fontWeight: FontWeight.w400,
                          height: 1.25,
                          letterSpacing: -0.54,
                          color: Color(0xFF5D4037),
                        ),
                      ),
                    ),
        ],
      ),
    );
  }

  /// 构建区域标题
  Widget _buildSectionTitle() {
    return Padding(
      padding: const EdgeInsets.only(top: 24),
      child: const Text(
        '输入认种数量',
        style: TextStyle(
          fontSize: 24,
          fontFamily: 'Inter',
          fontWeight: FontWeight.w400,
          height: 1.25,
          color: Color(0xFF5D4037),
        ),
      ),
    );
  }

  /// 构建数量选择器
  Widget _buildQuantitySelector() {
    return Column(
      children: [
        Container(
          width: double.infinity,
          padding: const EdgeInsets.all(24),
          decoration: BoxDecoration(
            color: const Color(0x99FFFFFF),
            borderRadius: BorderRadius.circular(12),
            boxShadow: const [
              BoxShadow(
                color: Color(0x1A000000),
                blurRadius: 6,
                offset: Offset(0, 4),
              ),
              BoxShadow(
                color: Color(0x1A000000),
                blurRadius: 4,
                offset: Offset(0, 2),
              ),
            ],
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              // 减少按钮
              _buildQuantityButton(
                icon: '-',
                onTap: _canDecrease ? _decreaseQuantity : null,
                enabled: _canDecrease,
              ),
              const SizedBox(width: 24),
              // 数量输入框
              SizedBox(
                width: 80,
                child: TextField(
                  controller: _quantityController,
                  focusNode: _quantityFocusNode,
                  keyboardType: TextInputType.number,
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    fontSize: 36,
                    fontFamily: 'Inter',
                    fontWeight: FontWeight.w400,
                    height: 1.5,
                    color: _showExceedWarning
                        ? const Color(0xFFE65100)
                        : const Color(0xFF5D4037),
                  ),
                  decoration: InputDecoration(
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(8),
                      borderSide: BorderSide(
                        color: _showExceedWarning
                            ? const Color(0xFFE65100)
                            : const Color(0xFFD4AF37),
                        width: 1,
                      ),
                    ),
                    enabledBorder: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(8),
                      borderSide: BorderSide(
                        color: _showExceedWarning
                            ? const Color(0xFFE65100)
                            : const Color(0xFFD4AF37),
                        width: 1,
                      ),
                    ),
                    focusedBorder: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(8),
                      borderSide: BorderSide(
                        color: _showExceedWarning
                            ? const Color(0xFFE65100)
                            : const Color(0xFFD4AF37),
                        width: 2,
                      ),
                    ),
                    contentPadding: const EdgeInsets.symmetric(
                      horizontal: 8,
                      vertical: 8,
                    ),
                    isDense: true,
                  ),
                ),
              ),
              const SizedBox(width: 24),
              // 增加按钮
              _buildQuantityButton(
                icon: '+',
                onTap: _canIncrease ? _increaseQuantity : null,
                enabled: _canIncrease,
              ),
            ],
          ),
        ),
        // 超出警告提示
        if (_showExceedWarning)
          Padding(
            padding: const EdgeInsets.only(top: 12),
            child: Container(
              width: double.infinity,
              padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
              decoration: BoxDecoration(
                color: const Color(0xFFFFF3E0),
                borderRadius: BorderRadius.circular(8),
                border: Border.all(
                  color: const Color(0xFFE65100),
                  width: 1,
                ),
              ),
              child: Row(
                children: [
                  const Icon(
                    Icons.warning_amber_rounded,
                    color: Color(0xFFE65100),
                    size: 20,
                  ),
                  const SizedBox(width: 8),
                  Expanded(
                    child: Text(
                      '输入数量 $_quantity 超过最大可认种数量 $_maxQuantity，请调整',
                      style: const TextStyle(
                        fontSize: 14,
                        fontFamily: 'Inter',
                        height: 1.5,
                        color: Color(0xFFE65100),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
      ],
    );
  }

  /// 构建数量调节按钮
  Widget _buildQuantityButton({
    required String icon,
    required VoidCallback? onTap,
    required bool enabled,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        width: 48,
        height: 48,
        decoration: BoxDecoration(
          color: const Color(0xFFFFF7E6),
          borderRadius: BorderRadius.circular(9999),
          boxShadow: const [
            BoxShadow(
              color: Color(0x1A000000),
              blurRadius: 3,
              offset: Offset(0, 1),
            ),
            BoxShadow(
              color: Color(0x1A000000),
              blurRadius: 2,
              offset: Offset(0, 1),
            ),
          ],
        ),
        child: Opacity(
          opacity: enabled ? 1.0 : 0.4,
          child: Center(
            child: Text(
              icon,
              style: const TextStyle(
                fontSize: 30,
                fontFamily: 'Inter',
                fontWeight: FontWeight.w400,
                height: 1.5,
                color: Color(0xFF745D43),
              ),
            ),
          ),
        ),
      ),
    );
  }

  /// 构建价格信息
  Widget _buildPriceInfo() {
    final calculationResult = (_availableBalance / _pricePerTree).toStringAsFixed(2);

    return Padding(
      padding: const EdgeInsets.only(top: 8),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 每棵价格
          Text(
            '每棵价格：${_pricePerTree.toInt()} 绿积分',
            style: const TextStyle(
              fontSize: 16,
              fontFamily: 'Inter',
              height: 1.5,
              color: Color(0xFF000000),
            ),
          ),
          const SizedBox(height: 7),
          // 最大可认种
          Text(
            '最大可认种：$_maxQuantity 棵 (根据余额自动计算)',
            style: const TextStyle(
              fontSize: 16,
              fontFamily: 'Inter',
              height: 1.5,
              color: Color(0xFF000000),
            ),
          ),
          const SizedBox(height: 7),
          // 计算说明
          Text(
            '（计算: ${_formatNumber(_availableBalance).replaceAll('.00', '')} \u00f7 ${_pricePerTree.toInt()} = $calculationResult \u2192 向下取整为 $_maxQuantity）',
            style: const TextStyle(
              fontSize: 14,
              fontFamily: 'Inter',
              height: 1.5,
              color: Color(0xFF000000),
            ),
          ),
          // 下次涨价倒计时预告
          if (_pricingConfig != null &&
              _pricingConfig!.autoIncreaseEnabled &&
              _pricingConfig!.nextAutoIncreaseAt != null) ...[
            const SizedBox(height: 12),
            Container(
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: const Color(0xFFFFF3E0),
                borderRadius: BorderRadius.circular(8),
                border: Border.all(color: const Color(0xFFFFCC80), width: 0.5),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 倒计时行
                  Row(
                    children: [
                      const Icon(
                        Icons.timer_outlined,
                        color: Color(0xFFE65100),
                        size: 18,
                      ),
                      const SizedBox(width: 6),
                      Expanded(
                        child: Text(
                          _timeUntilIncrease == Duration.zero
                              ? '涨价时间已到，价格即将更新'
                              : '距下次涨价还有 ${_timeUntilIncrease.inDays}天 ${_timeUntilIncrease.inHours % 24}小时 ${_timeUntilIncrease.inMinutes % 60}分钟',
                          style: const TextStyle(
                            fontSize: 14,
                            fontFamily: 'Inter',
                            fontWeight: FontWeight.w600,
                            height: 1.4,
                            color: Color(0xFFE65100),
                          ),
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 6),
                  // 涨价后价格
                  Row(
                    children: [
                      const Icon(
                        Icons.trending_up,
                        color: Color(0xFFE65100),
                        size: 16,
                      ),
                      const SizedBox(width: 6),
                      Expanded(
                        child: Text(
                          '涨价后每棵: ${(_pricingConfig!.totalPrice + _pricingConfig!.autoIncreaseAmount).toInt()} 绿积分 (+${_pricingConfig!.autoIncreaseAmount.toInt()})',
                          style: const TextStyle(
                            fontSize: 13,
                            fontFamily: 'Inter',
                            height: 1.4,
                            color: Color(0xFFBF360C),
                          ),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ],
        ],
      ),
    );
  }

  /// 构建底部按钮
  Widget _buildBottomButton() {
    final bool canProceed = _quantity > 0 && _quantity <= _maxQuantity && !_isLoading && !_isCreatingOrder;

    return Container(
      padding: const EdgeInsets.fromLTRB(16, 16, 16, 24),
      child: GestureDetector(
        onTap: canProceed ? _goToNextStep : null,
        child: Container(
          width: double.infinity,
          height: 56,
          decoration: BoxDecoration(
            color: canProceed
                ? const Color(0xFFD4AF37)
                : const Color(0xFFD4AF37).withValues(alpha: 0.5),
            borderRadius: BorderRadius.circular(12),
            boxShadow: canProceed
                ? const [
                    BoxShadow(
                      color: Color(0x1A000000),
                      blurRadius: 15,
                      offset: Offset(0, 10),
                    ),
                    BoxShadow(
                      color: Color(0x1A000000),
                      blurRadius: 6,
                      offset: Offset(0, 4),
                    ),
                  ]
                : null,
          ),
          child: Center(
            child: _isCreatingOrder
                ? const SizedBox(
                    width: 24,
                    height: 24,
                    child: CircularProgressIndicator(
                      strokeWidth: 2,
                      color: Colors.white,
                    ),
                  )
                : const Text(
                    '下一步：选择省市',
                    style: TextStyle(
                      fontSize: 18,
                      fontFamily: 'Inter',
                      fontWeight: FontWeight.w500,
                      height: 1.56,
                      color: Colors.white,
                    ),
                  ),
          ),
        ),
      ),
    );
  }
}

/// 认种数量参数 - 传递给下一个页面
class PlantingQuantityParams {
  final int quantity;
  final double totalPrice;

  PlantingQuantityParams({
    required this.quantity,
    required this.totalPrice,
  });
}
