import 'dart:math';
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:kaer_with_panels/app/modules/kr_home/controllers/kr_home_controller.dart';
import 'package:kaer_with_panels/app/widgets/kr_local_image.dart';
import 'package:kaer_with_panels/app/widgets/dialogs/hi_dialog.dart';
import 'package:kaer_with_panels/app/widgets/kr_app_text_style.dart';
import 'package:kaer_with_panels/app/services/global_overlay_service.dart';
import 'package:kaer_with_panels/app/services/singbox_imp/kr_sing_box_imp.dart';
import 'package:kaer_with_panels/singbox/model/singbox_status.dart';

DateTime? _hiConnectBtnNextAllowedAt;
const Duration _hiConnectBtnDebounce = Duration(milliseconds: 800);

/// ✅ 按钮组件（带多层呼吸同心圆动画）
class HIAnimatedConnectButton extends GetView<KRHomeController> {
  final VoidCallback? onTriggerSubscriptionAnimation;

  const HIAnimatedConnectButton({
    Key? key,
    this.onTriggerSubscriptionAnimation,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Obx(() {
      final delay = controller.kr_currentNodeLatency.value;

      // 🔧 关键: 强制读取两个 observable 确保追踪
      final _ = KRSingBoxImp.instance.kr_status.value; // 强制追踪
      final isConnected = controller.kr_isConnected.value; // 使用 controller 的状态

      // 再次读取状态用于判断
      final status = KRSingBoxImp.instance.kr_status.value;
      final isSwitching =
          status is SingboxStarting || status is SingboxStopping;

      print(
          '🔵 Switch UI 更新: status=${status.runtimeType}, isConnected=$isConnected, isSwitching=$isSwitching');

      final isShow = delay == -1 || isConnected;

      final Color buttonColor = Theme.of(context).primaryColor;
      final double screenWidth = Get.width;
      final double screenHeight = Get.height;

      final double buttonSize = 340;
      final double currentButtonSize = isShow ? 270 : buttonSize;

      return Stack(
        children: [
          AnimatedPositioned(
            duration: const Duration(milliseconds: 400),
            curve: Curves.linear,
            left: isShow ? (screenWidth - currentButtonSize) / 2 : -60,
            bottom: isShow ? screenHeight * 0.2 : -40,
            child: Stack(
              alignment: Alignment.center,
              clipBehavior: Clip.none,
              children: [
                /// ✅ 呼吸同心圆背景
                if (isShow)
                  Positioned.fill(
                    child: OverflowBox(
                      maxWidth: buttonSize * 3,
                      maxHeight: buttonSize * 3,
                      child: ContinuousRippleEffect(
                          color: Theme.of(context).primaryColor),
                    ),
                  ),

                if (!isShow)
                  Positioned(
                    top: -20, // 距离顶部 10.w
                    left: 115, // 距离右侧 10.w
                    child: KrLocalImage(
                      imageName: "hi-home-slogan",
                      imageType: ImageType.svg,
                    ),
                  ),

                /// ✅ 按钮主体
                Material(
                  shape: const CircleBorder(),
                  color: isShow
                      ? Colors.transparent
                      : Theme.of(context).primaryColor,
                  clipBehavior: Clip.antiAlias,
                  child: InkWell(
                    onTap: () async {
                      HapticFeedback.lightImpact();
                      final _now = DateTime.now();
                      if (_hiConnectBtnNextAllowedAt != null &&
                          _now.isBefore(_hiConnectBtnNextAllowedAt!)) {
                        _hiConnectBtnNextAllowedAt =
                            _now.add(_hiConnectBtnDebounce);
                        return;
                      }
                      _hiConnectBtnNextAllowedAt =
                          _now.add(_hiConnectBtnDebounce);

                      final current = controller
                          .kr_subscribeService.kr_currentSubscribe.value;
                      bool hasValidSubscription = false;
                      if (current != null) {
                        DateTime? expire;
                        try {
                          expire = DateTime.parse(current.expireTime);
                        } catch (_) {
                          expire = null;
                        }
                        hasValidSubscription =
                            expire != null && expire.isAfter(DateTime.now());
                      }
                      if (hasValidSubscription) {
                        controller
                            .kr_toggleSwitch(!controller.kr_isConnected.value);
                      } else {
                        HIDialog.show(
                          customMessageWidget: Padding(
                            padding: EdgeInsets.only(top: 16.w),
                            child: Text(
                              '尚未购买套餐，请前往购买页面下单后即可开始极速网络体验',
                              textAlign: TextAlign.left,
                              style: KrAppTextStyle(
                                color: Theme.of(context)
                                    .textTheme
                                    .bodyMedium
                                    ?.color,
                                fontSize: 14.sp,
                                fontWeight: FontWeight.w600,
                              ),
                            ),
                          ),
                          cancelText: '取消',
                          confirmText: '前往',
                          onConfirm: () {
                            GlobalOverlayService.instance
                                .triggerSubscriptionAnimation();
                          },
                        );
                      }
                    },
                    child: SizedBox(
                      width: currentButtonSize,
                      height: currentButtonSize,
                      child: Stack(
                        alignment: Alignment.center,
                        children: [
                          if (isShow)

                            /// ✅ isShow = true，图片居中，文字贴近底部
                            Stack(
                              alignment: Alignment.center,
                              children: [
                                Align(
                                  alignment: Alignment.center,
                                  child: KrLocalImage(
                                    imageName: "hi-home-logo",
                                    width: 186,
                                    imageType: ImageType.svg,
                                  ),
                                ),
                                Positioned(
                                  bottom: 5,
                                  left: 0,
                                  right: 0,
                                  child: Text(
                                    controller.kr_connectText.value == '已连接'
                                        ? '已连接\n点击断开'
                                        : controller.kr_connectText.value,
                                    key: ValueKey(
                                        controller.kr_connectText.value),
                                    textAlign: TextAlign.center,
                                    style: TextStyle(
                                        color: Colors.black,
                                        fontSize: 18,
                                        fontWeight: FontWeight.bold,
                                        height: 1),
                                  ),
                                ),
                              ],
                            )
                          else

                            /// ✅ isShow = false，恢复原本布局
                            Column(
                              mainAxisSize: MainAxisSize.min,
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                KrLocalImage(
                                  imageName: "hi-home-logo",
                                  width: 104,
                                  imageType: ImageType.svg,
                                ),
                                SizedBox(height: 2.h),
                                Text(
                                  controller.kr_connectText.value == '已连接'
                                      ? '已连接\n点击断开'
                                      : controller.kr_connectText.value,
                                  key:
                                      ValueKey(controller.kr_connectText.value),
                                  textAlign: TextAlign.center,
                                  style: TextStyle(
                                    color: Colors.black,
                                    fontSize: 18.sp,
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                              ],
                            ),
                        ],
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      );
    });
  }
}

/// ✅ 呼吸式同心圆动画（最小圆固定270，其他圆在270~479间波动，初始直径差10%）
/// ✅ 呼吸式同心圆动画（所有圆在270~470之间运动，起点相同但周期不同）
class ContinuousRippleEffect extends StatefulWidget {
  final Color color;

  const ContinuousRippleEffect({
    super.key,
    this.color = Colors.greenAccent,
  });

  @override
  State<ContinuousRippleEffect> createState() => _ContinuousRippleEffectState();
}

class _ContinuousRippleEffectState extends State<ContinuousRippleEffect>
    with TickerProviderStateMixin {
  final int _layerCount = 4;
  final List<AnimationController> _controllers = [];
  final List<Animation<double>> _animations = [];
  final List<double> _opacities = [0.4, 0.6, 0.8, 1.0];

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

    // 每层动画不同周期（呼吸错峰）
    for (int i = 0; i < _layerCount; i++) {
      // 动画周期差异：外层慢，内层快
      final duration = Duration(milliseconds: 3000 + i * 1200);

      final controller = AnimationController(vsync: this, duration: duration)
        ..repeat(reverse: true);

      final curved =
          CurvedAnimation(parent: controller, curve: Curves.easeInOutSine);
      _controllers.add(controller);
      _animations.add(curved);
    }
  }

  @override
  void dispose() {
    for (final c in _controllers) {
      c.dispose();
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    const double minDiameter = 270.0; // 最小直径
    const double maxDiameter = 470.0; // 最大直径
    const double motionRange = (maxDiameter - minDiameter) / 2; // 呼吸幅度 = 100
    const double centerDiameter = (maxDiameter + minDiameter) / 2; // 平均值 370

    return IgnorePointer(
      child: SizedBox(
        width: maxDiameter * 1.5,
        height: maxDiameter * 1.5,
        child: Stack(
          alignment: Alignment.center,
          clipBehavior: Clip.none,
          children: List.generate(_layerCount, (i) {
            final opacity = _opacities[i];
            final anim = _animations[i];

            return AnimatedBuilder(
              animation: anim,
              builder: (context, _) {
                double diameter;

                if (i == _layerCount - 1) {
                  // ✅ 最内层固定不动（稳态核心）
                  diameter = minDiameter;
                } else {
                  // ✅ 所有圆都在270~470之间波动
                  final value = anim.value;
                  // 呼吸范围：370 ± 100 * sin(…)
                  diameter = minDiameter + (maxDiameter - minDiameter) * value;
                }

                return Center(
                  child: Container(
                    width: diameter,
                    height: diameter,
                    decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      color: widget.color.withOpacity(opacity),
                    ),
                  ),
                );
              },
            );
          }),
        ),
      ),
    );
  }
}
