import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:kaer_with_panels/app/modules/kr_purchase_membership/views/kr_purchase_membership_view.dart';
import 'package:kaer_with_panels/app/modules/kr_purchase_membership/bindings/kr_purchase_membership_binding.dart';
import 'package:kaer_with_panels/app/modules/kr_purchase_membership/controllers/kr_purchase_membership_controller.dart';
import 'package:kaer_with_panels/app/widgets/kr_local_image.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../controllers/kr_home_controller.dart';
import '../../../routes/app_pages.dart';
import 'package:kaer_with_panels/app/services/global_overlay_service.dart';

// ======================= 1. Circular Clipper (保持不变) =======================
class CircularClipper extends CustomClipper<Path> {
  final double fraction;
  final Offset centerOffset;

  CircularClipper(this.fraction, this.centerOffset);

  @override
  Path getClip(Size size) {
    final double maxDistance = _calculateMaxDistance(size, centerOffset);
    final double currentRadius = maxDistance * fraction;
    return Path()..addOval(Rect.fromCircle(center: centerOffset, radius: currentRadius));
  }

  double _calculateMaxDistance(Size size, Offset center) {
    final List<Offset> corners = [
      Offset(0, 0),
      Offset(size.width, 0),
      Offset(0, size.height),
      Offset(size.width, size.height)
    ];
    double maxDist = 0;
    for (var corner in corners) {
      final dist = (corner - center).distance;
      if (dist > maxDist) maxDist = dist;
    }
    return maxDist;
  }

  @override
  bool shouldReclip(CircularClipper oldClipper) {
    return oldClipper.fraction != fraction || oldClipper.centerOffset != centerOffset;
  }
}

// ======================= 2. 自定义路由类 (保持不变) =======================
class CustomCircleRoute extends PageRouteBuilder {
  final Widget child;
  final Offset startOffset;
  final Color transitionColor;
  final Duration customDuration;

  CustomCircleRoute({
    required this.child,
    required this.startOffset,
    required this.transitionColor,
    this.customDuration = const Duration(milliseconds: 250),
  }) : super(
    opaque: false,
    transitionDuration: customDuration,
    pageBuilder: (context, animation, secondaryAnimation) => child,
    transitionsBuilder: (context, animation, secondaryAnimation, child) {
      final curvedAnimation = CurvedAnimation(
        parent: animation,
        curve: Curves.easeOutCubic,
      );
      return ClipPath(
        clipper: CircularClipper(curvedAnimation.value, startOffset),
        child: Container(
          color: transitionColor,
          child: child,
        ),
      );
    },
  );
}

// ======================= 3. 按钮组件 (核心修改) =======================

// 3.1. 将 StatelessWidget 转换为 StatefulWidget
class HISubscriptionCornerButton extends StatefulWidget {
  final double size;
  final double topOffset;
  final double rightOffset;
  final Color color;
  final Function(VoidCallback)? onSetAnimationTrigger;

  const HISubscriptionCornerButton({
    super.key,
    required this.size,
    required this.topOffset,
    required this.rightOffset,
    required this.color,
    this.onSetAnimationTrigger,
  });

  @override
  State<HISubscriptionCornerButton> createState() => _HISubscriptionCornerButtonState();
}

// 3.2. 创建对应的 State 类
class _HISubscriptionCornerButtonState extends State<HISubscriptionCornerButton> {
  // 3.3. 在 State 内部创建 GlobalKey，确保其唯一性
  final GlobalKey _buttonKey = GlobalKey();

  @override
  void initState() {
    super.initState();
    print('🔥 HISubscriptionCornerButton initState 被调用');
    // 注册到全局 Overlay Service
    GlobalOverlayService.instance.registerAnimationTrigger(() {
      if (mounted) {
        print('🔥 通过全局服务触发动画');
        _startCircularTransition(context);
      }
    });
  }

  // 核心函数：计算按钮圆形的中心点全局坐标
  Offset _getButtonCenterOffset(BuildContext context) {
    final RenderBox? renderBox = _buttonKey.currentContext?.findRenderObject() as RenderBox?;
    if (renderBox == null) {
      final screenWidth = MediaQuery.of(context).size.width;
      // 使用 widget.属性 来访问 StatefulWidget 的成员
      return Offset(screenWidth - widget.rightOffset - widget.size / 2, widget.topOffset + widget.size / 2);
    }
    final Offset position = renderBox.localToGlobal(Offset.zero);
    return Offset(position.dx + widget.size / 2, position.dy + widget.size / 2);
  }

  // 导航和过渡逻辑
  void _startCircularTransition(BuildContext context) {
    print('🔥 _startCircularTransition 开始执行');
    // 使用 GetX 提供的当前路由
    final currentRoute = Get.currentRoute;
    if(currentRoute.isEmpty) return
    print('🔥 当前路由: $currentRoute');

    if (currentRoute == Routes.KR_PURCHASE_MEMBERSHIP ||  currentRoute == Routes.KR_ORDER_STATUS ) {
      print('🔥 已经在 KRPurchaseMembership 页面，无需跳转');
      return; // 已在目标页面，直接返回
    }
    // ✅ 进入购买页前，把按钮颜色改为透明
    GlobalOverlayService.instance.updateSubscriptionButtonColor(Colors.transparent);

    final Offset startOffset = _getButtonCenterOffset(context);
    final Color transitionColor = widget.color; // 使用 widget.color
    print('🔥 startOffset: $startOffset, transitionColor: $transitionColor');

    // 👉 每次都删除旧的 Controller，确保重新创建
    if (Get.isRegistered<KRPurchaseMembershipController>()) {
      Get.delete<KRPurchaseMembershipController>(force: true);
      print('🔥 已删除旧的 KRPurchaseMembershipController');
    }

    // 再重新注册
    KRPurchaseMembershipBinding().dependencies();
    print('🔥 开始导航到购买页面');
    Navigator.of(context).push(
      CustomCircleRoute(
        child: KRPurchaseMembershipView(),
        startOffset: startOffset,
        transitionColor: transitionColor,
        customDuration: const Duration(milliseconds: 500),
      ),
    ).then((_) {
      // 页面返回后恢复默认主题色
      GlobalOverlayService.instance.updateSubscriptionButtonColor(null);
    });
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () async {
        _startCircularTransition(context);
      },
      child: Container(
        key: _buttonKey, // 绑定 GlobalKey
        width: widget.size,
        height: widget.size,
        decoration: BoxDecoration(
          color: widget.color, // 使用 widget.color
          shape: BoxShape.circle,
        ),
      ),
    );
  }
}
