import 'package:fis_i18n/i18n.dart';
import 'package:fis_theme/theme.dart';
import 'package:fis_ui/base_define/page.dart';
import 'package:fis_ui/index.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/router/index.dart';
import 'package:flyinsono/architecture/utils/prompt_box.dart';
import 'package:fis_lib_qrcode/qr_flutter.dart';
import 'package:flyinsono/managers/server_config_manager.dart';
import 'package:flyinsono/pages/remedical/consultation/controller.dart';
import 'package:flyinsono/pages/user/user_center/widgets/desk_top_module_card.dart';
import 'package:get/get.dart';
import 'package:flyinsono/rpc.dart';
import 'package:fis_common/index.dart';

class ReportShareDialog extends FStatefulWidget implements FPage {
  ///报告Url
  final String repotUrl;

  /// 实时诊断给的报告code
  final String? reportToShare;
  late final bool isQROnly;
  @override
  final String pageName;
  ReportShareDialog(
    this.repotUrl,
    this.reportToShare, {
    bool isQROnly = false,
    this.pageName = 'ReportShareDialog',
  }) {
    this.isQROnly = isQROnly;
  }

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

class ReportShareDialogState extends FState<ReportShareDialog> {
  final controller = Get.find<ConsultationController>();
  bool _isEmailShare = false;

  ///报告分享内容列表
  List<FWidget> _children = [];

  ///手机号集合视图
  late FWidget _numbersView;

  late bool _isDefault;

  ///短信分享手机号集合
  List<String> _phones = [];

  ///邮箱分享集合
  List<String> _emails = [];

  @override
  void initState() {
    _isEmailShare = controller.state.isEmailShare;
    _numbersView = _buildPhoneOrEmailNumbersView();
    _children = widget.isQROnly
        ? _children = [_buildQrcode()]
        : _getReportShareChildren();
    _phones = controller.state.selectedPhoneNumbers;
    _emails = controller.state.selectedEmails;
    _isDefault = false;
    super.initState();
  }

  @override
  FWidget build(BuildContext context) {
    return FSimpleDialog(
      contentPadding: EdgeInsets.symmetric(vertical: 25, horizontal: 25),
      title: FText(
        i18nBook.remedical.share.t,
        style: TextStyle(
          color: Colors.white,
          fontSize: 18,
        ),
      ),
      okString: i18nBook.common.confirm4Btn.t,
      onClose: () {
        _clearContrastData();
        router.back();
      },
      cancelString: i18nBook.common.cancel.t,
      insetPadding: EdgeInsets.symmetric(vertical: 100),
      children: [
        FContainer(
          child: FRow(
            mainAxisAlignment: MainAxisAlignment.center,
            children: _children,
          ),
        ),
      ],
      isDefault: _isDefault,
      onOk: () async {
        _isEmailShare
            ? await controller.submitShareEmail(widget.reportToShare)
            : await controller.submitShareSMS(widget.reportToShare);
        _clearContrastData();
      },
      onCancel: () {
        if (widget.isQROnly) {
          router.back();
        } else {
          setState(() {
            _children = _getReportShareChildren();
            _clearContrastData();
            _isDefault = false;
          });
        }
      },
    );
  }

  void _clearContrastData() {
    _phones = [];
    controller.state.selectedPhoneNumbers = [];
    controller.state.selectedEmails = [];
    _emails = [];
    controller.targetAcountController.text = "";
  }

  ///二维码
  FWidget _buildQrcode() {
    return FColumn(
      children: [
        FContainer(
          width: 360,
          child: FContainer(
            padding: const EdgeInsets.only(top: 20, bottom: 20),
            child: QRCodeWithLogo(
              widget.repotUrl,
              codeStatement: i18nBook.remedical.scanQrCodeToShare.t,
              operationStatement: i18nBook.remedical.copyLink.t,
              operationSuccessCallback: () {
                if (FPlatform.isWindows || FPlatform.isMacOS) {
                  rpc.platform.copyToClipboard(widget.repotUrl);
                }
                PromptBox.toast(i18nBook.remedical.copySuccess.t);
              },
            ),
          ),
        ),
        const FSizedBox(height: 10),
        _buildCancelButton(),
      ],
    );
  }

  ///报告分享选择项
  List<FWidget> _getReportShareChildren() {
    List<FWidget> children = [];
    final space = 20.0;
    children = [
      FSizedBox(
        width: space,
        height: 240,
      ),
      if (ServerConfigManager.isSMSOn) ...[
        DesktopModuleCard(
          businessParent: widget,
          label: i18nBook.remedical.shortMessage.t,
          iconData: Icons.message,
          width: i18nBook.isCurrentChinese ? null : 320,
          onPressed: () {
            setState(() {
              _isEmailShare = false;
              _numbersView = _buildPhoneOrEmailNumbersView();
              _children = _buildShareContentView();
              _isDefault = true;
            });
          },
        ),
      ],
      FSizedBox(width: space),
      DesktopModuleCard(
        businessParent: widget,
        label: i18nBook.common.email.t,
        iconData: Icons.email,
        width: i18nBook.isCurrentChinese ? null : 320,
        onPressed: () {
          setState(() {
            _isEmailShare = true;
            _numbersView = _buildPhoneOrEmailNumbersView();
            _children = _buildShareContentView();
            _isDefault = true;
          });
        },
      ),
      FSizedBox(width: space),
      DesktopModuleCard(
        businessParent: widget,
        label: i18nBook.remedical.qrCode.t,
        iconData: Icons.qr_code,
        width: i18nBook.isCurrentChinese ? null : 320,
        onPressed: () {
          setState(() {
            _children = [_buildQrcode()];
          });
        },
      ),
      FSizedBox(width: space),
    ];
    return children;
  }

  ///短信分享or邮箱分享
  List<FWidget> _buildShareContentView() {
    List<FWidget> children = [
      const FSizedBox(
        height: 340,
        width: 40,
      ),
      FColumn(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          FRow(
            children: [
              FSizedBox(height: 40),
              FContainer(
                width: 440,
                child: FTextField(
                  onEditingComplete: () {
                    _isEmailShare ? _addShareEmail() : _addSharePhoneNumber();
                  },
                  controller: controller.targetAcountController,
                  decoration: InputDecoration(
                    hintText: _isEmailShare
                        ? i18nBook.user.InputEmail.t
                        : i18nBook.profileComplete.phoneNumberPlaceHolder.t,
                    fillColor: Colors.white,
                    filled: true,
                    contentPadding:
                        EdgeInsets.symmetric(vertical: 10, horizontal: 15),
                    hintStyle: TextStyle(
                      fontSize: 16,
                      color: Colors.black54,
                    ),
                    alignLabelWithHint: true,
                    counterText: '',
                    isDense: true,
                    enabledBorder: OutlineInputBorder(
                      borderSide: BorderSide(
                        color: FTheme.ins.colorScheme.primary,
                      ),
                    ),
                    focusedBorder: OutlineInputBorder(
                      borderSide: BorderSide(
                        color: FTheme.ins.colorScheme.primary,
                      ),
                    ),
                  ),
                ),
              ),
              FSizedBox(width: 10),
              FContainer(
                child: FElevatedButton(
                  businessParent: this.widget,
                  name: "isEmailShare:$_isEmailShare",
                  onPressed: () {
                    _isEmailShare ? _addShareEmail() : _addSharePhoneNumber();
                  },
                  style: ButtonStyle(
                    padding: MaterialStateProperty.all(
                      EdgeInsets.symmetric(
                        vertical: 15,
                        horizontal: 25,
                      ),
                    ),
                    alignment: Alignment.center,
                  ),
                  child: FText(i18nBook.common.add.t),
                ),
              )
            ],
          ),
          const FSizedBox(height: 10),
          FText(i18nBook.common.added.t),
          const FSizedBox(height: 10),
          _numbersView,
          const FSizedBox(height: 40),
        ],
      ),
      const FSizedBox(
        height: 340,
        width: 40,
      ),
    ];
    return children;
  }

  ///单个手机号码
  FWidget _buildPhoneView(int index) {
    return FContainer(
      padding: EdgeInsets.fromLTRB(0, 0, 0, 5),
      child: FRow(
        mainAxisSize: MainAxisSize.min,
        children: [
          FText(_isEmailShare ? _emails[index] : _phones[index]),
          const FSizedBox(width: 5),
          FContainer(
            alignment: Alignment.center,
            child: FMouseRegion(
              cursor: SystemMouseCursors.click,
              child: FGestureDetector(
                businessParent: this.widget,
                name: "removeAt:$index",
                onTap: () {
                  _isEmailShare
                      ? controller.state.selectedEmails.removeAt(index)
                      : controller.state.selectedPhoneNumbers.removeAt(index);
                  setState(() {
                    _isEmailShare
                        ? _emails = controller.state.selectedEmails
                        : _phones = controller.state.selectedPhoneNumbers;
                    _numbersView = _buildPhoneOrEmailNumbersView();
                    _children = _buildShareContentView();
                  });
                },
                child: FIcon(
                  Icons.close,
                  size: 20,
                  color: FTheme.ins.colorScheme.primary,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  FWidget _buildPhoneOrEmailNumbersView() {
    return FContainer(
      width: 440,
      height: 300,
      padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 15),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(
          8.0,
        ),
        border: Border.all(
          width: 1.0,
          color: FTheme.ins.colorScheme.primary,
        ),
      ),
      child: _buildContrastListView(),
    );
  }

  FWidget _buildContrastListView() {
    return FSingleChildScrollView(
      padding: const EdgeInsets.symmetric(vertical: 2),
      child: _isEmailShare
          ? FContainer(
              child: FColumn(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: _generateContrastItems(),
              ),
            )
          : FWrap(
              alignment: WrapAlignment.start,
              spacing: 20,
              children: _generateContrastItems(),
            ),
    );
  }

  List<FWidget> _generateContrastItems() {
    return List.generate(
      _isEmailShare ? _emails.length : _phones.length,
      ((index) => _buildPhoneView(index)),
    );
  }

  void _addSharePhoneNumber() {
    controller.addSharePhoneNumbers();
    setState(() {
      _phones = controller.state.selectedPhoneNumbers;
      _numbersView = _buildPhoneOrEmailNumbersView();
      _children = _buildShareContentView();
    });
  }

  _addShareEmail() {
    controller.addShareEmail();
    setState(() {
      _emails = controller.state.selectedEmails;
      _numbersView = _buildPhoneOrEmailNumbersView();
      _children = _buildShareContentView();
    });
  }

  ///取消按钮
  FWidget _buildCancelButton() {
    return FBottomCanCelButton(
      businessParent: this.widget,
      name: "cancel",
      radius: 4,
      height: 35,
      onPressed: () {
        if (widget.isQROnly) {
          router.back();
        } else {
          setState(() {
            _children = _getReportShareChildren();
            if (_isEmailShare) {
              controller.state.selectedEmails = [];
              _emails = [];
            } else {
              _phones = [];
              controller.state.selectedPhoneNumbers = [];
            }
            controller.targetAcountController.text = '';
            _isDefault = false;
          });
        }
      },
      title: i18nBook.common.cancel.t,
    );
  }
}
