import 'package:ef/ef.dart';
import 'package:flutter/material.dart';
import 'package:flutterflow_ui/flutterflow_ui.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/controller/device/device_share_list_controller.dart';
import 'package:vbvs_app/controller/message/message_controller.dart';
import 'package:vbvs_app/controller/theme_controller/ThemeController.dart';

class DeviceShareInfoWidget extends StatefulWidget {
  final data;

  const DeviceShareInfoWidget({super.key, required this.data});

  @override
  State<DeviceShareInfoWidget> createState() => _DeviceShareInfoWidgetState();
}

class _DeviceShareInfoWidgetState extends State<DeviceShareInfoWidget> {
  ThemeController themeController = Get.find();
  MessageController messageController = Get.find();
  DeviceShareListController deviceShareListController = Get.find();

  @override
  Widget build(BuildContext context) {
    final key = deviceShareListController.model.accountKey;

    final matchedValues = [];
    for (final item in widget.data) {
      if (item is Map && item.containsKey(key)) {
        final value = item[key];
        if (value != null) {
          final strValue = value.toString();
          if (strValue.isNotEmpty) {
            matchedValues.add(strValue);
            break;
          }
        }
      }
    }

    return ClickableContainer(
      backgroundColor: themeController.currentColor.sc5,
      highlightColor: themeController.currentColor.sc4,
      borderRadius: 20.rpx,
      padding: EdgeInsetsDirectional.fromSTEB(0.rpx, 33.rpx, 0.rpx, 33.rpx),
      onTap: () {},
      child: Row(
        mainAxisSize: MainAxisSize.max,
        children: [
          Obx(() {
            // 判断当前项是否被选中
            var aa = deviceShareListController.selectedShareInfo;
            print(aa);
            final isSelected = matchedValues.any((v) =>
                deviceShareListController.selectedShareInfo.value.contains(v));
            return Theme(
              data: ThemeData(
                checkboxTheme: CheckboxThemeData(
                  visualDensity: VisualDensity.compact,
                  materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(64),
                  ),
                ),
                unselectedWidgetColor: Color(0xFFD3D3D3),
              ),
              child: Checkbox(
                value: isSelected,
                onChanged: (newValue) async {
                  if (newValue != null) {
                    final key = deviceShareListController.model.accountKey;
                    // 提取包含指定 key 的 value
                    final List<String> matchedValues = [];
                    for (final item in widget.data) {
                      if (item is Map && item.containsKey(key)) {
                        final value = item[key];
                        if (value != null) {
                          final strValue = value.toString();
                          if (strValue.isNotEmpty) {
                            matchedValues.add(strValue);
                            break;
                          }
                        }
                      }
                    }
                    if (newValue == true) {
                      // 添加匹配值到已选列表中（避免重复）
                      for (final v in matchedValues) {
                        if (!deviceShareListController.selectedShareInfo.value
                            .contains(v)) {
                          deviceShareListController.selectedShareInfo.value
                              .add(v);
                        }
                      }
                    } else {
                      // 从已选列表中移除匹配值
                      deviceShareListController.selectedShareInfo.value
                          .removeWhere((v) => matchedValues.contains(v));
                    }

                    // 刷新 UI 和全选状态
                    final selectedCount =
                        deviceShareListController.selectedShareInfo.length;
                    final totalCount =
                        deviceShareListController.shareInfoList.length;

                    deviceShareListController.model.all =
                        (selectedCount == totalCount) ? 1 : 0;

                    deviceShareListController.selectedShareInfo.refresh();
                    deviceShareListController.updateAll();
                  }

                  final selectedCount =
                      deviceShareListController.selectedShareInfo.length;
                  final totalCount =
                      deviceShareListController.shareInfoList.length;

                  deviceShareListController.model.all =
                      (selectedCount == totalCount) ? 1 : 0;
                  deviceShareListController.selectedShareInfo.refresh();
                  deviceShareListController.updateAll();
                },
                side: BorderSide(
                  width: 1.5,
                  color: Colors.white,
                ),
                activeColor: stringToColor("#16C89F"),
                checkColor: Colors.white,
              ),
            );
          }),
          Row(
            mainAxisSize: MainAxisSize.max,
            children: [
              Container(
                constraints: BoxConstraints(
                  minWidth: 30.rpx,
                ),
                child: Column(
                  mainAxisSize: MainAxisSize.max,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: List.generate(widget.data.length, (index) {
                    final item = widget.data[index];
                    if (item is Map &&
                        item.containsKey('show') &&
                        item['show'] == false) {
                      return Container();
                    }
                    return Container(
                      constraints: BoxConstraints(
                        minHeight: 62.rpx,
                      ),
                      child: Row(
                        children: [
                          SizedBox(
                            width: 105.rpx,
                            child: Align(
                              alignment: AlignmentDirectional(-1, 0),
                              child: Text(
                                "${item['k']}",
                                style: TextStyle(
                                  fontFamily: 'Inter',
                                  fontSize: 26.rpx,
                                  letterSpacing: 0.0,
                                  color: themeController.currentColor.sc4,
                                ),
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                              ),
                            ),
                          ),
                          Text(
                            "${item['v']}",
                            style: TextStyle(
                              fontFamily: 'Inter',
                              fontSize: 26.rpx,
                              letterSpacing: 0.0,
                              color: themeController.currentColor.sc3,
                            ),
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                          ),
                        ].divide(SizedBox(
                          width: 34.rpx,
                        )),
                      ),
                    );
                  }),
                ),
              ),
            ].divide(SizedBox(width: 50.rpx)),
          ),
        ].divide(SizedBox(
          width: 10.rpx,
        )),
      ),
    );
  }
}
