import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:keyboard_android/keyboard_android.dart';

import '../util/ToastUtil.dart';
import 'chat_page.dart';

/// 首页
class HomePage extends StatefulWidget {
  const HomePage({super.key, required this.title});

  /// 页面标题
  final String title;

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  /// 平台版本，安卓上就是获取安卓的系统版本号
  String _platformVersion = 'Unknown';

  /// 插件对象
  final _keyboardAndroidPlugin = KeyboardAndroid();

  /// 是否启用悬浮窗
  bool _enableFloatingWindow = true;

  @override
  void initState() {
    super.initState();
    _initPlatformState();
    // 初始化悬浮窗
    _keyboardAndroidPlugin.enableFloatingWindow(_enableFloatingWindow);
  }

  /// 获取平台版本
  Future<void> _initPlatformState() async {
    String platformVersion;
    try {
      platformVersion =
          await _keyboardAndroidPlugin.getPlatformVersion() ??
          'Unknown platform version';
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }

    if (!mounted) {
      return;
    }

    setState(() {
      _platformVersion = platformVersion;
    });
  }

  /// 跳转到聊天页面
  void _goChatPage(BuildContext context) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) {
          return ChatPage();
        },
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(widget.title)),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text('当前系统平台版本: $_platformVersion\n'),
            SwitchListTile(
              title: Text('开启、关闭悬浮窗功能'),
              value: _enableFloatingWindow,
              onChanged: (newValue) {
                _keyboardAndroidPlugin.enableFloatingWindow(newValue);
                setState(() {
                  _enableFloatingWindow = newValue;
                });
              },
            ),
            OutlinedButton(
              onPressed: () {
                _keyboardAndroidPlugin.openInputMethodSettings();
              },
              child: Text("打开输入法设置"),
            ),
            OutlinedButton(
              onPressed: () async {
                bool isTargetKeyboardEnabled =
                    await _keyboardAndroidPlugin.isTargetKeyboardEnabled();
                ToastUtil.showToast(isTargetKeyboardEnabled ? "可用" : "不可用");
              },
              child: Text("自定义键盘是否可用"),
            ),
            OutlinedButton(
              onPressed: () {
                _goChatPage(context);
              },
              child: Text("跳转到聊天页面"),
            ),
          ],
        ),
      ),
    );
  }
}
