import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:nomo/app/base/base_view.dart';
import 'package:nomo/app/constants/assets.dart';
import 'package:nomo/app/dialog/all_dialog.dart';
import 'package:nomo/app/widgets/click_opacity.dart';
import 'package:nomo/app/widgets/ix_image.dart';
import 'package:nomo/config/theme/theme_extensions/theme_extension.dart';

import '../../../../utils/system_helper.dart';
import '../../../routes/app_pages.dart';
import '../../../widgets/ix_app_bar.dart';
import '../controllers/setting_controller.dart';

class SettingView extends BaseView<SettingController> {
  const SettingView({super.key});

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

  @override
  Widget buildContent(BuildContext context) {
    return CustomScrollView(
      slivers: [
        // Account Section
        _buildSectionHeader('Account'),
        _buildAccountSection(),

        // Network Section
        _buildSectionHeader('Network'),
        _buildNetworkSection(),

        // APP Section
        _buildSectionHeader('APP'),
        _buildAppSection(),

        // Security Section
        _buildSectionHeader('Security'),
        _buildSecuritySection(),

        // 底部间距
        SliverToBoxAdapter(child: 20.verticalSpaceFromWidth),
      ],
    );
  }

  /// 构建分组标题
  Widget _buildSectionHeader(String title) {
    return SliverToBoxAdapter(
      child: Padding(
        padding: EdgeInsets.fromLTRB(28.w, 20.w, 28.w, 12.w),
        child: Text(
          title,
          style: TextStyle(
            fontSize: 14.sp,
            color: Get.reactiveTheme.hintColor,
            fontWeight: FontWeight.w500,
          ),
        ),
      ),
    );
  }

  /// Account 分组
  Widget _buildAccountSection() {
    return SliverToBoxAdapter(
      child: Obx(() {
        final isPremium = controller.isPremium.value;
        return Container(
          margin: EdgeInsets.symmetric(horizontal: 14.w),
          decoration: BoxDecoration(
            color: Get.reactiveTheme.highlightColor,
            borderRadius: BorderRadius.circular(16.r),
          ),
          child: Column(
            children: [
              _buildSettingItem(
                icon: Icons.account_circle,
                iconColor: const Color(0xFF00A8E8),
                title: 'Account',
                trailing: IXImage(
                  source: isPremium ? Assets.premium : Assets.free,
                  width: isPremium ? 92.w : 64.w,
                  height: 28.w,
                  sourceType: ImageSourceType.asset,
                ),
                onTap: () {
                  Get.toNamed(Routes.ACCOUNT);
                },
              ),
              _buildDivider(),
              _buildSettingItem(
                icon: Icons.badge_outlined,
                iconColor: const Color(0xFF00A8E8),
                title: 'UID 123-456-789-101',
                trailing: Icon(
                  Icons.copy,
                  size: 20.w,
                  color: Get.reactiveTheme.hintColor,
                ),
                onTap: () {
                  Clipboard.setData(
                    const ClipboardData(text: '123-456-789-101'),
                  );
                  Get.snackbar('已复制', 'UID 已复制到剪贴板');
                },
              ),
              _buildDivider(),
              // 根据用户类型显示不同的时间信息
              if (isPremium) ...[
                _buildSettingItem(
                  icon: Icons.workspace_premium,
                  iconColor: const Color(0xFF00A8E8),
                  title: 'My Pre Code',
                  trailing: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Text(
                        '123***ADZ',
                        style: TextStyle(
                          fontSize: 14.sp,
                          color: Get.reactiveTheme.hintColor,
                        ),
                      ),
                      SizedBox(width: 4.w),
                      Icon(
                        Icons.arrow_forward_ios,
                        size: 16.w,
                        color: Get.reactiveTheme.hintColor,
                      ),
                    ],
                  ),
                  onTap: () {
                    // TODO: 跳转到Pre Code页面
                    Get.toNamed(Routes.PRECODE);
                  },
                ),
                _buildDivider(),
                _buildSettingItem(
                  icon: Icons.event,
                  iconColor: const Color(0xFF00A8E8),
                  title: 'Valid Term',
                  trailing: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Text(
                        'Year / 2026-12-12',
                        style: TextStyle(
                          fontSize: 14.sp,
                          color: const Color(0xFF00A8E8),
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                      SizedBox(width: 4.w),
                      Icon(
                        Icons.arrow_forward_ios,
                        size: 16.w,
                        color: Get.reactiveTheme.hintColor,
                      ),
                    ],
                  ),
                  onTap: () {
                    // TODO: 跳转到有效期详情页面
                  },
                ),
              ] else ...[
                _buildSettingItem(
                  icon: Icons.access_time,
                  iconColor: const Color(0xFF00A8E8),
                  title: 'Free Time',
                  trailing: Text(
                    '01:60:59 / Days',
                    style: TextStyle(
                      fontSize: 14.sp,
                      color: const Color(0xFFFF9500),
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ),
              ],
              _buildDivider(),
              _buildSettingItem(
                icon: Icons.phone_iphone,
                iconColor: const Color(0xFF00A8E8),
                title: 'Device Authorization',
                trailing: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Text(
                      isPremium ? '1/4' : '0/1',
                      style: TextStyle(
                        fontSize: 14.sp,
                        color: Get.reactiveTheme.hintColor,
                      ),
                    ),
                    SizedBox(width: 4.w),
                    Icon(
                      Icons.arrow_forward_ios,
                      size: 16.w,
                      color: Get.reactiveTheme.hintColor,
                    ),
                  ],
                ),
                onTap: () {
                  Get.toNamed(Routes.DEVICEAUTH);
                },
              ),
            ],
          ),
        );
      }),
    );
  }

  /// Network 分组
  Widget _buildNetworkSection() {
    return SliverToBoxAdapter(
      child: Container(
        margin: EdgeInsets.symmetric(horizontal: 14.w),
        decoration: BoxDecoration(
          color: Get.reactiveTheme.highlightColor,
          borderRadius: BorderRadius.circular(16.r),
        ),
        child: Column(
          children: [
            _buildSettingItem(
              icon: Icons.router,
              iconColor: const Color(0xFF00A8E8),
              title: 'Routing Mode',
              trailing: Icon(
                Icons.arrow_forward_ios,
                size: 16.w,
                color: Get.reactiveTheme.hintColor,
              ),
              onTap: () {
                // TODO: 跳转到路由模式页面
                Get.toNamed(Routes.ROUTINGMODE);
              },
            ),
            _buildDivider(),
            _buildSettingItem(
              icon: Icons.share,
              iconColor: const Color(0xFF00A8E8),
              title: 'Split Tunneling',
              trailing: Icon(
                Icons.arrow_forward_ios,
                size: 16.w,
                color: Get.reactiveTheme.hintColor,
              ),
              onTap: () {
                // TODO: 跳转到分流隧道页面
                Get.toNamed(Routes.SPLITTUNNELING);
              },
            ),
            _buildDivider(),
            _buildSettingItem(
              icon: Icons.flash_on,
              iconColor: const Color(0xFF00A8E8),
              title: 'Auto Reconnect',
              trailing: Obx(
                () => CupertinoSwitch(
                  value: controller.autoReconnect.value,
                  onChanged: (value) {
                    controller.autoReconnect.value = value;
                  },
                  activeTrackColor: Get.reactiveTheme.shadowColor,
                  thumbColor: Colors.white,
                  inactiveThumbColor: Colors.white,
                  inactiveTrackColor: Colors.grey,
                ),
              ),
            ),
            _buildDivider(),
            _buildSettingItem(
              icon: Icons.restart_alt,
              iconColor: const Color(0xFF00A8E8),
              title: 'Restore Default',
              trailing: Icon(
                Icons.arrow_forward_ios,
                size: 16.w,
                color: Get.reactiveTheme.hintColor,
              ),
              onTap: () {
                // TODO: 恢复默认设置
              },
            ),
          ],
        ),
      ),
    );
  }

  /// APP 分组
  Widget _buildAppSection() {
    return SliverToBoxAdapter(
      child: Container(
        margin: EdgeInsets.symmetric(horizontal: 14.w),
        decoration: BoxDecoration(
          color: Get.reactiveTheme.highlightColor,
          borderRadius: BorderRadius.circular(16.r),
        ),
        child: Column(
          children: [
            _buildSettingItem(
              icon: Icons.language,
              iconColor: const Color(0xFFFF9500),
              title: 'Language',
              trailing: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    'English',
                    style: TextStyle(
                      fontSize: 14.sp,
                      color: Get.reactiveTheme.hintColor,
                    ),
                  ),
                  8.horizontalSpace,
                  Icon(
                    Icons.arrow_forward_ios,
                    size: 16.w,
                    color: Get.reactiveTheme.hintColor,
                  ),
                ],
              ),
              onTap: () {
                // TODO: 跳转到语言选择页面
                Get.toNamed(Routes.LANGUAGE);
              },
            ),
            _buildDivider(),
            _buildSettingItem(
              icon: Icons.email,
              iconColor: const Color(0xFFFF9500),
              title: 'Feedback',
              trailing: Icon(
                Icons.arrow_forward_ios,
                size: 16.w,
                color: Get.reactiveTheme.hintColor,
              ),
              onTap: () {
                // TODO: 跳转到反馈页面
                Get.toNamed(Routes.FEEDBACK);
              },
            ),
            _buildDivider(),
            _buildSettingItem(
              icon: Icons.policy,
              iconColor: const Color(0xFFFF9500),
              title: 'Privacy Policy',
              trailing: Icon(
                Icons.arrow_forward_ios,
                size: 16.w,
                color: Get.reactiveTheme.hintColor,
              ),
              onTap: () {
                // TODO: 跳转到隐私政策页面
                SystemHelper.openPrivacyTerms();
              },
            ),
            _buildDivider(),
            _buildSettingItem(
              icon: Icons.description,
              iconColor: const Color(0xFFFF9500),
              title: 'Terms of Service',
              trailing: Icon(
                Icons.arrow_forward_ios,
                size: 16.w,
                color: Get.reactiveTheme.hintColor,
              ),
              onTap: () {
                // TODO: 跳转到服务条款页面
                SystemHelper.openTermsOfService();
              },
            ),
            _buildDivider(),
            _buildSettingItem(
              icon: Icons.apps,
              iconColor: const Color(0xFFFF9500),
              title: 'Version',
              trailing: Text(
                'V1.0.0',
                style: TextStyle(
                  fontSize: 14.sp,
                  color: Get.reactiveTheme.hintColor,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// Security 分组
  Widget _buildSecuritySection() {
    return SliverToBoxAdapter(
      child: Container(
        margin: EdgeInsets.symmetric(horizontal: 14.w),
        decoration: BoxDecoration(
          color: Get.reactiveTheme.highlightColor,
          borderRadius: BorderRadius.circular(16.r),
        ),
        child: Column(
          children: [
            _buildSettingItem(
              icon: Icons.person_remove,
              iconColor: const Color(0xFFFF3B30),
              title: 'Delete Account',
              onTap: () {
                // TODO: 删除账户
              },
            ),
            _buildDivider(),
            _buildSettingItem(
              icon: Icons.logout,
              iconColor: const Color(0xFFFF3B30),
              title: 'logout',
              titleColor: const Color(0xFFFF3B30),
              onTap: () {
                // TODO: 退出登录
                AllDialog.showLogoutConfirm();
              },
            ),
          ],
        ),
      ),
    );
  }

  /// 构建设置项
  Widget _buildSettingItem({
    required IconData icon,
    required Color iconColor,
    required String title,
    Color? titleColor,
    Widget? trailing,
    VoidCallback? onTap,
  }) {
    return ClickOpacity(
      onTap: onTap,
      child: Container(
        height: 56.w,
        padding: EdgeInsets.symmetric(horizontal: 16.w),
        child: Row(
          children: [
            // 图标
            Container(
              width: 32.w,
              height: 32.w,
              decoration: BoxDecoration(
                color: iconColor,
                borderRadius: BorderRadius.circular(8.r),
              ),
              child: Icon(icon, size: 20.w, color: Colors.white),
            ),
            SizedBox(width: 12.w),
            // 标题
            Expanded(
              child: Text(
                title,
                style: TextStyle(
                  fontSize: 16.sp,
                  color:
                      titleColor ??
                      Get.reactiveTheme.textTheme.bodyLarge!.color,
                  fontWeight: FontWeight.w400,
                ),
              ),
            ),
            // 右侧内容
            if (trailing != null) trailing,
          ],
        ),
      ),
    );
  }

  /// 构建分割线
  Widget _buildDivider() {
    return Padding(
      padding: EdgeInsets.only(left: 60.w),
      child: Divider(
        height: 1,
        color: Get.reactiveTheme.dividerColor.withOpacity(0.3),
      ),
    );
  }
}
