import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';

import 'package:get/get.dart';
import 'package:naiyouwl/app/component/button_select.dart';
import 'package:naiyouwl/app/component/connection_status.dart';
import 'package:naiyouwl/app/component/connection_widget.dart';
import 'package:naiyouwl/app/component/sys_app_bar.dart';
import 'package:naiyouwl/app/controller/controllers.dart';
import 'package:naiyouwl/app/utils/system_proxy.dart';
import 'package:url_launcher/url_launcher.dart';
import '../controllers/home_controller.dart';


class HomeView extends GetView<HomeController> {

  const HomeView({Key? key}) : super(key: key);


  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: const BoxDecoration(
        image: DecorationImage(
          image: AssetImage("assets/images/main/main.png"),
          fit: BoxFit.fill,
        ),
      ),
      child: Scaffold(
          backgroundColor: Colors.transparent,
          appBar: SysAppBar(title: const Text("首页"), actions: [
            Row(
              children: [
                IconButton(
                  icon: const Icon(Icons.refresh),
                  tooltip: '刷新节点',
                  onPressed: () {
                    controller.fetchNode();
                  },
                ),
                IconButton(onPressed: (){

                  controller.outlogin();
                } ,tooltip: '切换账号', icon: const Icon(Icons.exit_to_app))
              ],
            ),
          ],),

          body: Obx(() {
            if (controllers.global.errorMsg.isNotEmpty) {
              // WidgetsBinding.instance.addPostFrameCallback((_) {
              //   ScaffoldMessenger.of(context).showSnackBar(
              //       SnackBar(content: Text(controller.errorMsg.value))
              //   );
              // });


              String message = controllers.global.errorMsg.value;
              controllers.global.errorMsg.value = '';  // Clear the error message immediately
              // Show the dialog and wait for the result
              Future.delayed(Duration.zero, () async {
                bool? result = await controllers.dialog.showNormalDialog(
                  title: "提示",
                  content: message,
                  cancelText: "取消",
                  enterText: "确认",
                );
                if (result != null && result) {
                  // User pressed "确认"
                  if(controllers.global.statusCode.value == 445){
                    await launchUrl(Uri.parse(controller.UsersysConfig.value.userBuy ?? ""));
                  }

                } else {
                  // User pressed "取消" or dismissed the dialog
                }
              });

            }

            final disabled = !controllers.service.isRunning;
            return controller.isLoading.value ? const Center(
                child: CircularProgressIndicator()) : Column(
              children: [
                // 错误消息展示


                UserStatusWidget(
                  isActive: controller.GetEnable(),
                  isLoading: controller.isLoading.value,
                  username: controller.GetUserName(),
                  expiryDate: controller.GetExpiredAt(),
                  userTraffic: controller.GetTraffic(),
                  onRefresh: () async {
                    // 这里插入刷新操作代码
                    //await Future.delayed(Duration(seconds: 2));
                    if (controller.isLoading.value != true) {
                      controller.fetchUserinfo();
                    }
                  },),
                Padding(
                    padding: const EdgeInsets.fromLTRB(20, 20, 0, 0),
                    child: Row(
                      children: controller.imageMap.entries.expand((entry) {
                        return [
                          GestureDetector(
                            onTap: () => controller.onImageTap(entry.key),
                            child: Image(
                              image: AssetImage(entry.value),
                              width: 60,
                              height: 60,
                            ),
                          ),
                          //Spacer(), // 平均分配间隔
                          const SizedBox(width: 30),
                        ];
                      }).toList()
                        ..removeLast(), // 删除最后一个Spacer
                    )

                ),
                const SizedBox(height: 30,),
                Padding(
                  padding: const EdgeInsets.fromLTRB(20, 0, 20, 0),
                  child: Row(
                    children: [
                      Text(controller.getHttp().toString()),
                      const Spacer(),
                      Text(controller.getSocket().toString()),
                    ],
                  ),
                ),
                ConnectionWidget(
                  status: controller.connectStatus.value, onTap: () {
                  if(controller.isRunning){
                    controller.stopVpn();
                  } else
                  {
                    controller.fetchAuthUser();
                  }

                },),
                Align(
                  alignment: Alignment.center,
                  child: Text(controllers.global.msgStatus.value),
                ),
                const SizedBox(height: 20,),
                Padding(
                  padding: const EdgeInsets.fromLTRB(20, 0, 20, 0),
                  child: SizedBox(
                    width: 200,
                    height: 40,
                    child: ElevatedButton(
                      onPressed: () {
                        controller.RouteNode();
                      },
                      style: ElevatedButton.styleFrom(
                        primary: Colors.white, // 设置背景颜色为白色
                        onPrimary: Colors.black, // 设置文字颜色为黑色，确保在白色背景上可见
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(20), // 设置圆角
                        ),
                      ),
                      child: Text(controller.GetNode()),
                    ),
                  ),
                ),
                const SizedBox(height: 40,),
                Align(
                  alignment: Alignment.center,
                  child: Padding(
                    padding: const EdgeInsets.fromLTRB(60, 0, 50, 0),
                    child: Row(
                      children: [
                        ButtonSelect(
                          labels: ['setting_mode_rules'.tr,'setting_mode_global'.tr,],
                          value: controllers.global.modes.indexOf(controllers.global.modesSelect.value),
                          onSelect: (idx) => {
                            controllers.global.updateMode(controllers.global.modes[idx])
                          },
                        ),
                        const SizedBox(width: 10,),
                        ButtonSelect(
                            labels: ['route_sys_tile'.tr,'route_tun_title'.tr,],
                            value: controllers.global.routeModes.indexOf(controllers.global.routeModesSelect.value),
                            onSelect: (idx) => {
                              controllers.global.updateRoute(controllers.global.routeModes[idx])
                            }
                        ),


                      ],
                    ),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.fromLTRB(60, 10, 50, 0),
                  child: Row(
                    children: [
                      ElevatedButton(onPressed: () async {
                        if(controller.serviceStuatus.value == false){
                          await controller.installService();
                        } else{
                          await controller.UninstallService();
                        }
                      }, child: controller.serviceStuatus.value == false ? const Text("安装服务") : const Text("卸载服务")),
                      const SizedBox(width: 10,),
                      ElevatedButton(onPressed: () async{
                        await controller.coreRestart();
                      }, child: const Text("重启内核")),
                    ],

                  ),
                )
                // const SizedBox(height: 20,),
                // Align(
                //   alignment: Alignment.center,
                //   child:,
                // )
              ],
            );
          })
      ),
    );
  }
}

class UserStatusWidget extends StatefulWidget {

  final Future<void> Function() onRefresh; // 新增的回调
  final bool isActive;
  final bool isLoading; // 新增的变量
  final String username;
  final String userTraffic;
  final String expiryDate;

  const UserStatusWidget(
      {Key? key, required this.isActive, required this.isLoading, required this.username, required this.userTraffic, required this.expiryDate, required this.onRefresh})
      : super(key: key);

  @override
  _UserStatusWidgetState createState() => _UserStatusWidgetState();
}

class _UserStatusWidgetState extends State<UserStatusWidget> {
  @override
  Widget build(BuildContext context) {
    String imagePath = widget.isActive
        ? "assets/images/main/userstatus.png"
        : "assets/images/main/userstatusoff.png";

    return Align(
      alignment: Alignment.topCenter,
      child: Padding(
        padding: const EdgeInsets.fromLTRB(5.0, 0, 5.0, 0.0),
        child:
        Row(
          children: [
            const SizedBox(
              width: 80,
              height: 20,
            ),
            Column(
              crossAxisAlignment: CrossAxisAlignment.start, // 这将使子组件从左边开始对齐
              children: [

                Row(
                  children: [
                    Text(widget.username),
                    const SizedBox(width: 10,),
                    Image(
                      image: AssetImage(imagePath),
                      width: 80,
                      height: 30,
                    ),
                    const SizedBox(width: 10,),
                    IconButton(
                      tooltip: '刷新账号状态',
                      icon: widget.isLoading
                          ? const CircularProgressIndicator()
                          : Image.asset("assets/images/main/refresh.png"),
                      onPressed: () {
                        // 刷新操作
                        if (!widget.isLoading) {
                          widget.onRefresh();
                        }
                      },
                    )
                  ],
                ),
                Text(
                  widget.expiryDate,
                  style: const TextStyle(
                    fontSize: 12.0, // 设置字体大小为20像素
                  ),
                ),
                Text(
                  widget.userTraffic,
                  style: const TextStyle(
                    fontSize: 12.0, // 设置字体大小为20像素
                  ),
                )
              ],
            ),
          ],
        ),
        // const SizedBox(height: 10,),  // 可调整间隔
      ),
    );
  }
}



