import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'dart:io' show Platform;
import 'package:flutter/foundation.dart' show kIsWeb;

import 'package:kaer_with_panels/app/model/response/kr_package_list.dart';
import 'package:kaer_with_panels/app/widgets/hi_base_scaffold.dart';
import 'package:kaer_with_panels/app/widgets/hi_help_entrance.dart';
import 'package:kaer_with_panels/app/widgets/kr_app_text_style.dart';
import '../controllers/kr_purchase_membership_controller.dart';
import '../../../widgets/kr_simple_loading.dart';
import 'package:kaer_with_panels/app/localization/app_translations.dart';
import '../../../widgets/kr_network_image.dart';
import 'package:kaer_with_panels/app/widgets/dialogs/kr_dialog.dart';
import 'package:kaer_with_panels/app/widgets/kr_local_image.dart';
import 'package:kaer_with_panels/app/utils/kr_log_util.dart';
import 'package:kaer_with_panels/app/widgets/swipe/has_swipe_config.dart';
import 'package:kaer_with_panels/app/widgets/swipe/swipe_config.dart';
import 'dart:convert';
import 'package:kaer_with_panels/app/widgets/dialogs/hi_dialog.dart';
import '../../../routes/app_pages.dart';
import 'package:kaer_with_panels/app/services/iap/iap_service.dart';
import 'package:kaer_with_panels/app/utils/kr_common_util.dart';



/// 购买会员页面视图
class KRPurchaseMembershipView extends GetView<KRPurchaseMembershipController>
    implements HasSwipeConfig {
  const KRPurchaseMembershipView({super.key});

  @override
  SwipeConfig get swipeConfig =>
      SwipeConfig(enableLeft: true, onLeft: () => Get.back());

  @override
  Widget build(BuildContext context) {
    // 获取屏幕顶部的安全区域高度（状态栏高度）
    final double topSafeArea = MediaQuery.of(context).padding.top;
    final double buttonTopPosition = 80 + topSafeArea;

    // 在最外层包裹一个 Stack
    return Stack(
      children: [
        // 第一层：整个页面原来的内容
        HIBaseScaffold(
          showBackgroundImage: false,
          title: '套餐选择',
          subtitle: '*所有套餐均不限流量不限速度',
          topContentAreaHeight: 110,
          child: Stack(
            // 允许内部的 slogan 等元素超出边界
            clipBehavior: Clip.none,
            children: [
              Positioned(
                left: 0,
                top: 0,
                bottom: 0,
                width: 20,
                child: const _LeftEdgeSwipeBack(),
              ),
              Padding(
                padding: const EdgeInsets.only(left: 20),
                child: Stack(
                  children: [
                    Obx(() {
                      return Positioned.fill(
                        bottom: 90.0,
                        child: SingleChildScrollView(
                          child: Column(
                            children: [
                              /*_kr_buildAccountSection(context),*/
                              if (controller.kr_isLoading.value)
                                Container(
                                  height:
                                  MediaQuery.of(context).size.height * 0.5,
                                  child: Center(
                                    child: KRSimpleLoading(
                                      color: Colors.white,
                                      size: 50.0,
                                    ),
                                  ),
                                )
                              else if (controller.kr_plans.isEmpty)
                                Container(
                                  height:
                                  MediaQuery.of(context).size.height * 0.5,
                                  child: Center(
                                    child: Text(
                                      AppTranslations
                                          .kr_purchaseMembership.noData,
                                      style: KrAppTextStyle(
                                        fontSize: 14,
                                        color: Theme.of(context)
                                            .textTheme
                                            .bodyMedium
                                            ?.color,
                                      ),
                                    ),
                                  ),
                                )
                              else
                                Container(
                                  margin: EdgeInsets.only(
                                      left: 40.0 - 20, right: 40.0),
                                  child: Column(
                                    children: [
                                      // 套餐选择部分
                                      Container(
                                        padding: EdgeInsets.all(0.0),
                                        child: Column(
                                          crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                          children: [
                                            Column(
                                              // 使用 List.generate 动态创建卡片列表
                                              children: List.generate(
                                                controller
                                                    .kr_getTotalOptionsCount(
                                                    controller.kr_plans[
                                                    controller
                                                        .kr_selectedPlanIndex
                                                        .value]),
                                                    (index) {
                                                  final plan = controller.kr_plans[
                                                  controller
                                                      .kr_selectedPlanIndex
                                                      .value];
                                                  final discountIndex =
                                                  plan.kr_discount.isEmpty
                                                      ? null
                                                      : index;
                                                  // 使用 Padding 来为每个卡片添加底部的间距，模拟 mainAxisSpacing
                                                  return Padding(
                                                    padding: EdgeInsets.only(
                                                        bottom: 8.0),
                                                    child: SizedBox(
                                                      height: 130.0,
                                                      child:
                                                      _kr_buildPlanOptionCard(
                                                        plan,
                                                        controller
                                                            .kr_selectedPlanIndex
                                                            .value,
                                                        discountIndex,
                                                        context,
                                                        index,
                                                      ),
                                                    ),
                                                  );
                                                },
                                              ),
                                            ),
                                          ],
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                            ],
                          ),
                        ),
                      );
                    }),
                    Positioned(
                      top: 160.0,
                      right: 10.0,
                      child: GestureDetector(
                        onTap: () {
                          controller.clearPendingOrderNo();
                        },
                        child: KrLocalImage(
                          imageName: 'purchase_slogan',
                          imageType: ImageType.svg,
                        ),
                      ),
                    ),
                    const HIHelpEntrance(isLight: false)
                  ],
                ),
              ),
              // --- 从这里移除按钮的 Positioned ---
            ],
          ),
        ),

        // 第二层：恢复按钮，放在 HIBaseScaffold 的上层
        Positioned(
          // top 值需要根据 HIBaseScaffold 的标题栏高度来精确调整
          // topContentAreaHeight 是 110，按钮高度是 20，让按钮下半部分贴着内容区顶部
          top: buttonTopPosition, // 110是标题区域高度, 10是按钮高度的一半
          left: 0,
          right: 0,
          child: _buildRestoreButton(),
        ),
      ],
    );
  }

  /// 构建“恢复已购项目”按钮
  Widget _buildRestoreButton() {
    if (!Platform.isIOS ) {
      return const SizedBox.shrink();
    }
    return Center(
      child: GestureDetector(
        onTap: () async{
          // 异步处理补单
          await KRIAPService.instance.retryUnfinishedTransactions();
          HIDialog.show(
            title: '温馨提示',
            message: '购买订单已确认，请耐心等待。若时长未到账，请联系在线客服处理。',
            confirmText: '联系客服',
            cancelText: '关闭',
            autoClose: false,
            showLoading: true,
            barrierDismissible: false,
            preventBackDismiss: true,
            onConfirm: () async {
              KRCommonUtil.kr_openCustomerService();
            },
          );
        },
        child: Container(
          height: 20,
          width: 94, // 保持固定宽度 94
          // 移除 padding 属性
          decoration: BoxDecoration(
            color: Colors.black,
            borderRadius: BorderRadius.circular(16),
          ),
          // 这个 Center 组件会使其子组件 Text 在 94x20 的空间内水平和垂直居中
          child: Center(
            child: Text(
              '恢复已购项目',
              style: const TextStyle(
                color: Colors.white,
                fontWeight: FontWeight.w600,
                fontSize: 12,
                height: 1.1,
                decoration: TextDecoration.none,
              ),
            ),
          ),
        ),
      ),
    );
  }

  // 套餐选项卡片
  Widget _kr_buildPlanOptionCard(
    KRPackageListItem plan,
    int planIndex,
    int? discountIndex,
    BuildContext context,
    int index,
  ) {
    // 由于移除了 Obx，isSelected 的值在构建时就固定了。
    // 它将不再响应用户的点击事件来改变UI。
    // 根据您的要求，isSelected 的值与 isFirst 相反。
    bool isFirst = 0 == index;
    bool isSelected = !isFirst;

    return GestureDetector(
      onTap: () {
        // 这里的 controller 调用仍然会更新状态，但UI不会自动重绘
        controller.kr_selectPlan(planIndex, discountIndex: discountIndex);
        controller.kr_startSubscription();
      },
      child: Container(
        // 外部Container作为边框
        padding: EdgeInsets.all(5), // 边框宽度
        decoration: BoxDecoration(
          color: Colors.black, // 边框颜色
          borderRadius: BorderRadius.circular(43.0), // 外部圆角 = 内部圆角 + 边框宽度
        ),
        child: ClipRRect(
          borderRadius: BorderRadius.circular(38.0), // 内部圆角
          child: Container(
            padding: EdgeInsets.fromLTRB(45.0, 0.0, 0.0, 0.0),
            decoration: BoxDecoration(
              color: isSelected ? Colors.black : Theme.of(context).primaryColor,
              borderRadius: BorderRadius.circular(38.0),
            ),
            child: Stack(
              alignment: Alignment.centerLeft,
              clipBehavior: Clip.none,
              children: [
                Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: [
                      Text(
                        controller.kr_getTimeStr(plan,
                            discountIndex: discountIndex),
                        style: TextStyle(
                          fontSize: 24,
                          fontWeight: FontWeight.w600,
                          color: isSelected
                              ? Colors.white
                              : Theme.of(context).textTheme.bodyMedium?.color,
                        ),
                      ),
                      Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          KrLocalImage(
                            imageName: 'money-icon',
                            imageType: ImageType.svg,
                            width: 36,
                            height: 36,
                            color: isSelected
                                ? Colors.white
                                : Theme.of(context).textTheme.bodyMedium?.color,
                          ),
                          SizedBox(width: 2),
                          Text(
                            controller
                                .kr_getPlanPrice(plan,
                                    discountIndex: discountIndex)
                                .toStringAsFixed(2),
                            style: TextStyle(
                              fontSize: 40,
                              height: 1,
                              fontWeight: FontWeight.w600,
                              color: isSelected
                                  ? Colors.white
                                  : Theme.of(context)
                                      .textTheme
                                      .bodyMedium
                                      ?.color,
                            ),
                          ),
                        ],
                      ),
                      Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Text(
                            '约',
                            style: TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.w600,
                              color: isSelected
                                  ? Colors.white
                                  : Theme.of(context)
                                      .textTheme
                                      .bodyMedium
                                      ?.color,
                            ),
                          ),
                          SizedBox(width: 2),
                          KrLocalImage(
                            imageName: 'money-icon',
                            imageType: ImageType.svg,
                            width: 16,
                            height: 16,
                            color: isSelected
                                ? Colors.white
                                : Theme.of(context).textTheme.bodyMedium?.color,
                          ),
                          SizedBox(width: 2),
                          Text(
                            '${controller.kr_getDayPlanPrice(plan, discountIndex: discountIndex).toStringAsFixed(2)}/天',
                            style: TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.w600,
                              color: isSelected
                                  ? Colors.white
                                  : Theme.of(context)
                                      .textTheme
                                      .bodyMedium
                                      ?.color,
                            ),
                          ),
                        ],
                      ),
                    ]),
                if (!isFirst)
                  Positioned(
                    top: 0,
                    right: 0,
                    child: Transform.rotate(
                      angle: 0.785398, // 45度角 (π/4)
                      child: Container(
                        // 调整位置，让标签的一部分显示在容器外
                        transform: Matrix4.translationValues(40, -10, 0),
                        width: 130, // 适当的宽度
                        height: 20, // 固定高度
                        decoration: BoxDecoration(
                          color: Theme.of(context).primaryColor, // 使用主题色作为背景
                        ),
                        child: Center(
                          child: Text(
                            '${controller.kr_getDiscountText(plan, discountIndex!)} off',
                            style: TextStyle(
                              color: Colors.black, // 白色文字更清晰
                              fontSize: 14,
                              fontWeight: FontWeight.w600,
                            ),
                            textAlign: TextAlign.center,
                          ),
                        ),
                      ),
                    ),
                  ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

class _LeftEdgeSwipeBack extends StatefulWidget {
  const _LeftEdgeSwipeBack();
  @override
  State<_LeftEdgeSwipeBack> createState() => _LeftEdgeSwipeBackState();
}

class _LeftEdgeSwipeBackState extends State<_LeftEdgeSwipeBack> {
  Offset? _start;
  Offset? _last;
  DateTime? _startTime;
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onHorizontalDragStart: (details) {
        _start = details.globalPosition;
        _startTime = DateTime.now();
        KRLogUtil.kr_d(
            'Purchase left edge dragStart x=${details.globalPosition.dx}',
            tag: 'PurchaseSwipe');
      },
      onHorizontalDragUpdate: (details) {
        _last = details.globalPosition;
      },
      onHorizontalDragEnd: (details) {
        final durationMs = DateTime.now()
            .difference(_startTime ?? DateTime.now())
            .inMilliseconds;
        final distance =
            _last != null && _start != null ? (_last!.dx - _start!.dx) : 0.0;
        KRLogUtil.kr_d(
            'Purchase left edge dragEnd dur=$durationMs dist=$distance',
            tag: 'PurchaseSwipe');
        if (distance > 20) {
          Get.back();
        }
        _start = null;
        _last = null;
        _startTime = null;
      },
    );
  }
}
