import 'package:ef/ef.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_svg/svg.dart';
import 'package:vbvs_app/common/util/FitTool.dart';
import 'package:vbvs_app/common/util/MyUtils.dart';
import 'package:vbvs_app/component/tool/ClickableContainer.dart';
import 'package:vbvs_app/component/tool/TopSlideNotification.dart';
import 'package:vbvs_app/controller/mh_controller/device_list_controller.dart';
import 'package:vbvs_app/model/api_response.dart';
import 'package:vbvs_app/pages/device_bind/componnet/bind_dialog.dart';
import 'package:vbvs_app/pages/mh_page/homepage/controller/mht_home_controller.dart';
import 'package:vbvs_app/pages/mh_page/test/WebviewTestModel.dart';

class BluetoothPage extends StatefulWidget {
  final Map data;
  BluetoothPage({Key? key, required this.data});
  @override
  _BluetoothPageState createState() => _BluetoothPageState();
}

class _BluetoothPageState extends State<BluetoothPage> {
  late RxMap<String, dynamic> obsData;
  @override
  void initState() {
    super.initState();
    obsData = Map<String, dynamic>.from(widget.data).obs; // 复制成 obs
  }

  BoxConstraints? bodysize;
  DeviceListController deviceListController = Get.find();
  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(builder: (context, cc) {
      bodysize = cc;
      return GestureDetector(
          onTap: () => FocusScope.of(context).unfocus(),
          child: Container(
              decoration: const BoxDecoration(
                image: DecorationImage(
                  image: AssetImage('assets/images/new_background.png'), // 本地图片
                  fit: BoxFit.fill, // 填满整个 Container
                ),
              ),
              child: Scaffold(
                backgroundColor: Colors.transparent,
                appBar: AppBar(
                  backgroundColor: Colors.transparent,
                  iconTheme: const IconThemeData(color: Colors.white),
                  automaticallyImplyLeading: false,
                  titleSpacing: 0,
                  title: SizedBox(
                    width: double.infinity,
                    height: 180.rpx,
                    child: Stack(
                      alignment: Alignment.center,
                      children: [
                        // 中间居中的标题
                        Text(
                          '设置',
                          textAlign: TextAlign.center,
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 30.rpx,
                          ),
                        ),
                        // 左侧图标
                        Positioned(
                          left: 0.rpx,
                          child: returnIconButtomNew,
                        ),
                      ],
                    ),
                  ),
                  centerTitle: false,
                ),
                body: SafeArea(
                    top: true,
                    child: Padding(
                      padding: EdgeInsets.fromLTRB(0.rpx, 115.rpx, 0.rpx, 0),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          Column(
                            children: [
                              Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  Text(
                                    obsData['name']?.toString() ?? '未命名',
                                    style: TextStyle(
                                      color: Colors.white,
                                      fontSize: 40.rpx,
                                    ),
                                  ),
                                  SizedBox(width: 27.rpx),
                                  ClickableContainer(
                                      backgroundColor: Colors.transparent,
                                      highlightColor: const Color(0xFF055466),
                                      padding: EdgeInsets.only(left: 0),
                                      onTap: () async {
                                        var x = await Get.toNamed(
                                            "/editBedPage",
                                            arguments: obsData);
                                        if (x != null) {
                                          setState(() {
                                            obsData.addAll(x); // 值更新后主动刷新页面
                                          });
                                        }
                                      },
                                      child: Container(
                                          width: 42.rpx,
                                          height: 42.rpx,
                                          child: SvgPicture.asset(
                                            "assets/img/icon/bluetooth_edit.svg",
                                            color: Colors.white,
                                          )))
                                ],
                              ),

                              const SizedBox(height: 4),
                              Text(obsData['mac']?.toString() ?? '未命名',
                                  style: TextStyle(
                                      color: Colors.white70, fontSize: 26.rpx)),

                              const SizedBox(height: 16),

                              // 蓝牙连接状态
                              Column(
                                children: [
                                  obsData['blueToothStatus'] == 1
                                      ? SvgPicture.asset(
                                          'assets/img/icon/blue_fail.svg',
                                          width: 68.rpx,
                                          height: 68.rpx,
                                        )
                                      : SvgPicture.asset(
                                          'assets/img/icon/blue_success.svg',
                                          width: 68.rpx,
                                          height: 68.rpx,
                                        ),
                                  SizedBox(height: 4),
                                  //下面文字和颜色也根据上面变化
                                  Text(
                                      obsData['blueToothStatus'] == 1
                                          ? '未连接'
                                          : '已连接',
                                      style: TextStyle(
                                          color: obsData['blueToothStatus'] == 1
                                              ? Color(0xFFFF7159)
                                              : Color(0xFF6BFDAC),
                                          fontSize: 26.rpx)),
                                ],
                              ),
                            ],
                          ),

                          const SizedBox(height: 24),

                          // 按钮列表
                          Expanded(
                            child: ListView(
                              padding: EdgeInsets.symmetric(horizontal: 30.rpx),
                              children: [
                                _buildMenuButton(
                                    context, '详情', "/devicePeopleInfo",
                                    arguments: obsData),
                                _buildMenuButton(
                                  context,
                                  '人员资料',
                                  "/peopleInfoPage",
                                  arguments: obsData,
                                ),
                                _buildMenuButton(
                                    context, '房间选择', "/roomPickerPage",
                                    arguments: obsData),
                                _buildMenuButton(context, '设备校准', ""),
                                _buildMenuButton(context, '体征传感器', ""),
                                _buildMenuButton(context, 'WIFI配置', ""),
                                _buildMenuButton(
                                    context, '睡眠习惯', "/sleepHabitPage"),
                                _buildMenuButton(
                                    context, '分享设备', "/deviceSharePage",
                                    arguments: obsData),
                                _buildMenuButton(
                                  context,
                                  obsData['bind_type'] == 1 ? '解绑' : '删除',
                                  "",
                                  onTap: () {
                                    if (obsData['bind_type'] == 1) {
                                      // 解绑弹窗
                                      showUnbindConfirmDialog(
                                        context: context,
                                        title: "是否进行解绑?",
                                        onConfirm: () async {
                                          await deviceListController
                                              .unbindDevice(obsData);
                                          await deviceListController
                                              .getDeviceList();
                                          MHTHomeController homeController =
                                              Get.find();
                                          homeController.selectDevcie.value =
                                              "";
                                          try {
                                            WebviewTestController
                                                webviewTestController =
                                                Get.find();
                                            webviewTestController
                                                .web.jsbridge?.dart
                                                .unBindDevice();
                                          } catch (e) {
                                            ef.log("[h5]通知列表更新报错：$e");
                                          }
                                          Get.toNamed("/mianPageBottomChange");
                                          // 执行解绑逻辑
                                        },
                                        onCancel: () {
                                          // 点击取消后的逻辑
                                        },
                                      );
                                    } else if (obsData['bind_type'] == 2) {
                                      // 删除弹窗
                                      showDeleteDeviceConfirmDialog(
                                        context: context,
                                        title: "是否进行删除?",
                                        onConfirm: () async {
                                          await deviceListController
                                              .unbindDevice(
                                            obsData,
                                          );
                                          await deviceListController
                                              .getDeviceList();
                                          Get.toNamed("/mianPageBottomChange");
                                        },
                                        onCancel: () {
                                          // 点击取消后的逻辑
                                        },
                                      );
                                    }
                                  },
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                    )),
              )));
    });
  }

  Widget _buildMenuButton(
    BuildContext context,
    String title,
    String? path, {
    Map<dynamic, dynamic>? arguments,
    VoidCallback? onTap,
  }) {
    return Padding(
      padding: EdgeInsets.only(bottom: 19.rpx),
      child: ClickableContainer(
        backgroundColor: Colors.transparent,
        highlightColor: Color(0XFF055466),
        padding: EdgeInsets.only(left: 0),
        onTap: () {
          // if (path?.isNotEmpty == true) {
          //   if (arguments != null) {
          //     Get.toNamed(path!, arguments: arguments);
          //   } else {
          //     Get.toNamed(path!);
          //   }
          // } else {
          //   TopSlideNotification.show(
          //     context,
          //     text: "功能开发中...",
          //   );
          // }
          if (onTap != null) {
            onTap(); // 优先执行自定义逻辑
          } else if (path?.isNotEmpty == true) {
            if (arguments != null) {
              Get.toNamed(path!, arguments: arguments);
            } else {
              Get.toNamed(path!);
            }
          } else {
            TopSlideNotification.show(
              context,
              text: "功能开发中...",
            );
          }
        },
        child: Container(
          height: MediaQuery.sizeOf(context).height * 0.0566,
          decoration: BoxDecoration(
            color: const Color(0xFF003058),
            borderRadius: BorderRadius.circular(16.rpx),
          ),
          child: Center(
            child: Text(
              title,
              style: const TextStyle(color: Colors.white, fontSize: 16),
            ),
          ),
        ),
      ),
    );
  }
}
