import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:get/get.dart';

import 'package:vnote_device_plugin/devices/searcher.dart';
import 'package:vnote_device_plugin/models/device.dart';

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

  final String type;

  static Future<DeviceInfo?> dialog(String type) async {
    return Get.dialog(
      AlertDialog(
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
        title: const Text("搜索设备"),
        content: SizedBox(
          height: 280,
          width: 400,
          child: SearchDialog(type: type),
        ),
        actionsAlignment: MainAxisAlignment.center,
        actions: [
          SizedBox(
            width: 360,
            child: TextButton(
              onPressed: () {
                Get.back();
              },
              child: const Text(
                "取消",
                style: TextStyle(color: Colors.blue, fontSize: 20),
              ),
            ),
          ),
        ],
      ),
      barrierDismissible: false,
    );
  }

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

class _SearchDialogState extends State<SearchDialog> {
  String? value;

  DeviceSearcher? searcher;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      if (mounted) {
        searcher = DeviceSearcher(widget.type);
        searcher!.init();
        searcher!.successEvent.addListener(onSuccess);
        searcher!.start();
      }
    });
  }

  @override
  void dispose() {
    if (searcher != null) {
      searcher!.successEvent.removeListener(onSuccess);
      searcher!.stop().then((value) {
        searcher!.dispose();
        searcher = null;
      });
    }

    super.dispose();
  }

  void onSuccess(_, DeviceInfo e) {
    if (value != null) return;

    print(jsonEncode(value.toString()));
    setState(() {
      value = e.mac;
      Future.delayed(const Duration(seconds: 2), () {
        Get.back(result: e);
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    Widget child;
    if (value == null) {
      child = _buildWorking();
    } else {
      child = _buildDone();
    }
    return Container(
      alignment: Alignment.center,
      // decoration: BoxDecoration(borderRadius: BorderRadius.circular(24)),
      child: child,
    );
  }

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

  Widget _buildDone() {
    return Row(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        const Icon(Icons.check_circle, color: Colors.green, size: 32),
        const SizedBox(width: 12),
        Column(
          mainAxisSize: MainAxisSize.min,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Text(
              "MAC地址：",
              style: TextStyle(fontSize: 24),
            ),
            const SizedBox(height: 8),
            Text(
              value!,
              style: const TextStyle(fontSize: 24),
            ),
          ],
        ),
      ],
    );
  }
}
