import 'package:fis_common/env/env.dart';
import 'package:fis_common/logger/logger.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:fis_lib_qrcode/qr_flutter.dart';
import 'package:fis_theme/theme.dart';
import 'package:fis_ui/base_define/page.dart';
import 'package:fis_ui/index.dart';
import 'package:fis_ui/values/font_sizes.dart';
import 'package:fis_ui/values/spacings.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/managers/interfaces/language.dart';
import 'package:flyinsono/managers/interfaces/user_info.dart';
import 'package:flyinsono/managers/server_config_manager.dart';
import 'package:flyinsono/pages/auth/auth_board/controller.dart';
import 'package:flyinsono/pages/auth/clause_view/checkrow.dart';
import 'package:flyinsono/pages/auth/widgets/checkbox.dart';
import 'package:flyinsono/pages/auth/widgets/code_field.dart';
import 'package:flyinsono/pages/auth/widgets/text_field.dart';
import 'package:flyinsono/pages/upgrade/upgrade_wrapper.dart';
import 'package:flyinsono/rpc.dart';
import 'package:get/get.dart';
import 'package:universal_html/html.dart' as html;

import '../widgets/button.dart';
import '../widgets/page_resizable_box.dart';
import 'controller.dart';

///登录界面
class SignInPage extends FisView<SignInController> implements FPage {
  @override
  final String pageName;

  const SignInPage({this.pageName = 'SignInPage', Key? key}) : super(key: key);

  @override
  FWidget build(BuildContext context) {
    return context.fResponsiveVoid(
      mobile: () => _MobileLayout(this),
      desktop: () => FPageResizableBox(
        builder: () => _DesktopLayout(this),
      ),
    );
  }
}

///账号密码文本框
class _AccountTextField extends FisView<SignInController> {
  @override
  FWidget build(BuildContext context) {
    return controller.state.isCodeSignIn
        ? _CodeAccountTextField()
        : _NormalAccountTextField();
  }
}

///验证码账号文本框
class _CodeAccountTextField extends FisView<SignInController> {
  final verificationCodeFieldController =
      Get.find<VerificationCodeFieldController>(
    tag: SignInController.C_VERIFICATION_CONTROLLER_TAG,
  );
  @override
  FWidget build(BuildContext context) {
    return FBorderTextFormField(
      initialValue: controller.state.codeAccount,
      maxLength: 254,
      onChanged: (val) {
        controller.state.codeAccount = val;
        verificationCodeFieldController.reset();
      },
      hintText: ServerConfigManager.isSMSOn
          ? i18nBook.auth.hint4AccountDouble.t
          : i18nBook.auth.enterEmail.t,
    );
  }
}

///验证码登录其他选项行布局页
///TODO 如果后续验证码登录无需其他选项，可以考虑删除此 Class
class _CodeSignInOtherOptionsRow extends FStatelessWidget {
  @override
  FWidget build(BuildContext context) {
    return FContainer();
  }
}

///登录界面PC端布局
class _DesktopLayout extends FisView<SignInController> implements FWidget {
  ///父级节点
  final FPage businessParent;

  final _authBoardController = Get.find<AuthBoardController>();

  _DesktopLayout(this.businessParent);
  @override
  FWidget build(BuildContext context) {
    final form = FForm(
      child: FColumn(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          FColumn(
            children: [
              _MethodTabBar(businessParent: businessParent),
              _MethodTabBarUnderLine(),
              FSizedBox(height: 68.sp),
              _MainItems(businessParent),
              _buildClauseCheckRow(),
            ],
          ),
          FContainer(
            height: 28.sp,
            child: _LanguageOptionsRow(businessParent),
          ),
        ],
      ),
    );
    return FContainer(
      color: Color.fromARGB(255, 247, 251, 255),
      child: FObx(
        () {
          controller.state.isAutoLogin;
          if (_authBoardController.state.isSwitchAuthBody) {
            ///仅在登录时可以显示
            return _buildQRCodeLoginView();
          } else {
            return form;
          }
        },
      ),
    );
  }

  FWidget _buildClauseCheckRow() {
    return FContainer(
      padding: const EdgeInsets.symmetric(horizontal: 4.0),
      child: FObx(
        () {
          return ClauseCheckRow(
            initalValue: controller.state.isAgreeClause,
            onChanged: controller.onAgreeClauseChanged,
          );
        },
      ),
    );
  }

  FWidget _buildQRCodeLoginView() {
    return FColumn(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        FText(
          i18nBook.auth.scanQRCodeLogin.t,
          style: TextStyle(fontSize: FFontSizes.H3),
        ),
        const FSizedBox(height: FSpacings.MINI_BUTTON),
        FText(
          i18nBook.auth.useFlyinsonoMobileScan.t,
          style: TextStyle(fontSize: FFontSizes.H6),
        ),
        const FSizedBox(height: FSpacings.XXL),
        FContainer(
          margin: EdgeInsets.symmetric(vertical: 40),
          alignment: Alignment.center,
          child: FStack(
            children: [
              QuickFWidget(
                QRCodeWithLogo(
                  "${_authBoardController.state.qrCode}&",
                  logoSize: 30,
                  size: 160,
                ),
              ),
              FObx(() {
                if (_authBoardController.state.expiredQRCode) {
                  return FPositioned(
                    left: 0,
                    top: 0,
                    bottom: 0,
                    right: 0,
                    child: FMouseRegion(
                      cursor: SystemMouseCursors.click,
                      child: FGestureDetector(
                        businessParent: businessParent,
                        name: 'refershQRCode',
                        onTap: () {
                          _authBoardController.startWaitLogin();
                        },
                        child: FContainer(
                          decoration: BoxDecoration(
                            color: Colors.black.withOpacity(0.5),
                          ),
                          child: FCenter(
                            child: FColumn(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                FIcon(
                                  Icons.refresh,
                                  size: 30,
                                  color: Colors.white,
                                ),
                                const FSizedBox(height: FSpacings.M),
                                FText(
                                  i18nBook.common.refreshQRCode.t,
                                  style: TextStyle(color: Colors.white),
                                ),
                              ],
                            ),
                          ),
                        ),
                      ),
                    ),
                  );
                } else {
                  return FSizedBox();
                }
              }),
            ],
          ),
        ),
        const FSizedBox(height: FSpacings.MINI_BUTTON),
        if (!i18nBook.isCurrentChinese)
          const FSizedBox(height: FSpacings.MINI_BUTTON),
        _OtherOptionsRow(),
        const FSizedBox(height: FSpacings.XXL),
        FContainer(
          height: 28.sp,
          child: _LanguageOptionsRow(businessParent),
        ),
      ],
    );
  }
}

///语言选择行布局
class _LanguageOptionsRow extends FStatelessWidget {
  ///父级节点
  final FPage businessParent;
  final appState = Store.app;
  _LanguageOptionsRow(this.businessParent);
  Locale get locale =>
      appState.isFollowSystemLocale ? appState.systemLocale : appState.locale;

  @override
  FWidget build(BuildContext context) {
    return _buildBody();
  }

  /// 设置 语言 或者报告标签是否弹出
  Future<void> setCommonSettingsAsync(
    CommonSettingsEnum currCommonSetting,
    String signatureValue,
  ) async {
    try {
      final result = await rpc.user.setCommonSettingsAsync(
        CommonSettingsRequest(
          token: Store.user.token,
          value: signatureValue,
          settingType: currCommonSetting,
        ),
      );
      if (result) {
        var manager = Get.find<IUserInfoManager>();
        await manager.getUserInfoAsync();
      }
    } catch (e) {
      printError(info: e.toString());
      logger.e("setCommonSettingsAsync ex:", e);
    }
  }

  FWidget _buildBody() {
    final style = TextStyle(
      color: Colors.grey,
      fontSize: 14.sp,
      fontFamily: FTheme.ins.localeSetting.fontFamily,
    );
    final zhStyle = style.copyWith(
      fontFamily: FTheme.ins.data.localeSettings.chinese.fontFamily,
    );
    final activeStyle = TextStyle(
      color: FTheme.ins.colorScheme.primary,
    );

    return FObx(
      () => FRichText(
        text: TextSpan(
          style: style,
          children: [
            TextSpan(
              text: "中文",
              style: appState.locale == CHINESE_LOCALE ? activeStyle : zhStyle,
              recognizer: appState.locale != CHINESE_LOCALE
                  ? (TapGestureRecognizer()
                    ..onTap = () {
                      _swithLanguageConfirm(CHINESE_LOCALE);
                    })
                  : null,
            ),
            TextSpan(text: "  |  "),
            TextSpan(
              text: "English",
              style: appState.locale == ENGLISH_LOCALE ? activeStyle : null,
              recognizer: appState.locale != ENGLISH_LOCALE
                  ? (TapGestureRecognizer()
                    ..onTap = () {
                      _swithLanguageConfirm(ENGLISH_LOCALE);
                    })
                  : null,
            ),
            TextSpan(text: "  |  "),
            TextSpan(
              text: "русский язык",
              style: appState.locale == RUSSIAN_LOCALE ? activeStyle : null,
              recognizer: appState.locale != RUSSIAN_LOCALE
                  ? (TapGestureRecognizer()
                    ..onTap = () {
                      _swithLanguageConfirm(RUSSIAN_LOCALE);
                    })
                  : null,
            ),
            TextSpan(text: "  |  "),
            TextSpan(
              text: "Español",
              style: appState.locale == SPANISH_LOCALE ? activeStyle : null,
              recognizer: appState.locale != SPANISH_LOCALE
                  ? (TapGestureRecognizer()
                    ..onTap = () {
                      _swithLanguageConfirm(SPANISH_LOCALE);
                    })
                  : null,
            ),
            TextSpan(text: "  |  "),
            TextSpan(
              text: "Română",
              style: appState.locale == ROMANIA_LOCALE ? activeStyle : null,
              recognizer: appState.locale != ROMANIA_LOCALE
                  ? (TapGestureRecognizer()
                    ..onTap = () {
                      _swithLanguageConfirm(ROMANIA_LOCALE);
                    })
                  : null,
            ),
          ],
        ),
      ),
    );
  }

  ///切换语言
  void _swithLanguageConfirm(Locale locale) {
    Get.find<ILanguageConfigManager>().swithLanguageByCode(locale.languageCode);
  }
}

///登录界面主要条目UI
class _MainItems extends FisView<SignInController> implements FWidget {
  ///父级节点
  final FPage businessParent;
  _MainItems(this.businessParent);

  @override
  FWidget build(BuildContext context) {
    final state = controller.state;
    return FObx(() {
      final FWidget verificationCodeField;
      if (state.isCodeSignIn) {
        verificationCodeField = VerificationCodeField(
          tag: SignInController.C_VERIFICATION_CONTROLLER_TAG,
          textController: controller.verificationCodeController,
          textFocusNode: controller.verificationCodeFocusNode,
          onTextChanged: (val) => controller.state.verificationCode = val,
          fetchCodeFunc: controller.onFetchCode,
        );
      } else {
        verificationCodeField = _PasswordTextField();
      }
      return FColumn(
        // mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          _AccountTextField(),
          FSizedBox(height: 14.sp),
          verificationCodeField,
          FSizedBox(height: 14.sp),
          _SignInSubmitButton(this.businessParent),
          state.isCodeSignIn ? FContainer() : FSizedBox(height: 14.sp),
          state.isCodeSignIn
              ? FContainer()
              : FContainer(
                  width: double.infinity,
                  child: FormSecondaryButton(
                    businessParent: businessParent,
                    onPressed: controller.onSignUpClick,
                    text: i18nBook.auth.signUp4Btn.t,
                    description: "_MainItems onSignUpClick",
                  ),
                ),
          if (!i18nBook.isCurrentChinese) FSizedBox(height: 5.sp),
          FContainer(
            height: 50.sp,
            child: state.isCodeSignIn
                ? _CodeSignInOtherOptionsRow() as FWidget
                : _OtherOptionsRow(),
          ),
        ],
      );
    });
  }
}

///TabBar
class _MethodTabBar extends FisView<SignInController> implements FWidget {
  final _colorScheme = FTheme.ins.colorScheme;

  ///父级节点
  final FPage businessParent;

  _MethodTabBar({required this.businessParent});

  @override
  FWidget build(BuildContext context) {
    final tabs = controller.tabTitles.map((e) => Tab(text: e)).toList();
    return FTabBar(
      indicatorWeight: 4.sp,
      indicatorColor: _colorScheme.primary,
      labelColor: _colorScheme.primary,
      labelStyle: TextStyle(
        fontSize: 16.sp,
        fontFamily: FTheme.ins.localeSetting.fontFamily,
      ),
      indicatorSize: TabBarIndicatorSize.label,
      unselectedLabelColor: _colorScheme.text,
      onTap: controller.onTabChanged,
      tabs: tabs,
      controller: controller.tabController,
    );
  }
}

///带下划线的TabBar
class _MethodTabBarUnderLine extends FStatelessWidget {
  @override
  FWidget build(BuildContext context) {
    return FContainer(
      child: const FDivider(
        color: Colors.black26,
        height: 2,
      ),
      transform: Matrix4.translationValues(0.0, -0.4.sp, 0.0),
    );
  }
}

///登录界面手机端布局
class _MobileLayout extends FisView<SignInController> implements FWidget {
  ///父级节点
  final FPage businessParent;
  _MobileLayout(this.businessParent);

  @override
  FWidget build(BuildContext context) {
    final form = FForm(
      child: FListView(
        padding: EdgeInsets.zero,
        shrinkWrap: true,
        children: [
          FSizedBox(height: 26.sp),
          _MethodTabBar(businessParent: businessParent),
          _MethodTabBarUnderLine(),
          FSizedBox(height: 14.sp),
          _MainItems(businessParent),
          FContainer(
            padding: EdgeInsets.symmetric(
                horizontal: i18nBook.isCurrentRussian ? 0.0 : 4.0),
            child: FObx(
              () {
                return ClauseCheckRow(
                  initalValue: controller.state.isAgreeClause,
                  onChanged: controller.onAgreeClauseChanged,
                );
              },
            ),
          ),
          i18nBook.isCurrentRussian
              ? FSizedBox(height: 10.sp)
              : FSizedBox(height: 23.sp),
          FCenter(
            child: FContainer(
              height: 38.sp,
              child: _LanguageOptionsRow(businessParent),
            ),
          ),
          FSizedBox(height: 2.sp),
        ],
      ),
    );
    return FContainer(
      color: Colors.white,
      child: form,
    );
  }
}

///通用账号文本框
class _NormalAccountTextField extends FStatefulWidget {
  @override
  FState<_NormalAccountTextField> createState() =>
      _NormalAccountTextFieldState();
}

class _NormalAccountTextFieldState extends FState<_NormalAccountTextField> {
  final controller = Get.find<SignInController>();

  @override
  FWidget build(BuildContext context) {
    return FBorderTextFormField(
      maxLength: 254,
      onChanged: (val) {
        controller.state.account = val;
        if (controller.state.isAutoLogin) {
          controller.passwordController.clear();
          controller.state.password = '';
        }
      },
      controller: controller.accountController,
      hintText: i18nBook.auth.hint4AccountTriple.t,
    );
  }

  @override
  void initState() {
    super.initState();
    controller.accountController.text = controller.state.account;
  }
}

///其他选项行布局页
class _OtherOptionsRow extends FisView<SignInController> implements FPage {
  @override
  String get pageName => '_OtherOptionsRow';

  final _authBoardController = Get.find<AuthBoardController>();

  @override
  FWidget build(BuildContext context) {
    final txtStyle = TextStyle(
      fontFamily: FTheme.ins.localeSetting.fontFamily,
      fontSize: 14.sp,
      height: 1,
      color: Colors.grey,
    );
    final state = controller.state;
    bool showSetting = true;
    if (FPlatform.isPureWeb) {
      if (html.window.location.protocol == "https") {
        showSetting = false;
      }
    }
    List<FWidget> children = [];
    if (!_authBoardController.state.isSwitchAuthBody &&
        (!i18nBook.isCurrentChinese)) {
      children.add(
        _forgotPwdAndSetting(txtStyle, showSetting),
      );
    }
    children.add(
      FFlexible(
        child: FObx(
          () => LabeledCheckbox(
            label: FText(
              i18nBook.auth.autoLogin.t,
              style: txtStyle,
            ),
            padding: EdgeInsets.symmetric(
                horizontal:
                    kIsMobile ? (i18nBook.isCurrentRussian ? 0.0 : 4.0) : 4.0),
            value: state.isAutoLogin,
            onChanged: controller.onRememberPasswordChanged,
            mainAxisAlignment: _authBoardController.state.isSwitchAuthBody
                ? MainAxisAlignment.center
                : MainAxisAlignment.start,
          ),
        ),
      ),
    );
    if (!_authBoardController.state.isSwitchAuthBody &&
        (i18nBook.isCurrentChinese)) {
      children.add(
        _forgotPwdAndSetting(txtStyle, showSetting),
      );
    }
    return FFlex(
      direction: (i18nBook.isCurrentChinese ||
              _authBoardController.state.isSwitchAuthBody)
          ? Axis.horizontal
          : Axis.vertical,
      children: children,
    );
  }

  FWidget _forgotPwdAndSetting(
    TextStyle? txtStyle,
    bool showSetting,
  ) {
    if (!i18nBook.isCurrentChinese) {
      return FExpanded(
        child: FContainer(
          height: 50,
          child: FRow(
            children: [
              const FSizedBox(
                width: 8,
              ),
              FInkWell(
                // businessParent: this,
                // name: i18nBook.auth.forgotPwd.t,
                onTap: () {
                  controller.onRetrievePasswordClick();
                },
                // behavior: HitTestBehavior.opaque,
                child: FContainer(
                  padding: EdgeInsets.symmetric(vertical: 5),
                  child: FText(
                    i18nBook.auth.forgotPwd.t,
                    style: txtStyle,
                  ),
                ),
              ),
              const FExpanded(
                child: FSizedBox(),
              ),
              if (showSetting) ...[
                FInkWell(
                  // businessParent: this,
                  // name: i18nBook.user.setting.t,
                  onTap: () {
                    controller.onNetworkSettingClick();
                  },
                  // behavior: HitTestBehavior.opaque,
                  child: FContainer(
                    padding: EdgeInsets.symmetric(vertical: 5),
                    child: FText(
                      i18nBook.user.setting.t,
                      style: txtStyle,
                    ),
                  ),
                ),
              ],
            ],
          ),
        ),
      );
    }

    return FExpanded(
      child: FContainer(
        alignment: Alignment.centerRight,
        child: FRow(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            FInkWell(
              onTap: controller.onRetrievePasswordClick,
              child: FContainer(
                padding:
                    EdgeInsets.only(left: 10, right: 5, top: 10, bottom: 10),
                child: FText(
                  i18nBook.auth.forgotPwd.t,
                  style: txtStyle,
                ),
              ),
            ),
            if (showSetting) ...[
              FText(
                "|",
                style: txtStyle,
              ),
              FInkWell(
                onTap: controller.onNetworkSettingClick,
                child: FContainer(
                  padding:
                      EdgeInsets.only(left: 5, right: 10, top: 10, bottom: 10),
                  child: FText(
                    i18nBook.user.setting.t,
                    style: txtStyle,
                  ),
                ),
              ),
            ],
          ],
        ),
      ),
    );
  }
}

///密码文本框
class _PasswordTextField extends FisView<SignInController> {
  @override
  FWidget build(BuildContext context) {
    return FBorderTextFormField(
      maxLength: 20,
      obscureText: true,
      onChanged: (val) => controller.state.password = val,
      hintText: i18nBook.auth.hint4Pwd.t,
      controller: controller.passwordController,
      isShowVisibilityIcon: true,
    );
  }
}

///登录提交按钮
class _SignInSubmitButton extends FisView<SignInController> {
  ///父级节点
  final FPage businessParent;
  _SignInSubmitButton(this.businessParent);
  @override
  FWidget build(BuildContext context) {
    return FContainer(
      width: double.infinity,
      child: FObx(() {
        return SubmitButton(
          businessParent: businessParent,
          text: i18nBook.auth.login4Btn.t,
          description: "_MainItems login4Btn",
          onPressed: controller.onSignInSubmit,
          loading: controller.state.onSubmit,
          loadingText: i18nBook.auth.logining.t,
          disabled: !controller.state.isCanSubmit,
        );
      }),
    );
  }
}
