import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:vnote_device_plugin/consts/types.dart';
import 'package:vnote_device_plugin/devices/weight.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 ExamBodyWeight extends StatefulWidget {
  ExamBodyWeight({
    super.key,
    required this.currentFormObject,
    required this.currentInputValue,
    this.bodyWeightInput,
  });
  FormObject currentFormObject;
  String currentInputValue;
  Function(String value)? bodyWeightInput;

  @override
  State<ExamBodyWeight> createState() => _ExamBodyWeightState();
}

class _ExamBodyWeightState extends State<ExamBodyWeight> {
  var permissionManager = Get.find<IPermissionManager>();
  final controller = Get.find<DeviceController>();

  late WeightDeviceWorker worker;

  late WorkerStatus connectStatus = WorkerStatus.connecting;
  bool isAccessTypeAuth = false;
  @override
  void initState() {
    getPermission();
    currentDevice();
    super.initState();
  }

  Future<void> currentDevice() async {
    DeviceModel? device = await controller.getDevice(DeviceTypes.WEIGHT);
    isAccessTypeAuth = await controller.isAccessTypeAuth(DeviceTypes.WEIGHT);

    if (device == null) {
      connectStatus = WorkerStatus.unboundDevice;
      setState(() {});
      return;
    }
    worker = WeightDeviceWorker(
      mac: device.mac,
      model: device.model,
    );

    loadListeners();
  }

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

  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(_, double e) {
    setState(() {
      widget.currentInputValue = e.toString();
      widget.bodyWeightInput!.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) {
    print('设备连接中断');
    connectStatus = WorkerStatus.disconnected;
    setState(() {});
  }

  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.bodyWeightInput!.call(widget.currentInputValue);
    }
  }
}



// class ExamBodyWeight extends StatefulWidget {
//   const ExamBodyWeight({
//     super.key,
//     required this.currentFormObject,
//     required this.currentInputValue,
//     this.specialInput,
//   });
//   final FormObject currentFormObject;
//   final String currentInputValue;
//   final Function(String value)? specialInput;

//   @override
//   State<ExamBodyWeight> createState() => _ExamBodyWeightState();
// }

// class _ExamBodyWeightState extends State<ExamBodyWeight> {
//   var permissionManager = Get.find<IPermissionManager>();
//   @override
//   void initState() {
//     getPermission();
//     super.initState();
//   }

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

//   @override
//   Widget build(BuildContext context) {
//     return ExamCard(
//       title: widget.currentFormObject.label ?? '',
//       clickCard: () {
//         _buildTempertureInput(widget.currentFormObject);
//       },
//       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> _buildTempertureInput(FormObject currentFormObject) async {
//     // Future.delayed(const Duration(milliseconds: 3000), () {
//     //   specialInputController.text = generateRandomNumber().toString();
//     //   widget.specialInput?.call(specialInputController.text);
//     //   setState(() {});
//     // });

//     final result = await Get.dialog(
//       Weight(
//         currentFormObject: widget.currentFormObject,
//         weight: widget.currentInputValue,
//       ),
//       barrierDismissible: false,
//     );
//     widget.specialInput?.call(result);
//     print('object');
//     print(result);
//     print('object');
//   }
// }

// class Weight extends StatefulWidget {
//   const Weight({
//     super.key,
//     required this.currentFormObject,
//     this.weight,
//   });
//   final FormObject currentFormObject;
//   final String? weight;

//   @override
//   State<Weight> createState() => _WeightState();
// }

// class _WeightState extends State<Weight> {
//   late final WeightDeviceWorker worker = WeightDeviceWorker(
//     mac: 'CF:E4:2C:22:01:39',
//     model: 'CF398BLE',
//   );
//   late TextEditingController specialInputController =
//       TextEditingController(text: widget.weight ?? '00.0');
//   bool connectFailState = false;
//   bool connectSuccessState = false;
//   bool isConnect = false;

//   @override
//   void initState() {
//     connect();

//     worker.successEvent.addListener(_onSuccess);
//     worker.connectErrorEvent.addListener(_onConnectFail);
//     worker.connectedEvent.addListener(_onConnectSuccess);

//     super.initState();
//   }

//   Future<void> connect() async {
//     connectFailState = false;
//     isConnect = true;
//     connectSuccessState = false;
//     setState(() {});
//     await worker.connect();
//   }

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

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

//   void _onSuccess(_, double e) {
//     setState(() {
//       specialInputController.text = e.toString();
//       // connectFailState = false;
//       // connectSuccessState = false;
//       isConnect = false;
//       // disconnect();
//     });
//   }

//   void _onConnectFail(sender, e) {
//     print('连接设备失败');
//     connectFailState = true;
//     connectSuccessState = false;
//     isConnect = false;
//     disconnect();
//     setState(() {});
//   }

//   void _onConnectSuccess(sender, e) {
//     connectSuccessState = true;
//     connectFailState = false;
//     isConnect = false;
//     setState(() {});
//   }

//   @override
//   Widget build(BuildContext context) {
//     return VAlertDialog(
//       title: widget.currentFormObject.label ?? '',
//       width: 600,
//       contentPadding: const EdgeInsets.symmetric(vertical: 12, horizontal: 24),
//       content: buildMainWidget(),
//       showCancel: true,
//       onConfirm: () {
//         disconnect();
//         Get.back(result: specialInputController.text);
//       },
//       onCanceled: () {
//         disconnect();
//       },
//     );
//   }

//   Widget buildInputField() {
//     return Container(
//       width: 350,
//       padding: const EdgeInsets.only(left: 15),
//       child: TextFormField(
//         keyboardType: TextInputType.number,
//         style: const TextStyle(
//           fontSize: 100,
//         ),
//         showCursor: false,
//         controller: specialInputController,
//         decoration: const InputDecoration(
//           labelStyle: TextStyle(
//             fontSize: 100,
//           ),
//         ),
//       ),
//     );
//   }

//   Widget buildConnectFailText() {
//     return const Text(
//       '设备连接失败',
//       style: TextStyle(
//         color: Colors.red,
//         fontSize: 25,
//       ),
//       textAlign: TextAlign.left,
//     );
//   }

//   Widget buildConnectSuccessText() {
//     return const Text(
//       '设备连接成功',
//       style: TextStyle(
//         color: Colors.green,
//         fontSize: 25,
//       ),
//       textAlign: TextAlign.left,
//     );
//   }

//   Widget buildConnectingText() {
//     return const Row(
//       children: [
//         Expanded(
//           child: Text(
//             '设备连接中',
//             style: TextStyle(
//               fontSize: 40,
//               color: Colors.blue,
//             ),
//           ),
//         ),
//         CircularProgressIndicator(
//           valueColor: AlwaysStoppedAnimation(
//             Colors.blue,
//           ),
//         ),
//         SizedBox(
//           width: 20,
//         ),
//       ],
//     );
//   }

//   Widget buildReconnectButton() {
//     return Container(
//       margin: const EdgeInsets.only(top: 4),
//       width: 134,
//       child: VButton(
//         onTap: () async {
//           /// TODO
//           await connect();
//           worker.connectErrorEvent.addListener(_onConnectFail);
//           worker.connectedEvent.addListener(_onConnectSuccess);

//           /// TODO 后面需要改，这边暂时演示用
//           Future.delayed(const Duration(milliseconds: 8000), () {
//             if (!connectSuccessState) {
//               connectFailState = true;
//             }
//           });
//         },
//         child: const Row(
//           mainAxisAlignment: MainAxisAlignment.center,
//           children: [
//             Icon(Icons.connected_tv_rounded, size: 24),
//             SizedBox(
//               width: 8,
//             ),
//             Text("重连", style: TextStyle(fontSize: 20)),
//           ],
//         ),
//       ),
//     );
//   }

//   Widget buildConnectStateWidgets() {
//     return Column(
//       children: [
//         if (connectFailState) buildConnectFailText(),
//         if (connectSuccessState) buildConnectSuccessText(),
//         if (isConnect)
//           buildConnectingText()
//         else if (connectFailState)
//           buildReconnectButton(),
//       ],
//     );
//   }

//   Widget buildMainWidget() {
//     return SizedBox(
//       height: 100,
//       child: Row(
//         children: [
//           buildInputField(),
//           Expanded(
//             child: buildConnectStateWidgets(),
//           ),
//         ],
//       ),
//     );
//   }
// }
