import 'dart:collection';

import 'package:flutter/material.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:get/get.dart';
import 'package:vnote_device_plugin/consts/types.dart';
import 'package:vnote_device_plugin_example/widgets/device_entity.dart';
import 'package:vnote_device_plugin_example/widgets/device_manager.dart';

import 'device_card.dart';

class DevicesSettingState {
  final RxList<String> _accessTypes = RxList<String>();
  final RxList<DeviceEntity> _deviceList = RxList<DeviceEntity>();

  /// 已授权设备类型集合
  List<String> get accessTypes => UnmodifiableListView(_accessTypes);
  set accessTypes(List<String> val) => _accessTypes.value = val;

  /// 设备信息集合
  List<DeviceEntity> get deviceList => UnmodifiableListView(_deviceList);
  set deviceList(List<DeviceEntity> val) => _deviceList.value = val;
}

class DevicesSettingController extends GetxController {
  final state = DevicesSettingState();
  final manager = DeviceManager();

  @override
  void onReady() {
    _loadData();
    super.onReady();
  }

  DeviceEntity? getDataByType(String type) {
    final data = state.deviceList.firstWhereOrNull((e) => e.type == type);
    return data;
  }

  void _loadData() {
    state.accessTypes = manager.getAccessTypes();
    state.deviceList = [
      DeviceEntity(
        type: DeviceTypes.TEMP,
        productName: "鱼跃",
        bleName: "yuyue",
        model: "yuddd",
        mac: "xx:xx:xx:00:xx",
      ),
    ];
  }
}

class DevicesSettingPage extends GetView<DevicesSettingController> {
  const DevicesSettingPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey.shade200,
      appBar: AppBar(
        elevation: 0,
      ),
      body: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Flexible(
            flex: 4,
            child: Container(
              color: Colors.green,
            ),
          ),
          Flexible(
            flex: 5,
            child: Container(
              padding: const EdgeInsets.all(12),
              child: _buildListView(),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildListView() {
    return Obx(() {
      final children = controller.state.accessTypes.map((e) {
        final data = controller.getDataByType(e);
        return DeviceCard(
          type: e,
          data: data,
        );
      }).toList();
      return StaggeredGrid.count(
        axisDirection: AxisDirection.down,
        crossAxisCount: 2,
        mainAxisSpacing: 16,
        crossAxisSpacing: 16,
        children: children,
      );
    });
  }
}
