import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:nomo/config/theme/theme_extensions/theme_extension.dart';
import '../../../base/base_view.dart';
import '../../../widgets/ix_app_bar.dart';
import '../controllers/node_controller.dart';
import '../widgets/node_list.dart';

class NodeView extends BaseView<NodeController> {
  const NodeView({super.key});

  @override
  PreferredSizeWidget? get appBar => IXAppBar(title: 'Select Server');

  @override
  Widget buildContent(BuildContext context) {
    final tabCount = controller.tabTextList.length;
    if (tabCount == 0) {
      return const Center(child: Text('暂无数据'));
    }
    return DefaultTabController(
      length: tabCount,
      initialIndex: controller.currentTabIndex, // 恢复上次的 Tab 位置
      child: Column(
        children: [
          _buildTabs(),
          Divider(color: Get.reactiveTheme.dividerColor, height: 0.5),
          Expanded(child: _buildTabBarView()),
        ],
      ),
    );
  }

  Widget _buildTabs() {
    return TabBar(
      splashFactory: NoSplash.splashFactory,
      overlayColor: WidgetStateProperty.all(Colors.transparent),
      isScrollable: true,
      tabAlignment: TabAlignment.start,
      dividerColor: Colors.transparent,
      indicatorSize: TabBarIndicatorSize.tab,
      indicatorColor: Get.reactiveTheme.primaryColor,
      indicator: BoxDecoration(
        color: Get.reactiveTheme.primaryColor,
        borderRadius: BorderRadius.circular(8.r),
      ),
      // indicatorWeight: 2,
      labelColor: Get.reactiveTheme.textTheme.bodyLarge!.color,
      unselectedLabelColor: Get.reactiveTheme.hintColor,
      labelStyle: TextStyle(
        fontSize: 14.sp,
        fontWeight: FontWeight.w400,
        fontFamily: 'FiraSans',
      ),
      unselectedLabelStyle: TextStyle(
        fontSize: 14.sp,
        fontWeight: FontWeight.w400,
        fontFamily: 'FiraSans',
      ),
      padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 10.w),
      labelPadding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 8.w),
      // 监听 Tab 切换，保存当前索引
      onTap: (index) {
        controller.currentTabIndex = index;
      },
      tabs: controller.tabTextList.map((e) {
        return Row(
          children: [
            Icon(Icons.terminal, size: 14.w),
            4.horizontalSpace,
            Text(e),
          ],
        );
      }).toList(),
    );
  }

  Widget _buildTabBarView() {
    return TabBarView(
      children: List.generate(
        controller.tabTextList.length,
        (index) => NodeList(tabIndex: index),
      ),
    );
  }
}
