import 'dart:math' as math;
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import '../../../domain/entities/kline.dart';

/// 成交量绘制器
class KlineVolumePainter extends CustomPainter {
  final List<Kline> klines;
  final int crossLineIndex;
  final double? candleWidth;
  final bool isDark;  // 深色模式
  final double scrollOffset;  // 滚动偏移（像素）

  static const Color _green = Color(0xFF10B981);
  static const Color _red = Color(0xFFEF4444);

  // 根据主题动态获取颜色
  Color get _gridColor => isDark ? const Color(0xFF374151) : const Color(0xFFE5E7EB);
  Color get _textColor => isDark ? const Color(0xFF9CA3AF) : const Color(0xFF6B7280);
  Color get _crossLineColor => isDark ? const Color(0xFF6B7280) : const Color(0xFF9CA3AF);

  KlineVolumePainter({
    required this.klines,
    this.crossLineIndex = -1,
    this.candleWidth,
    this.isDark = false,
    this.scrollOffset = 0.0,
  });

  @override
  void paint(Canvas canvas, Size size) {
    if (klines.isEmpty) return;

    const leftPadding = 8.0;
    const rightPadding = 50.0;
    const topPadding = 4.0;
    const bottomPadding = 4.0;

    final chartWidth = size.width - leftPadding - rightPadding;
    final chartHeight = size.height - topPadding - bottomPadding;

    // 计算最大成交量
    double maxVolume = 0;
    for (final kline in klines) {
      final volume = double.tryParse(kline.volume) ?? 0;
      if (volume > maxVolume) maxVolume = volume;
    }

    if (maxVolume == 0) maxVolume = 1; // 防止除零

    // 绘制分隔线
    final gridPaint = Paint()
      ..color = _gridColor
      ..strokeWidth = 0.5;
    canvas.drawLine(
      Offset(leftPadding, 0),
      Offset(size.width - rightPadding, 0),
      gridPaint,
    );

    // 绘制成交量标签
    final textPainter = TextPainter(
      text: TextSpan(
        text: 'VOL',
        style: TextStyle(color: _textColor, fontSize: 9),
      ),
      textDirection: ui.TextDirection.ltr,
    );
    textPainter.layout();
    textPainter.paint(canvas, Offset(leftPadding, 2));

    // 最大成交量标签
    final maxVolText = TextPainter(
      text: TextSpan(
        text: _formatVolume(maxVolume),
        style: TextStyle(color: _textColor, fontSize: 8),
      ),
      textDirection: ui.TextDirection.ltr,
    );
    maxVolText.layout();
    maxVolText.paint(canvas, Offset(size.width - rightPadding + 4, topPadding));

    // 绘制成交量柱
    final actualCandleWidth = candleWidth ?? (chartWidth / klines.length);
    final barWidth = math.max(actualCandleWidth * 0.7, 2.0);

    // 裁剪绘图区域
    canvas.save();
    canvas.clipRect(Rect.fromLTRB(leftPadding, 0, size.width - rightPadding, size.height));

    for (int i = 0; i < klines.length; i++) {
      final kline = klines[i];
      final volume = double.tryParse(kline.volume) ?? 0;
      final open = double.tryParse(kline.open) ?? 0;
      final close = double.tryParse(kline.close) ?? 0;

      final isUp = close >= open;
      final color = isUp ? _green : _red;

      final x = leftPadding + i * actualCandleWidth + actualCandleWidth / 2 - scrollOffset;

      // 跳过不在可见区域的柱子
      if (x < leftPadding - actualCandleWidth || x > size.width - rightPadding + actualCandleWidth) {
        continue;
      }

      final barHeight = (volume / maxVolume) * chartHeight;
      final y = size.height - bottomPadding - barHeight;

      // 高亮十字线位置的柱子
      final alpha = (crossLineIndex >= 0 && crossLineIndex != i) ? 0.4 : 1.0;

      canvas.drawRect(
        Rect.fromLTRB(x - barWidth / 2, y, x + barWidth / 2, size.height - bottomPadding),
        Paint()..color = color.withOpacity(alpha),
      );
    }

    canvas.restore();

    // 绘制十字线
    if (crossLineIndex >= 0 && crossLineIndex < klines.length) {
      final x = leftPadding + crossLineIndex * actualCandleWidth + actualCandleWidth / 2 - scrollOffset;
      canvas.drawLine(
        Offset(x, 0),
        Offset(x, size.height),
        Paint()
          ..color = _crossLineColor
          ..strokeWidth = 0.5,
      );

      // 显示选中的成交量
      final volume = double.tryParse(klines[crossLineIndex].volume) ?? 0;
      final volText = TextPainter(
        text: TextSpan(
          text: _formatVolume(volume),
          style: TextStyle(color: _textColor, fontSize: 9, fontWeight: FontWeight.bold),
        ),
        textDirection: ui.TextDirection.ltr,
      );
      volText.layout();
      volText.paint(canvas, Offset(leftPadding + 30, 2));
    }
  }

  String _formatVolume(double volume) {
    if (volume >= 1000000000) return '${(volume / 1000000000).toStringAsFixed(2)}B';
    if (volume >= 1000000) return '${(volume / 1000000).toStringAsFixed(2)}M';
    if (volume >= 1000) return '${(volume / 1000).toStringAsFixed(2)}K';
    return volume.toStringAsFixed(0);
  }

  @override
  bool shouldRepaint(covariant KlineVolumePainter oldDelegate) {
    return oldDelegate.klines != klines ||
        oldDelegate.crossLineIndex != crossLineIndex ||
        oldDelegate.candleWidth != candleWidth ||
        oldDelegate.isDark != isDark ||
        oldDelegate.scrollOffset != scrollOffset;
  }
}
