import 'package:flutter/material.dart';

class MarqueeGradientText extends StatefulWidget {
  final String text;
  final double speed; // 滚动速度（像素/秒）
  final double sweepSpeed; // 扫光速度（单位/秒）
  final double gapWidth; // 滚动时文字间的间距（像素）
  final List<Color> gradientColors;
  final double fontSize;
  final bool needScroll; // 外部控制是否滚动
  final bool needGradient; // 外部控制是否扫光
  final Color textColor;
  final FontWeight? fontWeight;

  const MarqueeGradientText({
    super.key,
    required this.text,
    this.speed = 30,
    this.sweepSpeed = 0.5,
    this.fontSize = 12,
    this.needScroll = false,
    this.needGradient = false,
    this.fontWeight,
    this.textColor = Colors.white,
    this.gapWidth = 80,
    this.gradientColors = const [Colors.red, Colors.yellow, Colors.red],
  });

  @override
  State<MarqueeGradientText> createState() => _MarqueeGradientTextState();
}

class _MarqueeGradientTextState extends State<MarqueeGradientText>
    with TickerProviderStateMixin {
  late ScrollController _scrollController;
  AnimationController? _scrollAnimationController;
  late AnimationController _sweepAnimationController;
  Animation<double>? _scrollAnimation;
  late Animation<double> _sweepAnimation;

  // 不再使用 _fullText 变量，改为计算属性
  String get _fullText {
    if (widget.needScroll) {
      double spaceWidth = widget.fontSize * 0.6; // 估算空格宽度
      int gapSpaces = (widget.gapWidth / spaceWidth).ceil();
      String gap = List.filled(gapSpaces, ' ').join();
      return widget.text + gap + widget.text;
    } else {
      return widget.text;
    }
  }

  @override
  void initState() {
    super.initState();
    _scrollController = ScrollController();
    _initSweepAnimation(); // 初始化扫光动画（仅一次）

    // 首次启动滚动动画（如果需要）
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (mounted && widget.needScroll && _scrollController.hasClients) {
        _startScrollAnimation();
      }
    });
  }

  void _initSweepAnimation() {
    if (widget.needGradient) {
      double cycleSeconds = 4.0 / widget.sweepSpeed;
      _sweepAnimationController = AnimationController(
        vsync: this,
        duration: Duration(milliseconds: (cycleSeconds * 1000).round()),
      );
      _sweepAnimation = Tween<double>(begin: -2.0, end: 2.0).animate(
        CurvedAnimation(parent: _sweepAnimationController, curve: Curves.easeOut),
      );
      _sweepAnimationController.repeat();
    } else {
      _sweepAnimationController = AnimationController(vsync: this, duration: Duration.zero);
      _sweepAnimation = AlwaysStoppedAnimation(-2.0);
    }
  }

  void _startScrollAnimation() {
    // 如果已有动画，先停止并销毁
    _scrollAnimationController?.stop();
    _scrollAnimationController?.dispose();
    _scrollAnimationController = null;

    // 计算滚动距离（拼接文本长度的一半）
    double totalScrollDistance = _scrollController.position.maxScrollExtent / 2;
    if (totalScrollDistance <= 0) return;

    double durationSeconds = totalScrollDistance / widget.speed;
    _scrollAnimationController = AnimationController(
      vsync: this,
      duration: Duration(milliseconds: (durationSeconds * 1000).round()),
    );

    _scrollAnimation = Tween<double>(begin: 0, end: totalScrollDistance).animate(
      CurvedAnimation(parent: _scrollAnimationController!, curve: Curves.easeOut),
    );

    void scrollListener() {
      if (!mounted || !_scrollController.hasClients) return;
      _scrollController.jumpTo(_scrollAnimation!.value);
    }

    _scrollAnimation!.addListener(scrollListener);
    _scrollAnimationController!.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        _scrollAnimationController!.reset();
        _scrollAnimationController!.forward();
      }
    });

    _scrollAnimationController!.forward();
  }

  void _resetScrollAnimation() {
    // 当 needScroll 或文本长度变化时，重置滚动动画
    if (widget.needScroll && _scrollController.hasClients) {
      _startScrollAnimation();
    } else {
      // 如果不再需要滚动，停止动画并回到起始位置
      _scrollAnimationController?.stop();
      _scrollAnimationController?.dispose();
      _scrollAnimationController = null;
      _scrollController.jumpTo(0);
    }
  }

  void _resetSweepAnimation() {
    // 当 needGradient 变化时，重新初始化扫光动画
    _sweepAnimationController.dispose();
    _initSweepAnimation();
  }

  @override
  void didUpdateWidget(covariant MarqueeGradientText oldWidget) {
    super.didUpdateWidget(oldWidget);

    // 检查哪些属性变化了，并执行对应更新
    if (widget.text != oldWidget.text ||
        widget.needScroll != oldWidget.needScroll ||
        widget.speed != oldWidget.speed ||
        widget.gapWidth != oldWidget.gapWidth ||
        widget.fontSize != oldWidget.fontSize) {
      // 文本长度或滚动参数变化 -> 需要重新启动滚动动画
      // 但必须等布局完成后才能获取 maxScrollExtent
      WidgetsBinding.instance.addPostFrameCallback((_) {
        if (mounted) {
          _resetScrollAnimation();
        }
      });
    }

    if (widget.needGradient != oldWidget.needGradient ||
        widget.sweepSpeed != oldWidget.sweepSpeed ||
        widget.gradientColors != oldWidget.gradientColors) {
      // 扫光参数变化 -> 重新创建扫光动画
      _resetSweepAnimation();
    }
  }

  @override
  void dispose() {
    _scrollAnimationController?.dispose();
    _sweepAnimationController.dispose();
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // 1. 根据最新 widget 属性生成显示文本（动态计算）
    final String displayText = _fullText;

    // 2. 构建基础文本组件
    Widget textWidget = Text(
      displayText,
      style: TextStyle(
        fontSize: widget.fontSize,
        fontWeight: widget.fontWeight,
        color: widget.textColor,
      ),
      overflow: TextOverflow.visible,
      maxLines: 1,
    );

    // 3. 如果需要扫光，包裹 ShaderMask
    if (widget.needGradient) {
      textWidget = AnimatedBuilder(
        animation: _sweepAnimation,
        builder: (context, child) {
          double beginVal = _sweepAnimation.value;
          double endVal = beginVal + 0.3;
          return ShaderMask(
            shaderCallback: (Rect rect) {
              return LinearGradient(
                begin: Alignment(beginVal, 0),
                end: Alignment(endVal, 0),
                colors: widget.gradientColors,
              ).createShader(rect);
            },
            blendMode: BlendMode.srcIn,
            child: child,
          );
        },
        child: textWidget,
      );
    }

    // 4. 如果需要滚动，包裹 SingleChildScrollView
    if (widget.needScroll) {
      textWidget = SingleChildScrollView(
        scrollDirection: Axis.horizontal,
        physics: const NeverScrollableScrollPhysics(),
        controller: _scrollController,
        child: textWidget,
      );
    }

    return ShaderMask(
      shaderCallback: (bounds) => LinearGradient(
        colors: widget.gradientColors,
        begin: Alignment.topLeft,
        end: Alignment.bottomRight,
      ).createShader(bounds),
      child: textWidget,
    );
  }
}