import 'package:ef/ef.dart';
import 'package:flutter/material.dart';
import 'package:vbvs_app/common/color/app_uri_status.dart';
import 'package:vbvs_app/common/util/FitTool.dart';
import 'package:vbvs_app/common/util/MyUtils.dart';
import 'package:vbvs_app/component/tool/CustomCard.dart';
import 'package:vbvs_app/component/tool/TopSlideNotification.dart';
import 'package:vbvs_app/controller/device/device_type_controller.dart';
import 'package:vbvs_app/controller/main_bottom/global_controller.dart';
import 'package:vbvs_app/controller/theme_controller/ThemeController.dart';
import 'package:vbvs_app/controller/user_info_controller.dart';
import 'package:vbvs_app/pages/mh_page/device/controller/mht_bluetooth_controller.dart';

class MHTBindDeviceTypePage extends StatefulWidget {
  int type = 0; //0绑定设备 1.查询我的设备
  MHTBindDeviceTypePage({super.key, this.type = 0});

  @override
  State<MHTBindDeviceTypePage> createState() => _MHTBindDeviceTypePageState();
}

class _MHTBindDeviceTypePageState extends State<MHTBindDeviceTypePage> {
  GlobalController globalController = Get.find();
  UserInfoController userInfoController = Get.find();
  // BlueteethBindController blueteethBindController = Get.find();
  MHTBlueToothController blueteethBindController = Get.find();
  ThemeController themeController = Get.find();
  DeviceTypeController deviceTypeController = Get.find();

  @override
  void initState() {
    super.initState();
    deviceTypeController.getDeviceType().then((response) {
      if (response.code != HttpStatusCodes.ok) {
        // 延迟到 widget 构建后再执行 show
        TopSlideNotification.show(
          context, // 用当前页面 context 替代 Get.context!
          text: response.msg ?? "服务器.失败".tr,
          textColor: themeController.currentColor.sc9,
        );
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    int read = blueteethBindController.model.read!;
    if (blueteethBindController.model.read == 1) {
      //需要弹窗显示教程
    }
    return LayoutBuilder(
      builder: (context, bodySize) => GestureDetector(
        onTap: () => FocusScope.of(context).unfocus(),
        child: Container(
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage('assets/images/new_background.png'), // 本地图片
              fit: BoxFit.fill, // 填满整个 Container
            ),
          ),
          child: Scaffold(
            backgroundColor: Colors.transparent, // 加上这一行
            appBar: AppBar(
              backgroundColor: Colors.transparent,
              // backgroundColor: Colors.transparent,
              automaticallyImplyLeading: false,
              iconTheme: IconThemeData(color: themeController.currentColor.sc3),
              titleSpacing: 0,
              // leading: returnIconButtom,
              title: Container(
                width: double.infinity,
                height: 180.rpx,
                child: Stack(
                  alignment: Alignment.center,
                  children: [
                    /// 居中标题
                    Text(
                      '添加设备'.tr,
                      style: TextStyle(
                        fontFamily: 'Readex Pro',
                        color: themeController.currentColor.sc3,
                        letterSpacing: 0,
                        fontSize: 30.rpx,
                      ),
                    ),

                    /// 左边返回按钮
                    Positioned(
                      left: 0,
                      child: returnIconButtom,
                    ),
                  ],
                ),
              ),

              actions: [],
              centerTitle: false,
            ),

            body: SafeArea(
              top: true,
              child: Padding(
                padding: EdgeInsetsDirectional.fromSTEB(30.rpx, 0, 30.rpx, 0),
                child: SingleChildScrollView(
                  child: Column(
                    mainAxisSize: MainAxisSize.max,
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // 使用 Obx 来监听 deviceTypeList 的变化
                      SizedBox(height: 26.rpx), // 开始的间隔
                      Text(
                        "选择类型",
                        style: TextStyle(color: Colors.white, fontSize: 30.rpx),
                      ),
                      SizedBox(height: 32.rpx), // 开始的间隔
                      Obx(() {
                        return Column(
                          children: [
                            ...deviceTypeController.deviceTypeList.value
                                .map((device) {
                              return Padding(
                                padding: EdgeInsets.only(
                                    bottom: 26.rpx), // 添加每个设备之间的间隔
                                child: _buildDeviceCard(
                                  context,
                                  title: device['name'],
                                  imageUrl: device['image'],
                                  type: device['type'],
                                  desc: device['desc'] ?? [],
                                  reg: device['device_reg'] ?? [],
                                ),
                              );
                            }).toList(),
                            SizedBox(height: 26.rpx), // 结束的间隔
                          ],
                        );
                      }),
                    ],
                  ),
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildDeviceCard(BuildContext context,
      {required String title,
      required String imageUrl,
      required double type,
      required List<dynamic>? desc,
      required List<dynamic>? reg}) {
    if (type == 1) {
      return SizedBox.shrink();
    }

    Map data = {
      "reg": reg,
      "type": type,
    };
    return CustomCard(
      borderRadius: 20.rpx,
      onTap: () {
        if (type == 2) {
          TopSlideNotification.show(
            context,
            text: "当前类型不支持绑定".tr,
          );
          return;
        }
        MHTBlueToothController mhtBlueToothController = Get.find();
        mhtBlueToothController.model.deviceType = type.toInt();
        Get.toNamed("/mHTBlueteethDevicePage", arguments: data);
      },
      colors: [Colors.white],
      child: Container(
        width: double.infinity,
        height: MediaQuery.sizeOf(context).height * 0.135,
        constraints: BoxConstraints(minHeight: 220.rpx),
        padding: EdgeInsets.symmetric(horizontal: 30.rpx),
        child: Row(
          children: [
            SizedBox(width: 58.rpx),
            ClipRRect(
              borderRadius: BorderRadius.circular(8.rpx),
              child: Image.network(
                imageUrl,
                width: 177.rpx,
                height: 85.rpx,
                fit: BoxFit.cover,
              ),
            ),
            SizedBox(width: 30.rpx),
            Expanded(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Text(
                    title,
                    style: TextStyle(
                      fontFamily: 'Inter',
                      color: stringToColor("#333333"),
                      fontSize: 30.rpx,
                      letterSpacing: 0.0,
                      fontWeight: FontWeight.w500,
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                  if (desc != null && desc.isNotEmpty) ...[
                    SizedBox(height: 10.rpx),
                    Text(
                      desc.join(' '),
                      style: TextStyle(
                        fontFamily: 'Inter',
                        color: stringToColor("#666666"),
                        fontSize: 24.rpx,
                      ),
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                      textAlign: TextAlign.left, // 或 center 看你整体布局需求
                    ),
                  ],
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
