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 FloatingGiftScreenWidget extends StatefulWidget {
  final SCFloatingMessage message;
  final VoidCallback onAnimationCompleted; // 动画完成回调

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

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

class _FloatingGiftScreenWidgetState extends State<FloatingGiftScreenWidget>
    with TickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<Offset> _offsetAnimation;
  late AnimationController _swipeController; // 新增：滑动动画控制器
  late Animation<Offset> _swipeAnimation; // 新增：滑动动画
  Debouncer debouncer = Debouncer();

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

  @override
  void initState() {
    super.initState();

    // 主动画控制器
    _controller = AnimationController(
      duration: const Duration(seconds: 5),
      vsync: this,
    );

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

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

    // 主动画：从右向左移动
    _offsetAnimation = Tween<Offset>(
      begin: const Offset(1.0, 0.0),
      end: const Offset(-1.0, 0.0),
    ).animate(CurvedAnimation(parent: _controller, curve: Curves.easeOut));

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

    // 监听主动画完成
    _controller.addStatusListener((status) {
      if (status == AnimationStatus.completed && !_isSwipeAnimating) {
        widget.onAnimationCompleted();
      }
    });

    // 延迟启动动画，确保组件已经完全构建
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (mounted) {
        _controller.forward();
      }
    });
  }

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

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

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

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

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

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

  ///礼物总价钱达到10000
  Widget _buildGiftAnimation() {
    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: SlideTransition(
        position: _isSwipeAnimating ? _swipeAnimation : _offsetAnimation,
        child: Container(
          alignment: Alignment.center,
          height: 54.w,
          width: 320.w,
          margin: EdgeInsets.only(top: 20.w),
          padding: EdgeInsets.symmetric(horizontal: 10.w),
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage("sc_images/room/sc_icon_gift_float_bg.png"),
              fit: BoxFit.fill,
            ),
          ),
          child: Row(
            mainAxisSize: MainAxisSize.min, // 宽度由内容决定
            children: [
              // 可以根据消息模型丰富内容，例如显示头像
              if (widget.message.userAvatarUrl?.isNotEmpty ?? false)
                head(url: widget.message.userAvatarUrl ?? "", width: 42.w),
              SizedBox(width: 4.w),
              Expanded(
                child: Row(
                  children: [
                    Container(
                      constraints: BoxConstraints(
                        maxWidth: 48.w,
                        maxHeight: 21.w,
                      ),
                      child:
                          (widget.message.userName?.length ?? 0) > 6
                              ? Marquee(
                                text: widget.message.userName ?? "",
                                style: TextStyle(
                                  fontSize: 13.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: 13.sp,
                                  color: Colors.orange,
                                  fontWeight: FontWeight.bold,
                                  decoration: TextDecoration.none,
                                ),
                              ),
                    ),
                    text(
                      SCAppLocalizations.of(context)!.sendTo,
                      textColor: Colors.white,
                      fontSize: 13.sp,
                      fontWeight: FontWeight.bold,
                    ),
                    Container(
                      constraints: BoxConstraints(
                        maxWidth: 48.w,
                        maxHeight: 21.w,
                      ),
                      child:
                          (widget.message.toUserName?.length ?? 0) > 6
                              ? Marquee(
                                text: widget.message.toUserName ?? "",
                                style: TextStyle(
                                  fontSize: 13.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.toUserName ?? "",
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                                style: TextStyle(
                                  fontSize: 13.sp,
                                  color: Colors.orange,
                                  fontWeight: FontWeight.bold,
                                  decoration: TextDecoration.none,
                                ),
                              ),
                    ),
                  ],
                ),
              ),
              netImage(url: widget.message.giftUrl ?? "", width: 32.w),
              SizedBox(width: 3.w),
              Image.asset(
                "sc_images/room/sc_icon_x.png",
                width: (widget.message.number ?? 0) > 99 ? 15.w : 18.w,
              ),
              buildNum(
                "${widget.message.number}",
                size: (widget.message.number ?? 0) > 99 ? 15.w : 18.w,
              ),
            ],
          ),
        ),
      ),
    );
  }

  String _getLuckGiftFloatBg() {
    if ((widget.message.coins ?? 0) > 4999 &&
        (widget.message.coins ?? 0) < 10000) {
      return "sc_images/room/sc_icon_luck_gift_float_bg1.png";
    } else if ((widget.message.coins ?? 0) > 9999 &&
        (widget.message.coins ?? 0) < 75000) {
      return "sc_images/room/sc_icon_luck_gift_float_bg2.png";
    } else if ((widget.message.coins ?? 0) > 74999 &&
        (widget.message.coins ?? 0) < 150000) {
      return "sc_images/room/sc_icon_luck_gift_float_bg3.png";
    } else if ((widget.message.coins ?? 0) > 149999 &&
        (widget.message.coins ?? 0) < 1500000) {
      return "sc_images/room/sc_icon_luck_gift_float_bg4.png";
    } else if ((widget.message.coins ?? 0) > 1499999) {
      return "sc_images/room/sc_icon_luck_gift_float_bg5.png";
    }

    return "";
  }
}
