import 'dart:convert';

import 'package:fis_common/index.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:fis_ui/base_define/page.dart';
import 'package:fis_ui/index.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/utils/prompt_box.dart';
import 'package:flyinsono/managers/interfaces/vboxcontrol.dart';
import 'package:get/get.dart';

import 'network_config_card.dart';

class NetworkWifiCard extends FStatefulWidget implements FPage {
  final List<Point> networks;
  final List<Interface> cardInfos;
  const NetworkWifiCard({required this.networks, required this.cardInfos});
  @override
  String get pageName => 'NetworkWifiCard';
  @override
  _NetworkWifiCard createState() => _NetworkWifiCard();
}

class _NetworkWifiCard extends FState<NetworkWifiCard> {
  late List<Point> _networks;
  final _applicationScrollController = ScrollController();
  var vBoxControl = Get.find<IVBoxControlManager>();
  late Point? currentWifiInfo;
  late bool isProperties = false;
  @override
  void initState() {
    super.initState();
    _networks = widget.networks;
    currentWifiInfo = null;
  }

  @override
  FWidget build(BuildContext context) {
    return FScrollbar(
      controller: _applicationScrollController,
      isAlwaysShown: true,
      child: FListView(
        shrinkWrap: true,
        controller: _applicationScrollController,
        children: [
          if (isProperties)
            if (isProperties)
              FContainer(
                margin: EdgeInsets.symmetric(vertical: 5),
                child: FColumn(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    NetworkConfigCards(cardInfos: widget.cardInfos),
                    FSizedBox(
                      height: 20,
                    ),
                    _buildCommonButton(i18nBook.common.save.t, () {
                      _onSave(widget.cardInfos[0]);
                    }),
                  ],
                ),
              ),
          if (!isProperties)
            FCenter(
              child: FWrap(
                runSpacing: 0,
                spacing: 45,
                children: (_networks).map((e) => _buildWifiItem(e)).toList(),
              ),
            ),
        ],
      ),
    );
  }

  FWidget _buildWifiIcon(int signalStrength) {
    var level = 0;
    if (signalStrength > 85) {
      level = 4;
    } else if (signalStrength > 55) {
      level = 3;
    } else if (signalStrength > 30) {
      level = 2;
    } else {
      level = 1;
    }

    return FImage.asset(
      'assets/images/wifi/wifi-$level.png',
      width: 30,
      fit: BoxFit.contain,
    );
  }

  FWidget _buildWifiItem(Point e) {
    return FInkWell(
      child: FColumn(
        children: <FWidget>[
          FListTile(
            title: FRow(
              children: [
                _buildWifiIcon(int.parse(e.signalStrength!)),
                FSizedBox(width: 8.0),
                FText(e.name!),
                e.isConnected!
                    ? FRow(
                        children: [
                          FIcon(Icons.check, color: Colors.green),
                          FText(i18nBook.setting.connecting.t),
                        ],
                      )
                    : FContainer(),
              ],
            ),
            onTap: () {
              setState(() {
                if (e.id == currentWifiInfo?.id) {
                  currentWifiInfo = null;
                } else {
                  currentWifiInfo = e;
                }
              });
            },
          ),
          if (e.isConnected! && currentWifiInfo?.id == e.id)
            FRow(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: <FWidget>[
                _buildCommonButton(i18nBook.setting.properties.t, () async {
                  setState(() {
                    isProperties = true;
                  });
                }),
                _buildCommonButton(i18nBook.setting.disconnect.t, () async {
                  var wifiInfo = new NetworkConnectWifi(
                      name: e.name!, password: e.password ?? '');
                  var isSuccess = await vBoxControl.disconnectWifi(wifiInfo);
                  if (isSuccess) {
                    setState(() {
                      e.hasProfile = true;
                      e.isConnected = false;
                    });
                  } else {
                    PromptBox.toast(i18nBook.user.operationFailed.t);
                  }
                }),
                _buildCommonButton(i18nBook.setting.forgetPassword.t, () async {
                  var wifiInfo = new NetworkConnectWifi(
                      name: e.name!, password: e.password ?? '');
                  var isSuccess =
                      await vBoxControl.forgetWifiPassword(wifiInfo);
                  if (isSuccess) {
                    setState(() {
                      e.hasProfile = false;
                      e.isConnected = false;
                    });
                  } else {
                    PromptBox.toast(i18nBook.user.operationFailed.t);
                  }
                }),
              ],
            ),
          if (!e.isConnected! && !e.hasProfile! && currentWifiInfo?.id == e.id)
            FRow(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <FWidget>[
                FExpanded(
                  child: FPadding(
                    padding: const EdgeInsets.all(16.0),
                    child: FTextFormField(
                      decoration: InputDecoration(
                        labelText: i18nBook.auth.password.t,
                        border: OutlineInputBorder(),
                        isDense: true,
                        contentPadding: EdgeInsets.symmetric(
                            horizontal: 8.0, vertical: 4.0),
                      ),
                      obscureText: e.password.isNotNullOrEmpty,
                      obscuringCharacter: '･',
                      onChanged: (String value) {
                        setState(() {
                          e.password = value;
                        });
                      },
                    ),
                  ),
                ),
                _buildCommonButton(i18nBook.setting.connect.t, () async {
                  var wifiInfo = new NetworkConnectWifi(
                      name: e.name ?? '', password: e.password ?? '');
                  var isSuccess = await vBoxControl.connectWifi(wifiInfo);
                  if (isSuccess) {
                    setState(() {
                      e.isConnected = true;
                    });
                  } else {
                    PromptBox.toast(i18nBook.user.operationFailed.t);
                  }
                }),
              ],
            ),
          if (!e.isConnected! && e.hasProfile! && currentWifiInfo?.id == e.id)
            FRow(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: <FWidget>[
                _buildCommonButton(i18nBook.setting.connect.t, () async {
                  var wifiInfo = new NetworkConnectWifi(
                      name: e.name ?? '', password: e.password ?? '');
                  var isSuccess = await vBoxControl.connectWifi(wifiInfo);
                  if (isSuccess) {
                    setState(() {
                      e.hasProfile = true;
                      e.isConnected = true;
                    });
                  } else {
                    PromptBox.toast(i18nBook.user.operationFailed.t);
                  }
                }),
                _buildCommonButton(i18nBook.setting.forgetPassword.t, () async {
                  var wifiInfo = new NetworkConnectWifi(
                      name: e.name ?? '', password: e.password ?? '');
                  var isSuccess =
                      await vBoxControl.forgetWifiPassword(wifiInfo);
                  if (isSuccess) {
                    setState(() {
                      e.hasProfile = false;
                      e.isConnected = false;
                    });
                  } else {
                    PromptBox.toast(i18nBook.user.operationFailed.t);
                  }
                }),
              ],
            ),
        ],
      ),
    );
  }

  FWidget _buildCommonButton(String buttonName, VoidCallback onPressed) {
    return FContainer(
      width: 150,
      margin: EdgeInsets.symmetric(
        horizontal: 15,
      ),
      child: FElevatedButton(
        child: FText(buttonName),
        onPressed: () {
          onPressed.call();
        },
        businessParent: this.widget,
        name: buttonName,
        style: ElevatedButton.styleFrom(
          elevation: 0,
          padding: EdgeInsets.symmetric(
            vertical: 15,
            horizontal: 25,
          ),
        ),
      ),
    );
  }

  void _onSave(Interface interface) async {
    var isSuccess =
        await vBoxControl.saveWifiNetworkCard(json.encode(interface.toJson()));
    if (isSuccess) {
      setState(() {
        isProperties = false;
      });
    } else {
      PromptBox.toast(i18nBook.user.operationFailed.t);
    }
  }
}
