import 'dart:io';

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/data/model/UserMode.dart';
import 'package:url_launcher/url_launcher.dart';
import '../../../routes/app_pages.dart';
import '../../../utils/shell.dart';
import '../controllers/home_controller.dart';
import '../../connect/views/connect_view.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.networkService.fetchNode();
                },
              ),
              IconButton(
                onPressed: () {
                  controller.networkService.outlogin();
                },
                tooltip: '切换账号', 
                icon: const Icon(Icons.exit_to_app)
              ),
              IconButton(
                onPressed: () {
                  Get.toNamed(Routes.CONNECT);
                },
                tooltip: '连接详情',
                icon: const Icon(Icons.info_outline)
              )
            ],
          ),
        ],),
        body: Obx(() {
          if(controller.errAdminMsg.value){
            controller.errAdminMsg.value = false;
            Future.delayed(Duration.zero, () async {
              bool? result = await controllers.dialog.showNormalDialog(
                title: "提示",
                content: controller.errAdmin.value,
                cancelText: "取消",
                enterText: "确定",
              );
              if (result != null && result) {
                if(Platform.isWindows){
                  await  onRunAdmin();
                }
              }
            });
          }

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

          return controller.isLoading.value 
            ? const Center(child: CircularProgressIndicator()) 
            : SingleChildScrollView(
              child: Column(
                children: [
                  UserStatusWidget(
                    isActive: controller.GetEnable(),
                    isLoading: controller.isLoading.value,
                    username: controller.GetUserName(),
                    expiryDate: controller.GetExpiredAt(),
                    userTraffic: controller.GetTraffic(),
                    onRefresh: () async {
                      if (!controller.isLoading.value) {

                        var userinfo = await controller.networkService.fetchUserinfo();
                        if(userinfo != null )
                        {
                          controller.userMode.value = userinfo;
                        }

                      }
                    },
                  ),
                  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,
                            ),
                          ),
                          const SizedBox(width: 30),
                        ];
                      }).toList()..removeLast(),
                    )
                  ),
                  const SizedBox(height: 35,),
                  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: () {
                      controller.handleButtonClick();
                      // if(controller.isConnect.value){
                      //   controller.connectionService.stopConnection();
                      // } else {
                      //   controller.networkService.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(
                          foregroundColor: Colors.black, 
                          backgroundColor: Colors.white,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(20),
                          ),
                        ),
                        child: Text(controller.GetNode()),
                      ),
                    ),
                  ),
                  const SizedBox(height: 20,),
                  Center(
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      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(height: 20,),
                  Text("版本号:${controllers.global.sysVersion.value}"),
                  const SizedBox(height: 2,),
                  if (controllers.global.sysInfo.value.isNotEmpty) 
                    Text("当前:${controllers.global.sysInfo.value}"),
                ],
              ),
            );
        })
      ),
    );
  }
}

class UserStatusWidget extends StatelessWidget {
  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
  Widget build(BuildContext context) {
    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: [
                    Container(
                      width: 150,
                      child: Text(
                        username,
                        overflow: TextOverflow.ellipsis,
                        softWrap: false,
                        maxLines: 1,
                      ),
                    ),
                    const SizedBox(width: 2),
                    IconButton(
                      tooltip: '刷新账号状态',
                      icon: isLoading
                        ? const CircularProgressIndicator()
                        : Image(image: AssetImage("assets/images/main/refresh.png"), width: 20, height: 20),
                      onPressed: () {
                        if (!isLoading) {
                          onRefresh();
                        }
                      },
                    )
                  ],
                ),
                Text(
                  expiryDate,
                  style: const TextStyle(fontSize: 12.0),
                ),
                Text(
                  userTraffic,
                  style: const TextStyle(fontSize: 12.0),
                )
              ],
            ),
          ],
        ),
      ),
    );
  }
}


/*
 const SizedBox(width: 20),
                        if (Platform.isMacOS)
                          ElevatedButton(
                            onPressed: () async {
                              if (controllers.cc_service.installStatus.value) {
                                if(!controller.isRunning)
                                {
                                  await controller.connectionService.UninstallService();
                                } else {
                                  controllers.global.errorMsg.value = "先停止连接,在尝试";
                                }
                              } else {

                                if(!controller.isRunning)
                                {
                                  await controller.connectionService.installService();
                                } else {
                                  controllers.global.errorMsg.value = "先停止连接,在尝试";
                                }

                              }
                              // await controller.connectionService.checkServiceInstallation();
                            },
                            child: Text(controllers.cc_service.installStatus.value ? '卸载���务' : '安装服务'),
                          ),
*/