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:yumi/app_localizations.dart';
import 'package:yumi/shared/data_sources/models/message/sc_floating_message.dart';

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

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

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

class _FloatingRoomRedenvelopeScreenWidgetState
    extends State<FloatingRoomRedenvelopeScreenWidget>
    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; // 标记是否正在执行滑动动画

  @override
  void initState() {
    super.initState();
    // 主动画控制器
    _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();
    }
  }


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

  @override
  Widget build(BuildContext context) {
    // 如果正在执行滑动动画，使用滑动动画
    if (_isSwipeAnimating) {
      return SlideTransition(
        position: _swipeAnimation,
        child: _buildRedenvelopeAnimation(),
      );
    }

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

  Widget _buildRedenvelopeAnimation() {
    // 使用Positioned.fill确保飘屏覆盖全屏宽度，并定位在特定高度（如顶部100像素）
    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,
                needOpenRedenvelope: true,
                redPackId: widget.message.toUserId ?? "",
                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: AlignmentDirectional.centerStart,
              children: [
                PositionedDirectional(
                  start: 5.w,
                  top: 31.w,
                  child: head(
                    url: widget.message.userAvatarUrl ?? "",
                    width: 63.w,
                  ),
                ),
                Image.asset("sc_images/room/sc_icon_redenvelope_broad_bg.webp"),
                PositionedDirectional(
                  start: 70.w,
                  top: 52.w,
                  child: text(
                    SCAppLocalizations.of(context)!.openTheTreasureChest,
                    textColor: Colors.white,
                    fontWeight: FontWeight.bold,
                    fontSize: 14.sp,
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

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

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

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

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