import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import './hi_node_list_view.dart';
import '../controllers/hi_node_list_controller.dart';
import 'package:kaer_with_panels/app/localization/app_translations.dart';
import 'package:flutter/services.dart';
import 'package:kaer_with_panels/app/widgets/kr_local_image.dart';
import 'package:kaer_with_panels/app/services/singbox_imp/kr_sing_box_imp.dart';
import 'package:kaer_with_panels/app/widgets/dialogs/hi_dialog.dart';
import 'package:kaer_with_panels/app/widgets/hi_help_entrance.dart';
import 'package:kaer_with_panels/app/widgets/hi_base_scaffold.dart';
import 'package:easy_refresh/easy_refresh.dart';
class HINodePageView extends StatefulWidget {
  const HINodePageView({super.key});

  @override
  State<HINodePageView> createState() => _HINodePageViewState();
}

class _HINodePageViewState extends State<HINodePageView> {
  final GlobalKey _modeSwitcherKey = GlobalKey();

  HINodeListController get controller => Get.find<HINodeListController>();

  @override
  Widget build(BuildContext context) {
    return HIBaseScaffold(
      child: Stack(
        children: [
          Positioned(
            left: 0,
            child: Obx(() => controller.isDebugMode.value
                ? GestureDetector(
                    onTap: () {
                      controller.kr_resetDebugMode();
                    },
                    child: Container(
                      padding: EdgeInsets.symmetric(horizontal: 10.w, vertical: 4.w),
                      decoration: BoxDecoration(
                        color: Colors.red.withOpacity(0.8),
                        borderRadius: BorderRadius.circular(12.w),
                      ),
                      child: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Icon(
                            Icons.bug_report,
                            size: 12.w,
                            color: Colors.white,
                          ),
                          SizedBox(width: 3.w),
                          Text(
                            '关闭调试',
                            style: TextStyle(
                              fontSize: 10.sp,
                              color: Colors.white,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                        ],
                      ),
                    ),
                  )
                : const SizedBox.shrink()),
          ),
          // 主要内容区域
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              
              // 模式切换器
              Padding(
                padding: EdgeInsets.only(left: 100.w, right: 60.w),
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    // 2. 关键：移除多余的 SizedBox，让 Expanded 正确工作
                    Expanded(
                      child: Container(
                        key: _modeSwitcherKey,
                        padding: EdgeInsets.all(4.w),
                        decoration: BoxDecoration(
                          border: Border.all(
                            color: Theme.of(context).primaryColor,
                            width: 2.0,
                          ),
                          borderRadius: BorderRadius.circular(100.r),
                        ),
                        child: Obx(() => Row(
                          children: [
                            // 3. 关键：修正按钮的点击逻辑和样式逻辑
                            _buildModeButton(
                              context,
                              title: AppTranslations.kr_setting.connectionTypeRule,
                              isSelected: KRSingBoxImp().kr_connectionType.value == KRConnectionType.rule,
                              onTap: () => controller.kr_updateConnectionType(KRConnectionType.rule),
                            ),
                            _buildModeButton(
                              context,
                              title: AppTranslations.kr_setting.connectionTypeGlobal,
                              isSelected: KRSingBoxImp().kr_connectionType.value == KRConnectionType.global,
                              onTap: () => controller.kr_updateConnectionType(KRConnectionType.global),
                            ),
                          ],
                        )),
                      ),
                    ),
                    SizedBox(width: 12.w),
                    GestureDetector(
                      onTap: () {
                        Offset? targetOffset;
                        final renderBox = _modeSwitcherKey.currentContext?.findRenderObject() as RenderBox?;
                        if (renderBox != null) {
                          final position = renderBox.localToGlobal(Offset.zero);
                          final size = renderBox.size;
                          targetOffset = Offset(
                            position.dx + (size.width / 2) - (HIDialog.kDialogWidth / 2),
                            position.dy + size.height + 10.w,
                          );
                        }

                        HIDialog.show(
                          targetOffset: targetOffset,
                          customMessageWidget: Padding(
                            padding: EdgeInsets.symmetric(horizontal: 0.w, vertical: 0.w),
                            child: Column(
                              mainAxisSize: MainAxisSize.min,
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text.rich(
                                  TextSpan(
                                    children: [
                                      TextSpan(
                                        text: '智能模式：',
                                        style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14.sp, color: Colors.black),
                                      ),
                                      TextSpan(
                                        text: '绕过所在地IP，只代理外网服务器，速度更快',
                                        style: TextStyle(fontSize: 14.sp,),
                                      ),
                                    ],
                                  ),
                                ),
                                SizedBox(height: 12.w),
                                Text.rich(
                                  TextSpan(
                                    children: [
                                      TextSpan(
                                        text: '全局模式：',
                                        style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14.sp),
                                      ),
                                      TextSpan(
                                        text: '代理所有网络服务器，保障隐私',
                                        style: TextStyle(fontSize: 14.sp),
                                      ),
                                    ],
                                  ),
                                ),
                              ],
                            ),
                          ),
                        );
                      },
                      child: KrLocalImage(
                        imageName: 'question-icon',
                        imageType: ImageType.svg,
                        width: 30.w,
                        height: 30.w,
                        color: Colors.white,
                      ),
                    ),
                  ],
                ),
              ),
              SizedBox(height: 16.w),

              // 4. 关键：将列表用 Expanded 包裹，使其自适应填充剩余空间，并为HIHelpEntrance预留空间
              Expanded(
                child: Padding(
                  padding: EdgeInsets.only(left: 60.w, right: 60.w, bottom: 90.w), // 为HIHelpEntrance预留空间
                  // 2. 在 Padding 内部使用 EasyRefresh
                  child: EasyRefresh(
                    onRefresh: controller.kr_handleRefresh,
                    // 4. 自定义 Header 样式
                    header: ClassicHeader(
                      dragText: '下拉刷新',
                      armedText: '释放刷新',
                      readyText: '正在刷新...',
                      processingText: '正在刷新...',
                      processedText: '刷新成功',
                      failedText: '刷新失败',
                      messageText: '最后更新于 %T',
                      textStyle: TextStyle(color: Colors.white.withOpacity(0.7)),
                      messageStyle: TextStyle(color: Colors.white.withOpacity(0.5), fontSize: 12.sp),
                      iconTheme: IconThemeData(color: Colors.white.withOpacity(0.7)),
                    ),
                    // 5. 将 HINodeListView 作为其 child
                    child: HINodeListView(),
                  ),
                ),
              ),
            ],
          ),
          // 底部帮助入口
          const HIHelpEntrance(),
        ],
      ),
    );
  }

  Widget _buildModeButton(
      BuildContext context, {
        required String title,
        required bool isSelected,
        required VoidCallback onTap,
      }) {
    return Expanded(
      child: GestureDetector(
        onTap: () {
          // 处理模式按钮点击（用于调试模式激活）
          controller.kr_handleModeButtonClick();
          // 执行原有的点击逻辑
          onTap();
        },
        child: AnimatedContainer(
          duration: const Duration(milliseconds: 200),
          padding: EdgeInsets.symmetric(vertical: 4.w),
          decoration: BoxDecoration(
            // 3. 关键：修正颜色逻辑
            color: isSelected
                ? Theme.of(context).primaryColor // 选中时：主题色背景
                : Colors.transparent,           // 未选中时：透明背景
            borderRadius: BorderRadius.circular(100.r),
          ),
          child: Center(
            child: Text(
              title,
              style: TextStyle(
                fontSize: 14.sp,
                fontWeight: FontWeight.w600,
                color: isSelected
                    ? Colors.black          // 选中时：黑色文字
                    : Theme.of(context).primaryColor, // 未选中时：主题色文字
              ),
            ),
          ),
        ),
      ),
    );
  }
}
