import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:vnote_device_plugin/consts/types.dart';
import 'package:vnote_device_plugin/devices/sugar.dart';
import 'package:vnote_device_plugin/models/exams/sugar.dart';
import 'package:vitalapp/managers/interfaces/models/device.dart';
import 'package:vitalapp/managers/interfaces/permission.dart';
import 'package:vitalapp/pages/check/models/form.dart';
import 'package:vitalapp/pages/check/widgets/device_controller.dart';
import 'package:vitalapp/pages/check/widgets/exam_configurable/exam_card.dart';

import 'package:vitalapp/components/dialog_number.dart';
import 'package:vitalapp/pages/medical/models/worker.dart';
import 'package:vitalapp/pages/medical/widgets/device_status.dart';

// ignore: must_be_immutable
class ExamBloodSugar extends StatefulWidget {
  ExamBloodSugar({
    super.key,
    required this.currentFormObject,
    required this.currentInputValue,
    this.bloodSugarInput,
  });
  FormObject currentFormObject;
  String currentInputValue;
  Function(String value)? bloodSugarInput;

  @override
  State<ExamBloodSugar> createState() => _ExamBloodSugarState();
}

class _ExamBloodSugarState extends State<ExamBloodSugar> {
  var permissionManager = Get.find<IPermissionManager>();
  final controller = Get.find<DeviceController>();
  WorkerStatus connectStatus = WorkerStatus.connecting;
  bool isAccessTypeAuth = false;
  late SugarDeviceWorker worker;

  @override
  void initState() {
    getPermission();
    currentDevice();
    super.initState();
  }

  Future<void> currentDevice() async {
    DeviceModel? device = await controller.getDevice(DeviceTypes.SUGAR);
    isAccessTypeAuth = await controller.isAccessTypeAuth(DeviceTypes.SUGAR);
    if (isAccessTypeAuth) {
      return;
    }
    if (device == null) {
      connectStatus = WorkerStatus.unboundDevice;
      setState(() {});
      return;
    }
    worker = SugarDeviceWorker(mac: device.mac, model: device.model);

    loadListeners();
  }

  Future<void> connect() async {
    setState(() {});
    await worker.connect();
  }

  Future<void> disconnect() async {
    worker.connectErrorEvent.removeListener(_onConnectFail);
    worker.connectedEvent.removeListener(_onConnectSuccess);
    worker.successEvent.removeListener(_onSuccess);
    worker.disconnectedEvent.removeListener(_onDisconnected);
    await worker.disconnect();
  }

  @override
  void dispose() {
    disconnect();
    super.dispose();
  }

  void _onSuccess(_, SugarExamData e) {
    setState(() {
      widget.currentInputValue = e.sugar.toString();
      widget.bloodSugarInput!.call(widget.currentInputValue);
      connectStatus = WorkerStatus.connected;
    });
  }

  void _onConnectFail(sender, e) {
    print('连接设备失败');
    connectStatus = WorkerStatus.connectionFailed;
    setState(() {});
  }

  void _onConnectSuccess(sender, e) {
    connectStatus = WorkerStatus.connected;
    setState(() {});
  }

  void _onDisconnected(sender, e) {
    connectStatus = WorkerStatus.disconnected;
    print('设备连接中断');
    setState(() {});
  }

  void loadListeners() {
    worker.successEvent.addListener(_onSuccess);
    worker.connectErrorEvent.addListener(_onConnectFail);
    worker.connectedEvent.addListener(_onConnectSuccess);
    worker.disconnectedEvent.addListener(_onDisconnected);
    worker.connect();
  }

  Future<void> getPermission() async {
    await permissionManager.requestLocationPermission();
    await permissionManager.requestBluetoothConnectPermission();
    await permissionManager.requestBluetoothAdvertisePermission();
    await permissionManager.requestBluetoothScanPermission();
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        _buildTemperature(),
        if (isAccessTypeAuth) DeviceStatus(connectStatus: connectStatus),
      ],
    );
  }

  Widget _buildTemperature() {
    return ExamCard(
      title: widget.currentFormObject.label ?? '',
      clickCard: () {
        _inputTemperature();
      },
      content: Container(
        alignment: Alignment.bottomRight,
        padding: const EdgeInsets.only(
          bottom: 20,
          right: 30,
          left: 40,
        ),
        constraints: const BoxConstraints(minHeight: 150),
        child: FittedBox(
          child: Row(
            mainAxisAlignment: MainAxisAlignment.end,
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              RichText(
                text: TextSpan(
                  text: widget.currentInputValue,
                  style: const TextStyle(
                    fontSize: 80,
                    color: Colors.black,
                  ),
                  children: [
                    TextSpan(
                      text: widget.currentFormObject.append ?? '',
                      style: const TextStyle(fontSize: 25),
                    )
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Future<void> _inputTemperature() async {
    String? result = await VDialogNumber(
      title: widget.currentFormObject.label,
      initialValue: widget.currentInputValue,
    ).show();
    if (result?.isNotEmpty ?? false) {
      widget.currentInputValue = result ?? '';
      widget.bloodSugarInput!.call(widget.currentInputValue);
    }
  }
}
