import 'dart:convert';

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

import 'package:vitalapp/components/alert_dialog.dart';
import 'package:vitalapp/managers/interfaces/models/device.dart';
import 'package:vitalapp/pages/check/widgets/exam_configurable/exam_card.dart';
import 'package:vitalapp/pages/medical/controller.dart';
import 'package:vitalapp/pages/medical/controllers/nibp.dart';
import 'package:vitalapp/pages/medical/models/item.dart';
import 'package:vitalapp/pages/medical/models/worker.dart';
import 'package:vitalapp/pages/medical/widgets/device_status.dart';
import 'package:vitalapp/pages/medical/widgets/switch_button.dart';

/// TODO 需要优化
/// 小弹窗输入
class VDialogBloodPressure extends StatelessWidget {
  /// 标题
  final String? title;

  /// 描述
  final String? description;

  /// 输入占位符
  final String? placeholder;

  /// 初始值
  final List<String>? initialValue;

  const VDialogBloodPressure({
    super.key,
    this.title,
    this.description,
    this.placeholder,
    this.initialValue,
  });

  Future<String?> show<String>() => VAlertDialog.showDialog<String>(this);

  @override
  Widget build(BuildContext context) {
    final controller1 = TextEditingController(text: initialValue?.first);
    final controller2 = TextEditingController(text: initialValue?.last);
    return VAlertDialog(
      title: title,
      width: 440,
      contentPadding: const EdgeInsets.symmetric(vertical: 12, horizontal: 24),
      content: _buildContent(context, controller1, controller2),
      showCancel: true,
      onConfirm: () {
        Get.back(result: json.encode([controller1.text, controller2.text]));
      },
    );
  }

  Widget _buildContent(
    BuildContext context,
    TextEditingController controller1,
    TextEditingController controller2,
  ) {
    final children = <Widget>[];
    if (description != null) {
      children.add(
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 4),
          child: Text(
            description!,
            style: const TextStyle(color: Colors.black87, fontSize: 18),
          ),
        ),
      );
      children.add(const SizedBox(height: 8));
    } else {
      children.add(const SizedBox(height: 12));
    }
    children.add(_buildInputWidget(context, controller1, controller2));
    return SingleChildScrollView(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: children,
      ),
    );
  }

  Widget _buildInputWidget(
    BuildContext context,
    TextEditingController controller1,
    TextEditingController controller2,
  ) {
    const fontSize = 20.0;
    return Row(
      children: [
        _buildItem(context, controller1, '高压'),
        const Text(
          '/',
          style: TextStyle(fontSize: fontSize),
        ),
        _buildItem(context, controller2, '低压'),
      ],
    );
  }

  Widget _buildItem(
    BuildContext context,
    TextEditingController controller,
    String hintText,
  ) {
    const fontSize = 20.0;
    const height = 56.0;
    return Expanded(
      child: SizedBox(
        height: height,
        child: TextField(
          controller: controller,
          readOnly: false,
          autofocus: true,
          keyboardType: const TextInputType.numberWithOptions(
              decimal: true), // 允许输入数字和小数点
          inputFormatters: [
            FilteringTextInputFormatter.allow(
              RegExp(r'^\d+\.?\d{0,2}'),
            ), // 只允许输入数字和小数点,俩位小数
          ],
          style: const TextStyle(fontSize: fontSize),
          decoration: InputDecoration(
            border: const UnderlineInputBorder(
              borderRadius: BorderRadius.zero,
              borderSide: BorderSide(),
            ),
            enabledBorder: const UnderlineInputBorder(
              borderRadius: BorderRadius.zero,
              borderSide: BorderSide(
                color: Colors.black54,
              ),
            ),
            focusedBorder: UnderlineInputBorder(
              borderRadius: BorderRadius.zero,
              borderSide: BorderSide(
                color: Theme.of(context).primaryColor.withOpacity(.4),
              ),
            ),
            filled: true,
            fillColor: Colors.white,
            contentPadding: const EdgeInsets.symmetric(
              vertical: (height - fontSize * 1.2) / 2,
              horizontal: 8,
            ),
            hintStyle: const TextStyle(fontSize: fontSize),
            labelStyle: const TextStyle(fontSize: fontSize),
            hintText: hintText,
            isCollapsed: true,
          ),
          onSubmitted: (value) {
            print(value);
            Get.back(result: value);
          },
        ),
      ),
    );
  }
}

// ignore: must_be_immutable
class BloodPressure extends StatefulWidget {
  const BloodPressure({
    super.key,
    // required this.currentValue,
    // required this.bloodPressure,
  });
  // Map<String, dynamic> currentValue;
  // Function(Map<String, dynamic>) bloodPressure;
  @override
  State<BloodPressure> createState() => _ExamBloodPressureState();
}

class _ExamBloodPressureState extends State<BloodPressure> {
  var controller = Get.find<MedicalController>();
  PressureStatus pressureStatus = PressureStatus.left;
  late NibpDeviceController nibp;
  late NibpDeviceWorker worker;
  int liveValue = 0;

  late NibpExamValue? value = NibpExamValue(
    diastolicPressure: controller.diagnosisDataValue['NIBP']?['Sbp'] ?? 0,
    systolicPressure: controller.diagnosisDataValue['NIBP']?['Dbp'] ?? 0,
    pulse: controller.diagnosisDataValue['NIBP']?['Pulse_Beat'] ?? 0,
  );

  WorkerStatus _connectStatus = WorkerStatus.connecting;
  @override
  void initState() {
    currentDevice();
    super.initState();
  }

  Future<void> currentDevice() async {
    DeviceModel? device = await controller.getDevice(DeviceTypes.NIBP);
    if (device.isNull) {
      _connectStatus = WorkerStatus.unboundDevice;
      setState(() {});
      return;
    }
    nibp = NibpDeviceController(device?.model ?? '', device?.mac ?? '');
    worker = nibp.worker;
    _connectStatus = nibp.connectStatus;

    loadListeners();
  }

  void loadListeners() {
    worker.liveUpdateEvent.addListener(_onLiveUpdate);
    worker.resultUpdateEvent.addListener(_onSuccess);
    worker.connectErrorEvent.addListener(_onConnectFail);
    worker.connectedEvent.addListener(_onConnectSuccess);
    worker.connect();
  }

  Future<void> disconnect() async {
    try {
      if (!worker.isNull) {
        await worker.disconnect();

        worker.connectErrorEvent.removeListener(_onConnectFail);
        worker.connectedEvent.removeListener(_onConnectSuccess);
        worker.liveUpdateEvent.removeListener(_onLiveUpdate);
        worker.resultUpdateEvent.removeListener(_onSuccess);
        worker.disconnectedEvent.removeListener(_onDisconnected);
      }
    } catch (err) {
      print(err);
    }
  }

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

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

  void _onSuccess(_, NibpExamValue e) {
    setState(() {
      value = e;
      controller.diagnosisDataValue['NIBP'] = {
        'Sbp': value?.diastolicPressure ?? '0',
        'Dbp': value?.systolicPressure ?? '0',
        'Pulse_Beat': value?.pulse,
      };

      /// 体检左侧
      if (pressureStatus == PressureStatus.left) {
        controller.diagnosisDataValue['NIBP']['Sbp_Left'] =
            value?.diastolicPressure ?? '0';
        controller.diagnosisDataValue['NIBP']['Dbp_Left'] =
            value?.diastolicPressure ?? '0';
      } else {
        controller.diagnosisDataValue['NIBP']['Sbp_Right'] =
            value?.diastolicPressure ?? '0';
        controller.diagnosisDataValue['NIBP']['Dbp_Right'] =
            value?.diastolicPressure ?? '0';
      }
    });
  }

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

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

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

  Widget _buildValue() {
    if (value?.pulse != 0) {
      return _buildResultWidget();
    }
    return _buildLiveWidget();
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        ExamCard(
          title: '血压',
          content: Container(
            padding: const EdgeInsets.only(top: 50),
            child: _SideBar(
              value: _buildValue(),
              unit: 'mmHg',
            ),
          ),
        ),
        _buildLeftOrRightBloodPressure(),
        DeviceStatus(connectStatus: _connectStatus),
      ],
    );
  }

  Widget _buildLeftOrRightBloodPressure() {
    return Positioned(
      top: 130,
      left: 38,
      child: AnimatedToggle(
        values: const ['左侧', '右侧'],
        onToggleCallback: (value) {
          setState(() {
            pressureStatus = value;
          });
        },
        buttonColor: Theme.of(context).primaryColor,
        backgroundColor: const Color(0xFFB5C1CC),
        textColor: const Color(0xFFFFFFFF),
      ),
      // child: Text('Toggle Value : $_toggleValue'),
    );
  }

  Widget _buildLiveWidget() {
    return Center(
      child: RichText(
        text: TextSpan(
          text: liveValue.toString() == '0' ? '--' : liveValue.toString(),
          style: const TextStyle(
            fontSize: 80,
            color: Colors.black,
          ),
          children: const [
            TextSpan(text: ' '),
            TextSpan(
              text: 'mmHg',
              style: TextStyle(fontSize: 25),
            )
          ],
        ),
      ),
    );
  }

  Widget _buildResultWidget() {
    const textStyle = TextStyle(
      fontSize: 48,
    );
    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),
            ),
          ),
        ),
      ],
    );
  }
}

class _SideBar extends StatelessWidget {
  final Widget value;
  final String unit;

  const _SideBar({
    required this.value,
    required this.unit,
  });

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.end,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          alignment: Alignment.bottomRight,
          padding: const EdgeInsets.only(
            bottom: 20,
            right: 30,
            left: 40,
          ),
          child: FittedBox(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.end,
              crossAxisAlignment: CrossAxisAlignment.end,
              children: [
                value,
              ],
            ),
          ),
        ),
      ],
    );
  }
}
