// hi_node_list_view.dart

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:kaer_with_panels/app/localization/app_translations.dart';
import 'package:kaer_with_panels/app/widgets/kr_app_text_style.dart';
import 'package:kaer_with_panels/app/widgets/kr_country_flag.dart';
import '../../../model/business/kr_outbound_item.dart';
import '../../../utils/kr_log_util.dart';
import 'package:kaer_with_panels/app/utils/kr_secure_storage.dart';
import '../controllers/hi_node_list_controller.dart';
import 'package:kaer_with_panels/app/modules/kr_home/models/kr_home_views_status.dart';
import 'package:kaer_with_panels/app/services/singbox_imp/kr_sing_box_imp.dart';
import 'package:kaer_with_panels/app/widgets/kr_local_image.dart';

/// 节点列表视图组件
/// 职责：只负责根据状态渲染不同的列表，不包含任何外部容器、背景或标题。
/// 布局控制权完全交给父组件。
class HINodeListView extends GetView<HINodeListController> {
  const HINodeListView({super.key});

  // 定义颜色常量
  static const Color krModernGreen = Color(0xFF4CAF50);
  static const Color krModernGreenLight = Color(0xFF81C784);

  /// 获取分组内最快节点的延迟值（单位：ms）
  /// 如果列表为空，返回 0
  int getFastestNodeDelay(
    HINodeListController controller,
    List<KROutboundItem> outboundList,
  ) {
    if (outboundList.isEmpty) return 0;

    // 返回最小延迟值
    outboundList
        .sort((a, b) => a.urlTestDelay.value.compareTo(b.urlTestDelay.value));
    return outboundList.first.urlTestDelay.value;
  }

  /// 找出延迟最低（最快）的节点对象
  KROutboundItem findFastestNode(List<KROutboundItem> outboundList) {
    if (outboundList.isEmpty) {
      throw ArgumentError('outboundList 不能为空');
    }

    KROutboundItem fastest = outboundList.first;
    int fastestDelay = fastest.urlTestDelay.value;

    for (final item in outboundList.skip(1)) {
      final delay = item.urlTestDelay.value;
      print('国家分组下的节点$delay');
      if (delay < fastestDelay) {
        fastest = item;
        fastestDelay = delay;
      }
    }

    return fastest;
  }

  @override
  Widget build(BuildContext context) {
    // 1. 使用 Material 作为根组件，确保 InkWell 的水波纹效果正常
    //    并设置透明背景，让父组件的背景可以透出来
    return Obx(() {
      // Material 保持透明背景，让 InkWell 水波纹正常
      return Material(
        color: Colors.transparent,
        child: controller.isDebugMode.value
            ? _buildSubscribeList(context)
            : _kr_buildRegionList(context),
      );
    });
  }

  /// 构建国家/地区分组列表
  Widget _kr_buildRegionList(BuildContext context) {
    return Obx(() {
      return _kr_buildListContainer(
        context,
        child: ListView(
            padding: EdgeInsets.symmetric(vertical: 8.w),
            // 2. 使用 children 属性，并一次性构建所有列表项
            children: [
              if (controller.kr_subscribeService.countryOutboundList.isEmpty)
                _buildEmptyListPlaceholder(
                    context, AppTranslations.kr_home.noRegions)
              else ...[
                InkWell(
                  // 🔧 修复：改为 async，等待节点切换完成后再关闭列表
                  onTap: () async {
                    try {
                      controller.homeController
                          .kr_setSelectedCountryTag('auto');
                      final success = await controller.homeController
                          .kr_performNodeSwitch('auto');
                      if (success) {
                        controller.homeController.kr_currentListStatus.value =
                            KRHomeViewsListStatus.kr_none;
                      }
                    } catch (e) {
                      KRLogUtil.kr_e('Auto选项切换异常: $e', tag: 'NodeListView');
                    }
                  },
                  child: Container(
                    decoration: BoxDecoration(
                      border: Border(
                        bottom: BorderSide(
                          color: Colors.white.withOpacity(0.3),
                          width: 1.0,
                        ),
                      ),
                    ),
                    padding:
                        EdgeInsets.symmetric(vertical: 12.w, horizontal: 16.w),
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Container(
                          width: 32.w,
                          height: 22.w,
                          decoration: BoxDecoration(
                            // 2. 设置背景色为主题色
                            color: Theme.of(context).primaryColor,
                          ),
                          // 4. 使用 Center 来确保内部的图片水平和垂直居中
                          child: Center(
                            child: KrLocalImage(
                              imageName: "hi-home-logo",
                              width: 14.w,
                              height: 14.h,
                            ),
                          ),
                        ),
                        SizedBox(width: 8.w),
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                '自动匹配最快网络', // 您指定的文本
                                style: KrAppTextStyle(
                                  fontSize: 14,
                                  color: Colors.white,
                                  fontWeight: FontWeight.w600, // 600 加粗
                                ),
                              ),
                              // 2. 第二个 Text: "根据网络IP自动匹配最快线路"
                              Text(
                                '根据网络IP自动匹配最快线路', // 您指定的文本
                                style: KrAppTextStyle(
                                  fontSize: 10,
                                  color: Colors.white,
                                ),
                              ),
                            ],
                          ),
                        ),
                        Obx(() =>
                            controller.homeController.kr_selectedCountryTag.value ==
                                    'auto'
                                ? KrLocalImage(
                                    imageName: 'radio-active-icon',
                                    imageType: ImageType.svg,
                                    width: 16.w, // 适当缩小 SVG 尺寸，留出白边
                                    height: 16.h,
                                  )
                                : KrLocalImage(
                                    imageName: 'radio-icon',
                                    imageType: ImageType.svg,
                                    width: 16.w, // 适当缩小 SVG 尺寸，留出白边
                                    height: 16.h,
                                  )),
                      ],
                    ),
                  ),
                ),
                ...controller.kr_subscribeService.countryOutboundList
                    .map((country) {
                  return InkWell(
                    onTap: () async {
                      try {
                        controller.homeController
                            .kr_setSelectedCountryTag(country.country);
                        final fastest = findFastestNode(country.outboundList);
                        final success = await controller.homeController
                            .kr_performNodeSwitch(fastest.tag);
                        if (success) {
                          controller.homeController.kr_currentListStatus.value =
                              KRHomeViewsListStatus.kr_none;
                        }
                      } catch (e) {
                        KRLogUtil.kr_e('国家选择切换异常: $e', tag: 'NodeListView');
                      }
                    },
                    child: _kr_buildCountryListItem(context, country: country),
                  );
                }).toList(),
              ]
            ] //
            ),
      );
    });
  }

  /// 构建默认的订阅节点列表
  Widget _buildSubscribeList(BuildContext context) {
    return Obx(() {
      return _kr_buildListContainer(
        context,
        child: ListView(
            padding: EdgeInsets.symmetric(vertical: 8.w),
            // 2. 使用 children 属性，并一次性构建所有列表项
            children: [
              ...[
                InkWell(
                  // 🔧 修复：改为 async，等待节点切换完成后再关闭列表
                  onTap: () async {
                    try {
                      final success = await controller.homeController
                          .kr_performNodeSwitch('auto');
                      if (success) {
                        controller.homeController.kr_currentListStatus.value =
                            KRHomeViewsListStatus.kr_none;
                      }
                    } catch (e) {
                      KRLogUtil.kr_e('Auto选项切换异常: $e', tag: 'NodeListView');
                    }
                  },
                  child: Container(
                    decoration: BoxDecoration(
                      border: Border(
                        bottom: BorderSide(
                          color: Colors.white.withOpacity(0.3),
                          width: 1.0,
                        ),
                      ),
                    ),
                    padding:
                        EdgeInsets.symmetric(vertical: 12.w, horizontal: 16.w),
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Container(
                          width: 32.w,
                          height: 22.w,
                          decoration: BoxDecoration(
                            // 2. 设置背景色为主题色
                            color: Theme.of(context).primaryColor,
                          ),
                          // 4. 使用 Center 来确保内部的图片水平和垂直居中
                          child: Center(
                            child: KrLocalImage(
                              imageName: "hi-home-logo",
                              width: 14.w,
                              height: 14.h,
                            ),
                          ),
                        ),
                        SizedBox(width: 8.w),
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                '自动匹配最快网络', // 您指定的文本
                                style: KrAppTextStyle(
                                  fontSize: 14,
                                  color: Colors.white,
                                  fontWeight: FontWeight.w600, // 600 加粗
                                ),
                              ),
                              // 2. 第二个 Text: "根据网络IP自动匹配最快线路"
                              Text(
                                '根据网络IP自动匹配最快线路', // 默认文本
                                style: KrAppTextStyle(
                                  fontSize: 10,
                                  color: Colors.white,
                                ),
                              ),
                              /*  Obx(() {
                          // 当选择全局 auto 时，显示当前选中的节点信息
                          if (controller.homeController.kr_cutTag.value == 'auto') {
                            final autoNodeInfo = controller.homeController.kr_getGlobalAutoSelectedNode();
                            if (autoNodeInfo != null) {
                              return Text(
                                '当前: ${autoNodeInfo['tag']} (${autoNodeInfo['delay']}ms)',
                                style: KrAppTextStyle(
                                  fontSize: 10,
                                  color: Colors.white.withOpacity(0.8),
                                ),
                              );
                            }
                          }
                          return Text(
                            '根据网络IP自动匹配最快线路', // 默认文本
                            style: KrAppTextStyle(
                              fontSize: 10,
                              color: Colors.white,
                            ),
                          );
                        }),*/
                            ],
                          ),
                        ),
                        Obx(() =>
                            controller.homeController.kr_cutTag.value == 'auto'
                                ? KrLocalImage(
                                    imageName: 'radio-active-icon',
                                    imageType: ImageType.svg,
                                    width: 16.w, // 适当缩小 SVG 尺寸，留出白边
                                    height: 16.h,
                                  )
                                : KrLocalImage(
                                    imageName: 'radio-icon',
                                    imageType: ImageType.svg,
                                    width: 16.w, // 适当缩小 SVG 尺寸，留出白边
                                    height: 16.h,
                                  )),
                      ],
                    ),
                  ),
                ),
                ...controller.kr_subscribeService.allList().map((item) {
                  return InkWell(
                    // 🔧 修复：改为 async，等待节点切换完成后再关闭列表
                    onTap: () async {
                      try {
                        KRLogUtil.kr_i('🔄 用户点击节点: ${item.tag}');
                        final success = await controller.homeController
                            .kr_performNodeSwitch(item.tag);
                        if (success) {
                          controller.homeController.kr_currentListStatus.value =
                              KRHomeViewsListStatus.kr_none;
                        }
                      } catch (e) {
                        KRLogUtil.kr_e('节点切换异常: $e', tag: 'NodeListView');
                      }
                    },
                    child: _kr_buildNodeListItem(context, item: item),
                  );
                }).toList(),
              ]
            ] //
            ),
      );
    });
  }

  /// 列表为空时的占位符
  Widget _buildEmptyListPlaceholder(BuildContext context, String text) {
    return Container(
      height: 400.w, // 这是一个示例值，你可能需要根据实际屏幕高度来计算
      alignment: Alignment.center,
      child: Text(
        text,
        style: KrAppTextStyle(
            fontSize: 14, color: Theme.of(context).textTheme.bodySmall?.color),
      ),
    );
  }

  /// 列表的白色圆角背景容器
  Widget _kr_buildListContainer(BuildContext context, {required Widget child}) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.transparent,
        borderRadius: BorderRadius.circular(12.w),
      ),
      child: child,
    );
  }

  /// 构建单个节点列表项的UI
  Widget _kr_buildNodeListItem(BuildContext context,
      {required KROutboundItem item}) {
    return Container(
      key: ValueKey(item.id),
      decoration: BoxDecoration(
        border: Border(
          bottom: BorderSide(
            // 2. 将颜色设置为白色，并添加 30% 的透明度
            color: Colors.white.withOpacity(0.3),
            width: 1.0, // 边框宽度 1px
          ),
        ),
      ),
      padding: EdgeInsets.symmetric(vertical: 12.w, horizontal: 16.w),
      child: Row(
        children: [
          KRCountryFlag(
              countryCode: item.country,
              width: 30.w,
              height: 20.w,
              isCircle: false,
              maintainSize: false),
          SizedBox(width: 12.w),
          Expanded(
            child: Obx(() {
              final isDebug = controller.isDebugMode.value;

              final text = isDebug
                  ? '${controller.homeController.kr_getCountryFullName(item.country)} - ${item.tag}'
                  : '${controller.homeController.kr_getCountryFullName(item.country)}';

              return Text(
                text,
                style: KrAppTextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w500,
                  color: Colors.white,
                ),
              );
            }),
          ),
          Obx(() {
            // 1. 获取延迟值和测速状态
            int displayDelay;
            bool isTesting = controller.homeController.kr_isLatency.value;

            // 极简逻辑：只根据节点类型决定显示方式
            print(
                '🔄 _kr_buildNodeListItem节点: item.tag=${item.tag}, country=${item.country}');

            // 普通节点，直接显示节点自身的速度
            displayDelay = item.urlTestDelay.value;
            print('🔄 _kr_buildNodeListItem使用普通节点延迟: $displayDelay');

            // 2. 声明文本和颜色变量
            String delayText;
            Color delayColor;

            // 3. 根据状态设置文本和颜色
            if (isTesting && displayDelay == 0) {
              delayText = '测速中...';
              delayColor = Colors.grey; // 测速时使用灰色
            } else if (displayDelay == 0) {
              delayText = '- ms'; // 未测速或初始状态
              delayColor = Colors.grey;
            } else if (displayDelay >= 3000) {
              delayText = AppTranslations.kr_home.timeout; // "超时"
              delayColor = Colors.red; // 超时状态使用红色
            } else {
              delayText = '${displayDelay}ms';
              // 正常延迟，根据快慢设置不同颜色
              delayColor = (displayDelay < 500) ? krModernGreen : Colors.orange;
            }

            // 4. 返回最终的 Text 组件
            return Text(
              delayText,
              style: KrAppTextStyle(
                fontSize: 10,
                color: delayColor, // 使用动态计算出的颜色
                fontWeight: FontWeight.w500,
              ),
            );
          }),
          SizedBox(width: 12.w),
          Obx(() {
            final selected =
                controller.homeController.kr_cutSeletedTag.value == item.tag;
            return selected
                ? KrLocalImage(
                    imageName: 'radio-active-icon',
                    imageType: ImageType.svg,
                    width: 16.w,
                    height: 16.h,
                  )
                : KrLocalImage(
                    imageName: 'radio-icon',
                    imageType: ImageType.svg,
                    width: 16.w,
                    height: 16.h,
                  );
          }),
        ],
      ),
    );
  }

  /// 构建国家列表项的UI
  Widget _kr_buildCountryListItem(BuildContext context, {required country}) {
    return Container(
      key: ValueKey(country),
      decoration: BoxDecoration(
        border: Border(
          bottom: BorderSide(
            // 2. 将颜色设置为白色，并添加 30% 的透明度
            color: Colors.white.withOpacity(0.3),
            width: 1.0, // 边框宽度 1px
          ),
        ),
      ),
      padding: EdgeInsets.symmetric(vertical: 12.w, horizontal: 16.w),
      child: Row(
        children: [
          KRCountryFlag(
              countryCode: country.country,
              width: 30.w,
              height: 20.w,
              isCircle: false,
              maintainSize: false),
          SizedBox(width: 12.w),
          Expanded(
            child: Text(
              controller.homeController.kr_getCountryFullName(country.country),
              style: KrAppTextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w500,
                  color: Colors.white),
            ),
          ),
          Obx(() {
            // 1. 获取延迟值和测速状态
            int displayDelay =
                getFastestNodeDelay(controller, country.outboundList);
            bool isTesting = controller.homeController.kr_isLatency.value;

            // 2. 声明文本和颜色变量
            String delayText;
            Color delayColor;

            // 3. 根据状态设置文本和颜色
            if (isTesting && displayDelay == 0) {
              delayText = '测速中...';
              delayColor = Colors.grey; // 测速时使用灰色
            } else if (displayDelay == 0) {
              delayText = '- ms'; // 未测速或初始状态
              delayColor = Colors.grey;
            } else if (displayDelay >= 3000) {
              delayText = AppTranslations.kr_home.timeout; // "超时"
              delayColor = Colors.red; // 超时状态使用红色
            } else {
              delayText = '${displayDelay}ms';
              // 正常延迟，根据快慢设置不同颜色
              delayColor = (displayDelay < 500) ? krModernGreen : Colors.orange;
            }

            // 4. 返回最终的 Text 组件
            // return Text(
            //   delayText,
            //   style: KrAppTextStyle(
            //     fontSize: 10,
            //     color: delayColor, // 使用动态计算出的颜色
            //     fontWeight: FontWeight.w500,
            //   ),
            // );

            return Container(
              width: 4,
              height: 4,
              // 使用 BoxDecoration 来设置形状和颜色
              decoration: BoxDecoration(
                color: delayColor, // ✅ 核心：使用之前逻辑计算出的动态颜色
                // shape: BoxShape.circle, // 使用圆形看起来更柔和，也可以用 BoxShape.rectangle
              ),
            );
          }),
          SizedBox(width: 12.w),
          Obx(() {
            final selectedCountryField =
                controller.homeController.kr_selectedCountryTag.value;
            final selected = selectedCountryField == country.country;
            return selected
                ? KrLocalImage(
                    imageName: 'radio-active-icon',
                    imageType: ImageType.svg,
                    width: 16.w,
                    height: 16.h,
                  )
                : KrLocalImage(
                    imageName: 'radio-icon',
                    imageType: ImageType.svg,
                    width: 16.w,
                    height: 16.h,
                  );
          }),
        ],
      ),
    );
  }
}
