import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:vnote_device_plugin/devices/nibp.dart';
import 'package:vnote_device_plugin/models/exams/nibp.dart';

class NibpCard extends StatefulWidget {
  final String mac;
  final String model;

  const NibpCard({super.key, required this.mac, required this.model});

  @override
  State<StatefulWidget> createState() => _NibpCardState();
}

class _NibpCardState extends State<NibpCard> {
  late final NibpDeviceWorker worker = NibpDeviceWorker(
    mac: widget.mac,
    model: widget.model,
  );
  NibpExamValue? value;
  int? liveValue;
  bool _working = false;

  @override
  void initState() {
    worker.liveUpdateEvent.addListener(_onLiveUpdate);
    worker.resultUpdateEvent.addListener(_onSuccess);
    worker.errorEvent.addListener(_onError);
    super.initState();
  }

  @override
  void dispose() {
    worker.liveUpdateEvent.removeListener(_onLiveUpdate);
    worker.resultUpdateEvent.removeListener(_onSuccess);
    worker.errorEvent.removeListener(_onError);
    worker.disconnect();

    super.dispose();
  }

  void _onSuccess(_, NibpExamValue e) {
    setState(() {
      value = e;
    });
  }

  void _onLiveUpdate(_, int e) {
    setState(() {
      liveValue = e;
    });
  }

  void _onError(_, String e) {
    Get.snackbar(
      "提示",
      "测量错误: $e",
      snackPosition: SnackPosition.TOP,
    );
  }

  Widget _buildValue() {
    if (value != null) {
      return _buildResultWidget();
    }
    if (liveValue != null) {
      return _buildLiveWidget();
    }
    return const Center(
      child: Text(
        "00",
        style: TextStyle(fontSize: 80),
      ),
    );
  }

  Widget _buildLiveWidget() {
    final textStyle = TextStyle(fontSize: 80, color: Colors.orange.shade700);
    return Center(
      child: Text(
        liveValue!.toString(),
        style: textStyle,
      ),
    );
  }

  Widget _buildResultWidget() {
    const textStyle = TextStyle(fontSize: 48, color: Colors.green);
    return Stack(
      children: [
        Column(
          mainAxisAlignment: MainAxisAlignment.center,
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Align(
              alignment: Alignment.centerLeft,
              child: Text(
                value!.systolicPressure.toString(),
                style: textStyle,
              ),
            ),
            Align(
              alignment: Alignment.centerRight,
              child: Text(
                value!.diastolicPressure.toString(),
                style: textStyle,
              ),
            ),
          ],
        ),
        const Positioned.fill(
          child: Center(
            child: Text(
              "   /",
              style: TextStyle(fontSize: 24),
            ),
          ),
        ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Card(
      elevation: 4,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
      child: Container(
        alignment: Alignment.center,
        width: 360,
        height: 160,
        child: SizedBox(
          // height: 160,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              SizedBox(width: 160, child: _buildValue()),
              const SizedBox(width: 8),
              Container(
                height: 100,
                alignment: Alignment.bottomCenter,
                child: const Text(
                  "mmHg",
                  style: TextStyle(fontSize: 18),
                ),
              ),
              const SizedBox(width: 8),
              SizedBox(
                width: 60,
                height: 60,
                child: _working
                    ? OutlinedButton(
                        style: ButtonStyle(
                          backgroundColor: MaterialStatePropertyAll(
                            Colors.red.withOpacity(.08),
                          ),
                          shape: MaterialStatePropertyAll(
                            RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(30),
                            ),
                          ),
                        ),
                        onPressed: () async {
                          await worker.disconnect();
                          setState(() {
                            _working = false;
                            value = null;
                            liveValue = null;
                          });
                        },
                        child: const Text(
                          "停止",
                          style: TextStyle(color: Colors.red),
                        ),
                      )
                    : OutlinedButton(
                        style: ButtonStyle(
                          backgroundColor: MaterialStatePropertyAll(
                            Theme.of(context).primaryColor.withOpacity(.08),
                          ),
                          shape: MaterialStatePropertyAll(
                            RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(30),
                            ),
                          ),
                        ),
                        onPressed: () async {
                          await worker.connect();
                          setState(() {
                            _working = true;
                          });
                        },
                        child: const Text("开始"),
                      ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
