import 'package:flutter/material.dart';
import 'package:flutter_debouncer/flutter_debouncer.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:yumi/ui_kit/components/sc_compontent.dart';
import 'package:yumi/ui_kit/components/text/sc_text.dart';
import 'package:yumi/shared/tools/sc_room_utils.dart';
import 'package:yumi/main.dart';
import 'package:marquee/marquee.dart';

import 'package:yumi/app_localizations.dart';
import 'package:yumi/shared/data_sources/models/message/sc_floating_message.dart';

class FloatingGameScreenWidget extends StatefulWidget {
  final SCFloatingMessage message;
  final VoidCallback onAnimationCompleted; // 动画完成回调

  const FloatingGameScreenWidget({
    Key? key,
    required this.message,
    required this.onAnimationCompleted,
  }) : super(key: key);

  @override
  _FloatingGameScreenWidgetState createState() =>
      _FloatingGameScreenWidgetState();
}

class _FloatingGameScreenWidgetState extends State<FloatingGameScreenWidget>
    with TickerProviderStateMixin {
  Debouncer debouncer = Debouncer();
  late AnimationController _controller;
  late Animation<Offset> _firstAnimation; // 第一段：从右到中
  late Animation<Offset> _secondAnimation; // 第二段：从中到左
  late AnimationController _swipeController; // 新增：滑动动画控制器
  late Animation<Offset> _swipeAnimation; // 新增：滑动动画

  bool _firstPhaseCompleted = false;
  bool _isSwipeAnimating = false; // 标记是否正在执行滑动动画

  ///游戏赢的金币按数量分等级，不同等级特效背景也不一样
  int level = 1;

  @override
  void initState() {
    super.initState();
    if ((widget.message.coins ?? 0) > 14999 &&
        (widget.message.coins ?? 0) < 50000) {
      level = 1;
    } else if ((widget.message.coins ?? 0) > 49999 &&
        (widget.message.coins ?? 0) < 100000) {
      level = 2;
    } else if ((widget.message.coins ?? 0) > 99999 &&
        (widget.message.coins ?? 0) < 300000) {
      level = 3;
    } else if ((widget.message.coins ?? 0) > 299999 &&
        (widget.message.coins ?? 0) < 500000) {
      level = 4;
    } else if ((widget.message.coins ?? 0) > 499999) {
      level = 5;
    }

    // 主动画控制器
    _controller = AnimationController(
      duration: const Duration(milliseconds: 1500), // 每段动画1.5秒
      vsync: this,
    );

    // 滑动动画控制器
    _swipeController = AnimationController(
      duration: const Duration(milliseconds: 550), // 滑动动画500ms
      vsync: this,
    );

    // 监听滑动动画完成
    _swipeController.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        widget.onAnimationCompleted();
      }
    });

    // 第一段动画：从右侧飘到中间
    _firstAnimation = Tween<Offset>(
      begin: const Offset(1.5, 0.0), // 从屏幕右侧外开始
      end: Offset.zero, // 到屏幕中心
    ).animate(CurvedAnimation(parent: _controller, curve: Curves.easeIn));

    // 第二段动画：从中间飘到左侧
    _secondAnimation = Tween<Offset>(
      begin: Offset.zero, // 从屏幕中心开始
      end: const Offset(-1.5, 0.0), // 到屏幕左侧外
    ).animate(CurvedAnimation(parent: _controller, curve: Curves.easeIn));

    // 滑动动画：从当前位置滑动到左侧屏幕外
    _swipeAnimation = Tween<Offset>(
      begin: Offset.zero, // 从当前位置开始
      end: const Offset(-1.5, 0.0), // 到屏幕左侧外
    ).animate(CurvedAnimation(
      parent: _swipeController,
      curve: Curves.easeIn,
    ));

    // 延迟启动动画
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (mounted) {
        _startAnimationSequence();
      }
    });
  }

  void _startAnimationSequence() async {
    // 第一阶段：从右到中
    _controller.reset();
    await _controller.forward();

    // 停顿2秒（你代码中是3秒，这里保持原样）
    await Future.delayed(const Duration(seconds: 3));

    if (!mounted) return;

    // 第二阶段：从中到左
    setState(() {
      _firstPhaseCompleted = true;
    });
    _controller.reset();
    await _controller.forward();

    if (mounted && !_isSwipeAnimating) {
      widget.onAnimationCompleted();
    }
  }

  // 处理向左滑动
  void _handleSwipeLeft() {
    if (_isSwipeAnimating) return;

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

    // 停止主动画
    _controller.stop();

    // 启动滑动动画
    _swipeController.reset();
    _swipeController.forward();
  }

  String _coinsVaFormat(num coins) {
    int value = coins.toInt();
    if (value > 99999) {
      return "${(value / 1000).toStringAsFixed(0)}k";
    }
    return "$value";
  }

  @override
  void dispose() {
    _controller.dispose();
    _swipeController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return _buildGameAnimation();
  }

  Widget _buildGameAnimation() {
    // 如果正在执行滑动动画，使用滑动动画
    if (_isSwipeAnimating) {
      return SlideTransition(
        position: _swipeAnimation,
        child: _buildContent(),
      );
    }

    // 否则使用原来的动画
    return SlideTransition(
      position: _firstPhaseCompleted ? _secondAnimation : _firstAnimation,
      child: _buildContent(),
    );
  }

  Widget _buildContent() {
    return GestureDetector(
      onTap: () {
        debouncer.debounce(
          duration: Duration(milliseconds: 350),
          onDebounce: () {
            if (widget.message.roomId != null &&
                widget.message.roomId!.isNotEmpty) {
              SCRoomUtils.goRoom(
                widget.message.roomId!,
                navigatorKey.currentState!.context,
                fromFloting: true,
              );
            }
          },
        );
      },
      onHorizontalDragEnd: (details) {
        // 获取当前的文本方向
        final textDirection = Directionality.of(context);

        // 定义一个根据方向转换速度符号的辅助函数
        double effectiveVelocity(double velocity) {
          // 在RTL模式下，反转速度的正负号
          return textDirection == TextDirection.rtl
              ? -velocity
              : velocity;
        }

        double velocity = effectiveVelocity(details.primaryVelocity ?? 0);
        if (velocity < 0) {
          ///向左滑动，把当前视图向左平移出去
          _handleSwipeLeft();
        }
      },
      child: Align(
        alignment: Alignment.topCenter,
        child: Directionality(
          textDirection: TextDirection.ltr,
          child: Container(
            alignment: Alignment.topCenter,
            height: 120.w,
            width: 325.w,
            margin: EdgeInsets.only(top: 10.w),
            child: Stack(
              alignment:
              level == 5
                  ? AlignmentDirectional.topCenter
                  : AlignmentDirectional.center,
              children: [
                if (widget.message.userAvatarUrl?.isNotEmpty ?? false)
                  _buildHead(),
                Image.asset("sc_images/index/sc_icon_gamebroad_lv${level}_bg.webp"),
                Row(
                  mainAxisSize: MainAxisSize.min, // 宽度由内容决定
                  children: [
                    SizedBox(width: level < 2 ? 82.w : 95.w),
                    Expanded(
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          Column(
                            mainAxisSize: MainAxisSize.min,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              SizedBox(
                                height:
                                level < 2
                                    ? 22.w
                                    : (level == 5 ? 31.w : 25.w),
                              ),
                              Row(
                                children: [
                                  Container(
                                    constraints: BoxConstraints(
                                      maxWidth: 55.w,
                                      maxHeight: 18.w,
                                    ),
                                    child:
                                    (widget.message.userName?.length ??
                                        0) >
                                        8
                                        ? Marquee(
                                      text:
                                      widget.message.userName ??
                                          "",
                                      style: TextStyle(
                                        fontSize: 12.sp,
                                        color: Colors.orange,
                                        fontWeight: FontWeight.bold,
                                        decoration:
                                        TextDecoration.none,
                                      ),
                                      scrollAxis: Axis.horizontal,
                                      crossAxisAlignment:
                                      CrossAxisAlignment.start,
                                      blankSpace: 20.0,
                                      velocity: 40.0,
                                      pauseAfterRound: Duration(
                                        seconds: 1,
                                      ),
                                      accelerationDuration: Duration(
                                        seconds: 1,
                                      ),
                                      accelerationCurve:
                                      Curves.easeOut,
                                      decelerationDuration: Duration(
                                        milliseconds: 500,
                                      ),
                                      decelerationCurve:
                                      Curves.easeOut,
                                    )
                                        : Text(
                                      widget.message.userName ?? "",
                                      maxLines: 1,
                                      overflow: TextOverflow.ellipsis,
                                      style: TextStyle(
                                        fontSize: 12.sp,
                                        color: Colors.orange,
                                        fontWeight: FontWeight.bold,
                                        decoration:
                                        TextDecoration.none,
                                      ),
                                    ),
                                  ),
                                  text(
                                    "ID:${widget.message.userId} ",
                                    textColor: Colors.white,
                                    fontWeight: FontWeight.bold,
                                    fontSize: 12.sp,
                                  ),
                                ],
                              ),
                              Transform.translate(
                                offset: Offset(
                                  0,
                                  level < 2 ? -5 : (level == 5 ? -5 : 0),
                                ),
                                child: Row(
                                  children: [
                                    text(
                                        SCAppLocalizations.of(context)!.get,
                                        textColor: Colors.orange,
                                        fontWeight: FontWeight.w900,
                                        fontSize: 16.sp,
                                        fontStyle: FontStyle.italic
                                    ),
                                    buildNumForGame(
                                      _coinsVaFormat(
                                        widget.message.coins ?? 0,
                                      ),
                                      size:
                                      (widget.message.coins ?? 0) > 99999
                                          ? 26.w
                                          : 20.w,
                                    ),
                                  ],
                                ),
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.only(top: level < 2 ? 10.w : 21.w),
                      child: netImage(
                        url: widget.message.giftUrl ?? "",
                        width: 28.w,
                        borderRadius: BorderRadius.all(Radius.circular(3.0)),
                      ),
                    ),
                    SizedBox(width: level < 2 ? 63.w : 65.w),
                  ],
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildHead() {
    if (level == 1) {
      return PositionedDirectional(
        start: 43.w,
        child: Container(
          margin: EdgeInsets.only(top: 12.w),
          child: head(url: widget.message.userAvatarUrl ?? "", width: 40.w),
        ),
      );
    } else if (level == 2) {
      return PositionedDirectional(
        start: 10.w,
        child: Container(
          margin: EdgeInsets.only(top: 25.w),
          child: head(url: widget.message.userAvatarUrl ?? "", width: 70.w),
        ),
      );
    } else if (level == 3) {
      return PositionedDirectional(
        start: 10.w,
        child: Container(
          margin: EdgeInsets.only(top: 25.w),
          child: head(url: widget.message.userAvatarUrl ?? "", width: 70.w),
        ),
      );
    } else if (level == 4) {
      return PositionedDirectional(
        start: 10.w,
        child: Container(
          margin: EdgeInsets.only(top: 25.w),
          child: head(url: widget.message.userAvatarUrl ?? "", width: 70.w),
        ),
      );
    } else if (level == 5) {
      return PositionedDirectional(
        start: 22.w,
        top: 20.w,
        child: Container(
          child: head(url: widget.message.userAvatarUrl ?? "", width: 48.w),
        ),
      );
    }
    return Container();
  }
}