import 'package:fis_ui/index.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/config/model.dart';
import 'package:flyinsono/architecture/utils/prompt_box.dart';
import 'package:flyinsono/global.dart';
import 'package:flyinsono/lab/color/lab_dark_colors.dart';
import 'package:flyinsono/lab/env/env.dart';
import 'package:flyinsono/managers/interfaces/server_config.dart';
import 'package:flyinsono/pages/setting/server_setting/state.dart';
import 'package:fis_common/logger/logger.dart';
import 'package:fis_ui/base_define/page.dart';
import 'package:fis_common/event/event_type.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:get/get.dart';
import 'package:fis_theme/theme.dart';

class ExistAddressSelected extends FStatefulWidget implements FPage {
  final List<ServerOptionModel> options;
  final void Function(ServerOptionModel) onSelectChanged;
  final void Function(ServerOptionModel) onDelete;
  final String? selectedValue;
  final bool isShowTitle;
  final bool isNeedChangeConfirm;
  final double? height;
  final double? width;

  ExistAddressSelected(
    this.options,
    this.onSelectChanged,
    this.onDelete,
    this.selectedValue, {
    this.isShowTitle = true,
    this.height,
    this.width = 300,
    this.isNeedChangeConfirm = false,
  });

  @override
  FState<FStatefulWidget> createState() {
    return ExistAddressSelectedState();
  }

  @override
  String get pageName => 'ExistAddressSelected';
}

class ExistAddressSelectedState extends FState<ExistAddressSelected> {
  List<ServerOptionModel> _options = [];
  String? _selectedValue;
  bool _isExpanded = false;
  FocusNode _focusNode = FocusNode();
  final FEventHandler<bool> _onReload = FEventHandler<bool>();

  @override
  void initState() {
    _options = widget.options;
    var selectedValue = widget.options
        .firstWhere((element) => element.disPlayName == widget.selectedValue);
    _selectedValue = selectedValue.fullAddress;
    super.initState();
  }

  @override
  void dispose() {
    _focusNode.dispose();
    super.dispose();
  }

  void didUpdateWidget(ExistAddressSelected oldWidget) {
    if (widget.options != _options) {
      setState(() {
        _options = widget.options;
      });
    }
    var selectedOption = widget.options.firstWhereOrNull(
        (element) => element.disPlayName == widget.selectedValue);
    var selectedValue = selectedOption?.fullAddress;
    if (_selectedValue != selectedValue) {
      setState(() {
        _selectedValue = selectedValue;
      });
    }
    super.didUpdateWidget(oldWidget);
  }

  @override
  FWidget build(BuildContext context) {
    FWidget title = FContainer(
      width: kIsMobile ? 100 : 120,
      child: FText(
        i18nBook.auth.selectServer.t,
        style: TextStyle(
          fontWeight: FontWeight.bold,
          color: kIsLab ? LabColorConfig.text800 : Colors.black,
        ),
      ),
    );

    return FRow(
      //  crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        if (widget.isShowTitle) ...[
          title,
          const FSizedBox(
            height: 15,
          ),
        ],
        if (kIsMobile) ...[
          FExpanded(
            child: _buildSelectAddress(),
          ),
        ] else ...[
          _buildSelectAddress(),
        ],
      ],
    );
  }

  FWidget specialWidget(ServerOptionModel data) {
    return FContainer(
      child: FRow(
        children: [
          FExpanded(
            child: FText(data.name),
          ),
          if (data.name != "杏聆荟科研工作站") ...[
            FIconButton(
              icon: FIcon(
                Icons.delete,
                color: Colors.grey,
              ),
              onPressed: () {
                widget.onDelete.call(data);
                if (Global.config.data.server.current != DefaultServerName) {
                  final currentUri = Global.config.data.server.currentUri!;

                  // 不可删除当前正在使用的网络地址
                  bool isCurrectNetWork = currentUri.host == data.host &&
                      currentUri.port.toString() == data.port;
                  // 数据更新
                  if (isCurrectNetWork) {
                    PromptBox.toast(
                        i18nBook.setting.currentServerAddressInUse.t);
                    return;
                  }
                }
                _options.remove(data);
                Future.delayed(Duration(microseconds: 500), () {
                  _onReload.emit(this, true);
                });
              },
              businessParent: widget,
              name: 'delete address',
            ),
          ],
        ],
      ),
    );
  }

  FWidget _buildSelectAddress() {
    return FSelect<ServerOptionModel, String>(
      source: _options,
      height: widget.height,
      width: kIsMobile ? null : widget.width,
      isExpanded: _isExpanded,
      optionLabelExtractor: (data) {
        return data.disPlayName;
      },
      value: _selectedValue,
      optionValueExtractor: (data) {
        return data.fullAddress;
      },
      focusNode: _focusNode,
      onReload: _onReload,
      textColor: kIsLab ? LabColorConfig.text800 : Colors.black,
      clearable: false,
      onSelectChanged: (value, index) {
        logger.i('ExistAddressSelected change select:$value');
        if (_selectedValue == widget.options[index!].fullAddress) {
          return;
        }
        if (widget.isNeedChangeConfirm) {
          changeNetwork(widget.options[index], index);
        } else {
          widget.onSelectChanged.call(widget.options[index]);
        }
      },
      fontFamily: FTheme.ins.localeSetting.fontFamily,
      specialWidgetHeight: 40,
      specialWidget: (data) {
        return specialWidget(data);
      },
    );
  }

  void changeNetwork(ServerOptionModel currChangedNetwork, int index) {
    FConfirmAlert.show(
      context: Get.context!,
      title: i18nBook.common.tip.t,
      subTitle: i18nBook.setting.switchCurrentServerRestartClient.t,
      businessParent: widget,
      confrimLabel: i18nBook.common.confirm.t,
      cancelLabel: i18nBook.common.cancel.t,
      onConfirm: () {
        widget.onSelectChanged.call(currChangedNetwork);
        setState(() {
          _selectedValue = widget.options[index].fullAddress;
        });
        Get.find<IServerConfigManager>().getAllServerConfig();
      },
      onCancel: () {
        setState(() {});
      },
    );
  }
}
