import 'dart:math';
import 'package:flutter/material.dart';
import '../../../../app/theme/app_colors.dart';
import '../../../../app/theme/app_typography.dart';
import '../../../../app/theme/app_spacing.dart';
import '../../../../app/i18n/app_localizations.dart';

/// 券交易详情页 - 币安风格
///
/// 券信息卡片 + K线图 + OHLC + 交易深度 + 买卖盘口 + 下单
/// 计价货币由用户在"我的→设置"中配置，默认跟随语言
class TradingDetailPage extends StatefulWidget {
  const TradingDetailPage({super.key});

  @override
  State<TradingDetailPage> createState() => _TradingDetailPageState();
}

class _TradingDetailPageState extends State<TradingDetailPage>
    with SingleTickerProviderStateMixin {
  String _selectedPeriod = '1D';
  bool _isBuy = true;
  String _orderType = 'limit'; // limit, market
  late TabController _bottomTabController;

  // Mock coupon data (实际从路由参数或状态管理获取)
  final _coupon = const _CouponInfo(
    couponName: '星巴克\$25 礼品卡',
    brandName: 'Starbucks',
    categoryLabel: '餐饮',
    faceValue: 25.0,
    currentPrice: 21.30,
    change24h: 2.05,
    creditRating: 'AAA',
    expiryDate: '2026/06/30',
  );

  // 计价货币符号 (从用户设置读取)
  final String _currencySymbol = '\$';

  @override
  void initState() {
    super.initState();
    _bottomTabController = TabController(length: 2, vsync: this);
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(_coupon.couponName),
        actions: [
          IconButton(
            icon: const Icon(Icons.star_border_rounded, size: 22),
            onPressed: () {},
          ),
          IconButton(
            icon: const Icon(Icons.share_rounded, size: 22),
            onPressed: () {},
          ),
        ],
      ),
      body: Column(
        children: [
          Expanded(
            child: SingleChildScrollView(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // Coupon info card
                  _buildCouponInfoCard(),

                  // Price header
                  _buildPriceHeader(),

                  // K-line chart
                  _buildKlineChart(),

                  // Period selector
                  _buildPeriodSelector(),

                  const SizedBox(height: 16),

                  // Order book + Recent trades
                  _buildOrderBookSection(),

                  const SizedBox(height: 16),

                  // Buy/Sell order form
                  _buildOrderForm(),

                  const SizedBox(height: 16),

                  // My orders
                  _buildMyOrders(),

                  const SizedBox(height: 100),
                ],
              ),
            ),
          ),
        ],
      ),

      // Bottom buy/sell bar
      bottomNavigationBar: _buildBottomBar(),
    );
  }

  // ============================================================
  // Coupon Info Card - 券基本信息
  // ============================================================
  Widget _buildCouponInfoCard() {
    return Container(
      margin: const EdgeInsets.fromLTRB(20, 8, 20, 0),
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: AppColors.primarySurface,
        borderRadius: AppSpacing.borderRadiusMd,
        border: Border.all(color: AppColors.primary.withValues(alpha: 0.15)),
      ),
      child: Row(
        children: [
          // Icon
          Container(
            width: 40,
            height: 40,
            decoration: BoxDecoration(
              color: AppColors.surface,
              borderRadius: AppSpacing.borderRadiusSm,
            ),
            child: const Icon(Icons.confirmation_number_outlined,
                color: AppColors.primary, size: 20),
          ),
          const SizedBox(width: 12),
          // Info
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Text(_coupon.brandName,
                        style: AppTypography.labelMedium),
                    const SizedBox(width: 6),
                    Container(
                      padding: const EdgeInsets.symmetric(
                          horizontal: 5, vertical: 1),
                      decoration: BoxDecoration(
                        color: AppColors.gray100,
                        borderRadius: AppSpacing.borderRadiusFull,
                      ),
                      child: Text(_coupon.categoryLabel,
                          style:
                              AppTypography.caption.copyWith(fontSize: 10)),
                    ),
                    const SizedBox(width: 6),
                    Container(
                      padding: const EdgeInsets.symmetric(
                          horizontal: 5, vertical: 1),
                      decoration: BoxDecoration(
                        color: AppColors.success.withValues(alpha: 0.1),
                        borderRadius: AppSpacing.borderRadiusFull,
                      ),
                      child: Text(_coupon.creditRating,
                          style: AppTypography.caption.copyWith(
                            fontSize: 10,
                            color: AppColors.success,
                            fontWeight: FontWeight.w600,
                          )),
                    ),
                  ],
                ),
                const SizedBox(height: 2),
                Text(
                  '${context.t('market.faceValue')} $_currencySymbol${_coupon.faceValue.toStringAsFixed(0)} · ${context.t('market.expiryDate')} ${_coupon.expiryDate}',
                  style: AppTypography.caption,
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // ============================================================
  // Price Header - OHLC + 24h stats
  // ============================================================
  Widget _buildPriceHeader() {
    final isPositive = _coupon.change24h >= 0;
    final changeColor = isPositive ? AppColors.success : AppColors.error;
    final changePrefix = isPositive ? '+' : '';

    return Padding(
      padding: const EdgeInsets.fromLTRB(20, 16, 20, 0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // Current price + change
          Row(
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              Text(
                '$_currencySymbol${_coupon.currentPrice.toStringAsFixed(2)}',
                style: AppTypography.priceLarge.copyWith(
                  color: changeColor,
                  fontSize: 32,
                ),
              ),
              const SizedBox(width: 8),
              Text(
                '${context.t('trading.discountLabel')} ${(_coupon.currentPrice / _coupon.faceValue * 10).toStringAsFixed(1)}${context.t('market.discountSuffix')}',
                style: AppTypography.bodySmall.copyWith(
                  color: AppColors.textTertiary,
                ),
              ),
              const Spacer(),
              Container(
                padding:
                    const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
                decoration: BoxDecoration(
                  color: changeColor,
                  borderRadius: AppSpacing.borderRadiusSm,
                ),
                child: Text(
                  '$changePrefix${_coupon.change24h.toStringAsFixed(2)}%',
                  style: AppTypography.labelSmall.copyWith(
                    color: Colors.white,
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ),
            ],
          ),

          const SizedBox(height: 12),

          // 24h OHLC stats
          Row(
            children: [
              _buildOhlcStat(context.t('trading.high24h'), '${_currencySymbol}21.75', AppColors.error),
              _buildOhlcStat(context.t('trading.low24h'), '${_currencySymbol}20.85', AppColors.success),
              _buildOhlcStat(context.t('trading.open'), '${_currencySymbol}20.87', AppColors.textPrimary),
              _buildOhlcStat(context.t('trading.vol24h'), '342.5K', AppColors.textPrimary),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildOhlcStat(String label, String value, Color valueColor) {
    return Expanded(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(label, style: AppTypography.caption),
          const SizedBox(height: 2),
          Text(
            value,
            style: AppTypography.labelSmall.copyWith(
              color: valueColor,
              fontWeight: FontWeight.w600,
            ),
          ),
        ],
      ),
    );
  }

  // ============================================================
  // K-line Chart (placeholder)
  // ============================================================
  Widget _buildKlineChart() {
    return Container(
      height: 220,
      margin: const EdgeInsets.fromLTRB(20, 16, 20, 0),
      decoration: BoxDecoration(
        color: AppColors.gray50,
        borderRadius: AppSpacing.borderRadiusMd,
        border: Border.all(color: AppColors.borderLight),
      ),
      child: Stack(
        children: [
          // Mock candlestick chart
          CustomPaint(
            size: const Size(double.infinity, 220),
            painter: _CandlestickPainter(),
          ),
          // Label
          Positioned(
            top: 8,
            left: 12,
            child: Text(
              '${_coupon.couponName} · $_selectedPeriod',
              style: AppTypography.caption.copyWith(
                color: AppColors.textTertiary,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildPeriodSelector() {
    final periods = ['1m', '5m', '15m', '1h', '4h', '1D', '1W'];
    return Padding(
      padding: const EdgeInsets.fromLTRB(20, 8, 20, 0),
      child: Row(
        children: periods.map((period) {
          final isSelected = _selectedPeriod == period;
          return Expanded(
            child: GestureDetector(
              onTap: () => setState(() => _selectedPeriod = period),
              child: Container(
                padding: const EdgeInsets.symmetric(vertical: 6),
                margin: const EdgeInsets.symmetric(horizontal: 2),
                decoration: BoxDecoration(
                  color:
                      isSelected ? AppColors.primary : Colors.transparent,
                  borderRadius: AppSpacing.borderRadiusSm,
                ),
                alignment: Alignment.center,
                child: Text(
                  period,
                  style: AppTypography.caption.copyWith(
                    color:
                        isSelected ? Colors.white : AppColors.textTertiary,
                    fontWeight:
                        isSelected ? FontWeight.w600 : FontWeight.w400,
                  ),
                ),
              ),
            ),
          );
        }).toList(),
      ),
    );
  }

  // ============================================================
  // Order Book (Bid/Ask depth)
  // ============================================================
  Widget _buildOrderBookSection() {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 20),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(context.t('trading.depth'), style: AppTypography.h3),
          const SizedBox(height: 12),
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // Asks (sell orders) - red
              Expanded(child: _buildOrderBookSide(isAsk: true)),
              const SizedBox(width: 12),
              // Bids (buy orders) - green
              Expanded(child: _buildOrderBookSide(isAsk: false)),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildOrderBookSide({required bool isAsk}) {
    final color = isAsk ? AppColors.error : AppColors.success;
    final label = isAsk ? context.t('trading.askSide') : context.t('trading.bidSide');
    final prices = isAsk
        ? [21.45, 21.42, 21.40, 21.38, 21.35]
        : [21.28, 21.25, 21.22, 21.20, 21.18];
    final amounts = isAsk
        ? [120, 85, 200, 45, 310]
        : [95, 150, 180, 60, 250];

    final maxAmount = [...amounts].reduce((a, b) => a > b ? a : b);

    return Column(
      children: [
        // Header
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(label, style: AppTypography.caption.copyWith(color: color)),
            Text(context.t('trading.quantitySheets'), style: AppTypography.caption),
          ],
        ),
        const SizedBox(height: 6),
        ...List.generate(prices.length, (i) {
          final ratio = amounts[i] / maxAmount;
          return Container(
            margin: const EdgeInsets.only(bottom: 2),
            child: Stack(
              children: [
                // Depth bar background
                Positioned.fill(
                  child: FractionallySizedBox(
                    alignment:
                        isAsk ? Alignment.centerRight : Alignment.centerLeft,
                    widthFactor: ratio,
                    child: Container(
                      decoration: BoxDecoration(
                        color: color.withValues(alpha: 0.08),
                        borderRadius: BorderRadius.circular(2),
                      ),
                    ),
                  ),
                ),
                // Price + Amount
                Padding(
                  padding: const EdgeInsets.symmetric(vertical: 4),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        '$_currencySymbol${prices[i].toStringAsFixed(2)}',
                        style: AppTypography.caption.copyWith(
                          color: color,
                          fontWeight: FontWeight.w500,
                          fontFamily: 'monospace',
                        ),
                      ),
                      Text(
                        '${amounts[i]}',
                        style: AppTypography.caption.copyWith(
                          fontFamily: 'monospace',
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          );
        }),
      ],
    );
  }

  // ============================================================
  // Order Form (Buy / Sell)
  // ============================================================
  Widget _buildOrderForm() {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 20),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(context.t('trading.placeOrder'), style: AppTypography.h3),
          const SizedBox(height: 12),

          // Buy/Sell toggle
          Container(
            decoration: BoxDecoration(
              color: AppColors.gray50,
              borderRadius: AppSpacing.borderRadiusFull,
            ),
            child: Row(
              children: [
                Expanded(
                  child: GestureDetector(
                    onTap: () => setState(() => _isBuy = true),
                    child: Container(
                      padding: const EdgeInsets.symmetric(vertical: 10),
                      decoration: BoxDecoration(
                        color: _isBuy ? AppColors.success : Colors.transparent,
                        borderRadius: AppSpacing.borderRadiusFull,
                      ),
                      alignment: Alignment.center,
                      child: Text(
                        context.t('trading.buy'),
                        style: AppTypography.labelMedium.copyWith(
                          color: _isBuy ? Colors.white : AppColors.textTertiary,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                    ),
                  ),
                ),
                Expanded(
                  child: GestureDetector(
                    onTap: () => setState(() => _isBuy = false),
                    child: Container(
                      padding: const EdgeInsets.symmetric(vertical: 10),
                      decoration: BoxDecoration(
                        color:
                            !_isBuy ? AppColors.error : Colors.transparent,
                        borderRadius: AppSpacing.borderRadiusFull,
                      ),
                      alignment: Alignment.center,
                      child: Text(
                        context.t('trading.sell'),
                        style: AppTypography.labelMedium.copyWith(
                          color:
                              !_isBuy ? Colors.white : AppColors.textTertiary,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),

          const SizedBox(height: 12),

          // Order type selector
          Row(
            children: [
              _buildOrderTypeChip(context.t('trading.limitOrder'), 'limit'),
              const SizedBox(width: 8),
              _buildOrderTypeChip(context.t('trading.marketOrder'), 'market'),
            ],
          ),

          const SizedBox(height: 12),

          // Price input (hidden for market orders)
          if (_orderType == 'limit') ...[
            _buildInputField(context.t('trading.price'), '21.30', _currencySymbol),
            const SizedBox(height: 8),
          ],

          // Amount input
          _buildInputField(context.t('trading.quantity'), '', context.t('trading.sheetsUnit')),

          const SizedBox(height: 8),

          // Amount slider (25% / 50% / 75% / 100%)
          Row(
            children: [
              _buildPercentChip('25%'),
              const SizedBox(width: 6),
              _buildPercentChip('50%'),
              const SizedBox(width: 6),
              _buildPercentChip('75%'),
              const SizedBox(width: 6),
              _buildPercentChip('100%'),
            ],
          ),

          const SizedBox(height: 12),

          // Available balance
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(context.t('trading.available'), style: AppTypography.caption),
              Text(
                _isBuy
                    ? '${_currencySymbol}1,234.56'
                    : '3 ${context.t('trading.sheetsUnit')} ${_coupon.couponName}',
                style: AppTypography.caption.copyWith(
                  color: AppColors.textPrimary,
                  fontWeight: FontWeight.w500,
                ),
              ),
            ],
          ),

          const SizedBox(height: 12),

          // Submit button
          SizedBox(
            width: double.infinity,
            height: 48,
            child: ElevatedButton(
              onPressed: () {},
              style: ElevatedButton.styleFrom(
                backgroundColor:
                    _isBuy ? AppColors.success : AppColors.error,
                foregroundColor: Colors.white,
                shape: RoundedRectangleBorder(
                  borderRadius: AppSpacing.borderRadiusMd,
                ),
              ),
              child: Text(
                _isBuy ? '${context.t('trading.buy')} ${_coupon.couponName}' : '${context.t('trading.sell')} ${_coupon.couponName}',
                style: AppTypography.labelLarge.copyWith(color: Colors.white),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildOrderTypeChip(String label, String type) {
    final isSelected = _orderType == type;
    return GestureDetector(
      onTap: () => setState(() => _orderType = type),
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 6),
        decoration: BoxDecoration(
          color: isSelected ? AppColors.primarySurface : AppColors.gray50,
          borderRadius: AppSpacing.borderRadiusFull,
          border: Border.all(
            color: isSelected
                ? AppColors.primary.withValues(alpha: 0.3)
                : AppColors.borderLight,
          ),
        ),
        child: Text(
          label,
          style: AppTypography.labelSmall.copyWith(
            color: isSelected ? AppColors.primary : AppColors.textSecondary,
            fontWeight: isSelected ? FontWeight.w600 : FontWeight.w400,
          ),
        ),
      ),
    );
  }

  Widget _buildInputField(String label, String hint, String suffix) {
    return Container(
      height: 44,
      padding: const EdgeInsets.symmetric(horizontal: 12),
      decoration: BoxDecoration(
        color: AppColors.gray50,
        borderRadius: AppSpacing.borderRadiusSm,
        border: Border.all(color: AppColors.borderLight),
      ),
      child: Row(
        children: [
          SizedBox(
            width: 40,
            child: Text(label, style: AppTypography.caption),
          ),
          Expanded(
            child: TextField(
              decoration: InputDecoration(
                hintText: hint,
                hintStyle: AppTypography.bodyMedium.copyWith(
                  color: AppColors.textTertiary,
                ),
                border: InputBorder.none,
                isDense: true,
                contentPadding: EdgeInsets.zero,
              ),
              keyboardType:
                  const TextInputType.numberWithOptions(decimal: true),
              style: AppTypography.bodyMedium.copyWith(
                fontFamily: 'monospace',
              ),
            ),
          ),
          Text(
            suffix,
            style: AppTypography.caption.copyWith(
              color: AppColors.textSecondary,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildPercentChip(String label) {
    return Expanded(
      child: GestureDetector(
        onTap: () {},
        child: Container(
          padding: const EdgeInsets.symmetric(vertical: 6),
          decoration: BoxDecoration(
            color: AppColors.gray50,
            borderRadius: AppSpacing.borderRadiusSm,
            border: Border.all(color: AppColors.borderLight),
          ),
          alignment: Alignment.center,
          child: Text(label, style: AppTypography.caption),
        ),
      ),
    );
  }

  // ============================================================
  // My Orders
  // ============================================================
  Widget _buildMyOrders() {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 20),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(context.t('trading.currentOrders'), style: AppTypography.h3),
              GestureDetector(
                onTap: () {},
                child: Text(context.t('trading.historyOrders'),
                    style: AppTypography.labelSmall
                        .copyWith(color: AppColors.primary)),
              ),
            ],
          ),
          const SizedBox(height: 12),

          // Mock orders
          _buildOrderItem(
              context.t('trading.buy'), _coupon.couponName, '21.20', '5', context.t('trading.limitOrder'), AppColors.success),
          const Divider(height: 1),
          _buildOrderItem(
              context.t('trading.sell'), _coupon.couponName, '21.50', '2', context.t('trading.limitOrder'), AppColors.error),
        ],
      ),
    );
  }

  Widget _buildOrderItem(String side, String couponName, String price,
      String amount, String type, Color sideColor) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 12),
      child: Row(
        children: [
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
            decoration: BoxDecoration(
              color: sideColor.withValues(alpha: 0.1),
              borderRadius: AppSpacing.borderRadiusFull,
            ),
            child: Text(
              side,
              style: AppTypography.caption.copyWith(
                color: sideColor,
                fontWeight: FontWeight.w600,
              ),
            ),
          ),
          const SizedBox(width: 10),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(couponName, style: AppTypography.labelSmall),
                Text('$type · ${amount}${context.t('trading.sheetsUnit')} @ $_currencySymbol$price',
                    style: AppTypography.caption),
              ],
            ),
          ),
          GestureDetector(
            onTap: () {},
            child: Container(
              padding:
                  const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
              decoration: BoxDecoration(
                border: Border.all(color: AppColors.borderLight),
                borderRadius: AppSpacing.borderRadiusFull,
              ),
              child: Text(context.t('trading.cancelOrder'),
                  style: AppTypography.caption
                      .copyWith(color: AppColors.textSecondary)),
            ),
          ),
        ],
      ),
    );
  }

  // ============================================================
  // Bottom Bar
  // ============================================================
  Widget _buildBottomBar() {
    return Container(
      padding: const EdgeInsets.fromLTRB(20, 12, 20, 24),
      decoration: const BoxDecoration(
        color: AppColors.surface,
        border: Border(top: BorderSide(color: AppColors.borderLight)),
      ),
      child: Row(
        children: [
          Expanded(
            child: SizedBox(
              height: 44,
              child: ElevatedButton(
                onPressed: () => setState(() => _isBuy = true),
                style: ElevatedButton.styleFrom(
                  backgroundColor: AppColors.success,
                  foregroundColor: Colors.white,
                  shape: RoundedRectangleBorder(
                    borderRadius: AppSpacing.borderRadiusSm,
                  ),
                ),
                child: Text(context.t('trading.buy'),
                    style: AppTypography.labelMedium
                        .copyWith(color: Colors.white)),
              ),
            ),
          ),
          const SizedBox(width: 12),
          Expanded(
            child: SizedBox(
              height: 44,
              child: ElevatedButton(
                onPressed: () => setState(() => _isBuy = false),
                style: ElevatedButton.styleFrom(
                  backgroundColor: AppColors.error,
                  foregroundColor: Colors.white,
                  shape: RoundedRectangleBorder(
                    borderRadius: AppSpacing.borderRadiusSm,
                  ),
                ),
                child: Text(context.t('trading.sell'),
                    style: AppTypography.labelMedium
                        .copyWith(color: Colors.white)),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

// ============================================================
// Data Model
// ============================================================
class _CouponInfo {
  final String couponName;
  final String brandName;
  final String categoryLabel;
  final double faceValue;
  final double currentPrice;
  final double change24h;
  final String creditRating;
  final String expiryDate;

  const _CouponInfo({
    required this.couponName,
    required this.brandName,
    required this.categoryLabel,
    required this.faceValue,
    required this.currentPrice,
    required this.change24h,
    required this.creditRating,
    required this.expiryDate,
  });
}

// ============================================================
// Mock Candlestick Chart Painter
// ============================================================
class _CandlestickPainter extends CustomPainter {
  final _random = Random(42);

  @override
  void paint(Canvas canvas, Size size) {
    final candleWidth = size.width / 30;
    final padding = 16.0;
    final chartHeight = size.height - padding * 2;

    double prevClose = 21.0;

    for (int i = 0; i < 28; i++) {
      final x = padding + i * candleWidth;

      // Generate OHLC
      final open = prevClose + (_random.nextDouble() - 0.5) * 0.3;
      final close = open + (_random.nextDouble() - 0.5) * 0.4;
      final high = max(open, close) + _random.nextDouble() * 0.2;
      final low = min(open, close) - _random.nextDouble() * 0.2;
      prevClose = close;

      final isGreen = close >= open;
      final color = isGreen ? AppColors.success : AppColors.error;

      // Normalize to chart coordinates (price range 20.5 - 22.0)
      final priceRange = 1.5;
      final minPrice = 20.5;
      double priceToY(double price) {
        return padding + (1 - (price - minPrice) / priceRange) * chartHeight;
      }

      // Draw wick
      canvas.drawLine(
        Offset(x + candleWidth / 2, priceToY(high)),
        Offset(x + candleWidth / 2, priceToY(low)),
        Paint()
          ..color = color
          ..strokeWidth = 1,
      );

      // Draw body
      final bodyTop = priceToY(max(open, close));
      final bodyBottom = priceToY(min(open, close));
      canvas.drawRect(
        Rect.fromLTRB(x + 2, bodyTop, x + candleWidth - 2, bodyBottom),
        Paint()
          ..color = color
          ..style = isGreen ? PaintingStyle.stroke : PaintingStyle.fill
          ..strokeWidth = 1,
      );
    }

    // Volume bars at bottom
    for (int i = 0; i < 28; i++) {
      final x = padding + i * candleWidth;
      final vol = _random.nextDouble() * 0.15 * chartHeight;
      canvas.drawRect(
        Rect.fromLTRB(
          x + 2,
          size.height - padding - vol * 0.3,
          x + candleWidth - 2,
          size.height - padding,
        ),
        Paint()..color = AppColors.gray200,
      );
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}
