import 'package:flutter/material.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:get/get.dart';
import 'package:fis_common/logger/logger.dart';

enum _RebootStep {
  ready,
  turnOff,
  turnOn,
  done,
  error,
}

final _stepDescMap = <_RebootStep, String>{
  _RebootStep.ready: "等待重启蓝牙",
  _RebootStep.turnOff: "正在关闭蓝牙",
  _RebootStep.turnOn: "正在打开蓝牙",
  _RebootStep.done: "重启蓝牙完成",
};

class BluetoothRebootDialog extends StatefulWidget {
  const BluetoothRebootDialog({super.key});

  static Future<String?> run() async {
    final result = await Get.dialog(
      const BluetoothRebootDialog(),
      barrierDismissible: false,
    );
    return result;
  }

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

class _BluetoothRebootDialogState extends State<BluetoothRebootDialog> {
  _RebootStep currStep = _RebootStep.ready;
  String? errorMessage;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      if (mounted) {
        doNext();
      }
    });
  }

  Future<void> doNext() async {
    bool ret = false;
    switch (currStep) {
      case _RebootStep.ready:
        ret = await turnOff();
        break;
      case _RebootStep.turnOff:
        ret = await turnOn();
        break;
      case _RebootStep.turnOn:
        ret = await reportDone();
        break;
      case _RebootStep.done:
        await Future.delayed(const Duration(milliseconds: 1500)); // 展示信息
        ret = false; // 完成并推出
        break;
      default:
        return;
    }
    if (ret) {
      setState(() {
        currStep = _RebootStep.values[currStep.index + 1];
      });
      // 继续下一步
      Future.delayed(const Duration(milliseconds: 500), doNext);
    } else {
      exit();
    }
  }

  /// 退出
  void exit() async {
    if (errorMessage != null) {
      setState(() {
        currStep = _RebootStep.error;
      });
      await Future.delayed(const Duration(milliseconds: 1500)); // 展示信息
    }
    Get.back(result: errorMessage);
  }

  Future<bool> turnOff() async {
    try {
      final isOn = await FlutterBluePlus.isOn;
      if (isOn) {
        await FlutterBluePlus.turnOff();
      }
      return true;
    } catch (e) {
      logger.e("BluetoothRebootDialog turn bluetooth off error", e);
      errorMessage = "关闭蓝牙失败";
      return false;
    }
  }

  Future<bool> turnOn() async {
    try {
      await FlutterBluePlus.turnOn();
      return true;
    } catch (e) {
      logger.e("BluetoothRebootDialog turn bluetooth on error", e);
      errorMessage = "启动蓝牙失败";
      return false;
    }
  }

  Future<bool> reportDone() async {
    await Future.delayed(const Duration(milliseconds: 200));
    return true;
  }

  @override
  Widget build(BuildContext context) {
    final body = buildBody(context);
    return AlertDialog(
      contentPadding: const EdgeInsets.symmetric(horizontal: 32, vertical: 28),
      content: body,
    );
  }

  Widget buildBody(BuildContext context) {
    final showLoading = currStep.index < _RebootStep.done.index;

    final message = errorMessage ?? _stepDescMap[currStep]!;

    List<Widget> children = [];
    children.add(
      Text(
        message,
        style: const TextStyle(fontSize: 20),
      ),
    );

    if (showLoading) {
      children.add(const SizedBox(width: 8));
      children.add(
        const SizedBox(
          width: 20,
          height: 20,
          child: CircularProgressIndicator(),
        ),
      );
    }

    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: children,
    );
  }
}
