import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:vitalapp/architecture/utils/prompt_box.dart';
import 'package:vnote_device_plugin/devices/searcher.dart';
import 'package:vnote_device_plugin/models/device.dart';
import 'package:vitalapp/components/alert_dialog.dart';

import 'consts.dart';

class DeviceSearchDialog extends StatefulWidget {
  const DeviceSearchDialog({
    Key? key,
    required this.type,
  }) : super(key: key);

  final String type;

  static Future<DeviceInfo?> dialog(String type) {
    // return Get.dialog(
    //   DeviceSearchDialog(type: type),
    //   barrierDismissible: false,
    // );

    return VAlertDialog.showDialog<DeviceInfo?>(DeviceSearchDialog(type: type));
  }

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

class _DialogState extends State<DeviceSearchDialog> {
  DeviceSearcher? searcher;
  DeviceInfo? deviceInfo;
  String? errorMsg;
  bool showDialogCancel = true;

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      if (mounted) {
        searcher = DeviceSearcher(widget.type);
        searcher!.successEvent.addListener(_onSuccess);
        searcher!.failEvent.addListener(_onFail);
        searcher!.timeoutEvent.addListener(_onTimeout);
        searcher!.start();
      }
    });
    super.initState();
  }

  @override
  void dispose() {
    if (searcher != null) {
      searcher!.successEvent.removeListener(_onSuccess);
      searcher!.failEvent.removeListener(_onFail);
      searcher!.timeoutEvent.removeListener(_onTimeout);
      searcher!.stop().then((value) {
        searcher = null;
      });
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final child = deviceInfo == null
        ? _LoadingWidget(type: widget.type)
        : _ResultWidget(
            isSuccess: true,
            message: errorMsg,
          );
    return VAlertDialog(
      title: "搜索设备",
      content: child,
      showCancel: showDialogCancel,
    );
  }

  void _onSuccess(_, DeviceInfo e) {
    setState(() {
      showDialogCancel = false; // 此时不可手动取消Dialog，否则结果无法回传
      deviceInfo = e;
      Future.delayed(const Duration(seconds: 2), () {
        Get.back(result: e);
      });
    });
  }

  void _onFail(_, String? e) {
    setState(() {
      errorMsg = e ?? "";
    });
  }

  void _onTimeout(_, e) {
    Get.back();
    Future.delayed(const Duration(milliseconds: 100), () {
      PromptBox.toast("未搜索到设备");
    });
  }
}

class _LoadingWidget extends StatelessWidget {
  final String type;

  const _LoadingWidget({required this.type});

  @override
  Widget build(BuildContext context) {
    final typeName = DevicesSettingConsts.getDeviceNameByType(type);

    return Column(
      mainAxisSize: MainAxisSize.min,
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        const SizedBox(height: 36),
        const SizedBox(
          height: 24,
          width: 24,
          child: CircularProgressIndicator(),
        ),
        const SizedBox(height: 36),
        Text(
          "正在搜索$typeName...",
          style: const TextStyle(fontSize: 20),
        ),
      ],
    );
  }
}

class _ResultWidget extends StatelessWidget {
  final bool isSuccess;
  final String? message;

  const _ResultWidget({
    required this.isSuccess,
    this.message,
  });

  @override
  Widget build(BuildContext context) {
    final icon = isSuccess
        ? const Icon(Icons.check_circle, color: Colors.green, size: 32)
        : const Icon(Icons.cancel, color: Colors.red, size: 32);
    return Container(
      height: 120,
      alignment: Alignment.center,
      child: Row(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          icon,
          const SizedBox(width: 12),
          Text(
            isSuccess ? "已搜索到设备" : (message ?? "未搜索到设备"),
            style: const TextStyle(fontSize: 20),
          ),
        ],
      ),
    );
  }
}
