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:flutter/services.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/lab/color/lab_dark_colors.dart';
import 'package:flyinsono/lab/env/env.dart';
import 'package:flyinsono/lab/pages/lab_record_info/widgets/alert_dialog.dart';
import 'package:get/get.dart';

import 'index.dart';
import 'widgets/exist_address_selected.dart';
import 'widgets/protocol_select.dart';

const String httpsProtocol = 'https';
const String httpProtocol = 'http';

class ServerSettingPage extends FStatelessWidget implements FPage {
  ServerSettingPage(
      {this.pageName = 'ServerSettingPage',
      this.isOpenInSettingPage,
      this.addServerListCallback,
      Key? key})
      : super(key: key);
  @override
  final String pageName;

  /// 设置页面打开的网络配置
  final bool? isOpenInSettingPage;

  /// 添加服务器地址的返回
  final VoidCallback? addServerListCallback;
  final controller = Get.put(ServerSettingController());
  @override
  FWidget build(BuildContext context) {
    return context.fResponsiveVoid(
      mobile: () => _ServerSettingView(
        this,
        isOpenInSettingPage: isOpenInSettingPage,
        addServerListCallback: addServerListCallback,
      ),
      desktop: () => _ServerSettingView(
        this,
        isOpenInSettingPage: isOpenInSettingPage,
        addServerListCallback: addServerListCallback,
      ),
    );
  }
}

class _ServerSettingView extends FisView<ServerSettingController> {
  static final _labelStyle = TextStyle(
    fontSize: 16,
    color: kIsLab ? LabColorConfig.text800 : Colors.black,
  );

  ///父级节点
  final FPage businessParent;
  final _portInputController = TextEditingController();
  late final _state = controller.state;
  final bool? isOpenInSettingPage;

  /// 添加服务器地址的返回
  final VoidCallback? addServerListCallback;
  _ServerSettingView(
    this.businessParent, {
    this.isOpenInSettingPage,
    this.addServerListCallback,
  });
  @override
  FWidget build(BuildContext context) {
    final padding = EdgeInsets.symmetric(
      vertical: 40,
      horizontal: kIsMobile ? 20 : 40,
    );
    if (kIsLab)
      return QuickFWidget(
        LabAlertDialog(
            title: i18nBook.user.setting.t,
            content: Container(
              padding: EdgeInsets.symmetric(horizontal: 20),
              child: _buildBody(),
            ),
            confirmText: "添加",
            onConfirm: () async {
              await controller.onSettingAddressAdding(
                isOpenInSettingPage,
                addServerListCallback ?? () {},
              );
            },
            cancelText: "提交",
            onCancel: () {
              controller.onSubmit();
            }),
      );
    return FSimpleDialog(
      title: _buildTitle(),
      contentPadding: padding,
      okString: i18nBook.common.confirm.t,
      cancelString: i18nBook.common.cancel.t,
      insetPadding: EdgeInsets.symmetric(horizontal: 10),
      children: [
        _buildBody(),
      ],
      bottomButton:
          isOpenInSettingPage ?? false ? _buildSettingFooter() : _buildFooter(),
    );
  }

  FWidget _buildBody() {
    return FContainer(
      alignment: Alignment.centerLeft,
      child: _buildAddressRow(),
    );
  }

  FWidget _buildAddressRow() {
    return FColumn(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        if (isOpenInSettingPage != true) ...[
          FObx(
            () => ExistAddressSelected(
              controller.state.options.toList(),
              (data) {
                controller.onAddressOptionChanged(data);
              },
              (data) {
                controller.onAddressOptionDeleted(data);
              },
              _state.currentAddressName,
            ),
          ),
          const FSizedBox(height: 30),
          FDivider(
            color: Colors.grey,
            thickness: 1.0,
          ),
          _verticalSpacing(),
        ],
        FText(
          i18nBook.setting.addServer.t,
          style: TextStyle(
            fontWeight: FontWeight.bold,
            color: kIsLab ? LabColorConfig.text800 : Colors.black,
          ),
        ),
        _verticalSpacing(),
        ProtocolSelect((p) {
          controller.state.protocol = p;
        }),
        _verticalSpacing(),
        if (kIsMobile) ...[
          FColumn(
            children: [
              FRow(
                children: [
                  FContainer(
                    width: 80,
                    child:
                        FText(i18nBook.setting.serverUrl.t, style: _labelStyle),
                  ),
                  _buildAddressInput(),
                ],
              ),
              _verticalSpacing(),
              FRow(
                children: [
                  FContainer(
                    width: 80,
                    child: FText(i18nBook.setting.serverPort.t,
                        style: _labelStyle),
                  ),
                  FFlexible(
                    child: _buildPortInput(),
                    flex: 0,
                  ),
                ],
              ),
            ],
          ),
        ] else ...[
          FRow(
            mainAxisSize: MainAxisSize.min,
            children: [
              FText(i18nBook.setting.serverUrl.t, style: _labelStyle),
              _buildAddressInput(),
              const FSizedBox(width: 32),
              FText(i18nBook.setting.serverPort.t, style: _labelStyle),
              FFlexible(
                child: _buildPortInput(),
                flex: 0,
              ),
            ],
          ),
        ],
      ],
    );
  }

  FWidget _verticalSpacing() {
    return FSizedBox(height: 15);
  }

  /// 地址输入框
  FWidget _buildAddressInput() {
    return FContainer(
      width: kIsMobile ? 200 : 180,
      child: FTextField(
        controller: controller.serverInputController,
        decoration: FBorderInput.buildDecoration(
          height: 40,
          hintText: i18nBook.setting.serverUrlExample.t,
          hintSize: 13,
          borderColor: kIsLab ? LabColorConfig.text800 : Colors.grey,
        ).copyWith(
            // hintStyle: _labelStyle,
            ),
        style: _labelStyle,
        maxLength: 100,
      ),
    );
  }

  FWidget _buildPortInput() {
    return FObx(() {
      _portInputController.value = _portInputController.value
          .copyWith(text: _state.currentPort.toString());
      return FBorderInput(
        controller: _portInputController,
        hintText: i18nBook.setting.serverPortExample.t,
        width: 100,
        height: 40,
        onChanged: (port) => controller.onPortChanged(port),
        borderColor: kIsLab ? LabColorConfig.text800 : Colors.grey,
        maxLength: 5,
        // hintStyle: _labelStyle,
        textStyle: _labelStyle,
        inputFormatters: <TextInputFormatter>[
          FilteringTextInputFormatter.digitsOnly
        ],
      );
    });
  }

  FWidget _buildTitle() {
    return FText(
      i18nBook.user.setting.t,
      style: const TextStyle(
        color: Colors.white,
        fontSize: 18,
      ),
    );
  }

  FWidget _buildSettingFooter() {
    return FContainer(
      alignment: Alignment.center,
      padding: EdgeInsets.symmetric(vertical: 15),
      child: FFlex(
        direction: Axis.horizontal,
        mainAxisSize: MainAxisSize.min,
        children: [
          _buildAddBtn(),
        ],
      ),
    );
  }

  FWidget _buildFooter() {
    return FContainer(
      alignment: Alignment.center,
      padding: EdgeInsets.symmetric(vertical: 15),
      child: FFlex(
        direction: Axis.horizontal,
        mainAxisSize: MainAxisSize.min,
        children: [
          _buildAddBtn(),
          const FSizedBox(width: 20),
          _buildSubmitBtn(),
        ],
      ),
    );
  }

  FWidget _buildAddBtn() {
    return FContainer(
      width: 95,
      child: FElevatedButton(
        name: "add",
        businessParent: businessParent,
        style: ButtonStyle(
          padding: MaterialStateProperty.all(
            const EdgeInsets.symmetric(
              vertical: 15,
              horizontal: 0,
            ),
          ),
        ),
        child: FText(i18nBook.common.add.t),
        onPressed: () async {
          await controller.onSettingAddressAdding(
            isOpenInSettingPage,
            addServerListCallback ?? () {},
          );
        },
      ),
    );
  }

  FWidget _buildSubmitBtn() {
    return FContainer(
      width: 95,
      child: FElevatedButton(
        name: "confirm",
        businessParent: businessParent,
        style: ButtonStyle(
          padding: MaterialStateProperty.all(
            const EdgeInsets.symmetric(vertical: 15, horizontal: 0),
          ),
        ),
        child: FText(i18nBook.common.confirm.t),
        onPressed: () {
          controller.onSubmit();
        },
      ),
    );
  }
}
