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:flutter_screenutil/flutter_screenutil.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/managers/server_config_manager.dart';
import 'package:flyinsono/pages/auth/widgets/form_validator.dart';
import 'package:flyinsono/pages/auth/widgets/text_field.dart';
import 'package:get/get.dart';
import 'package:flutter/foundation.dart';
import 'package:flyinsono/pages/auth/sign_up/controller.dart';
import 'package:fis_theme/theme.dart';
import 'package:flyinsono/pages/auth/widgets/code_field.dart';
import 'package:flyinsono/pages/auth/clause_view/checkrow.dart';
import '../auth_board/controller.dart';
import '../widgets/button.dart';
import '../widgets/page_resizable_box.dart';

///登出界面
class SignUpPage extends FisView<SignUpController> implements FPage {
  const SignUpPage({this.pageName = 'SignUpPage', Key? key}) : super(key: key);
  @override
  final String pageName;

  @override
  FWidget build(BuildContext context) {
    return FPageResizableBox(
      builder: () => _BuildLayout(this),
    );
  }
}

///登出界面布局
class _BuildLayout extends FisView<SignUpController> implements FWidget {
  _BuildLayout(this.businessParent);

  ///父级节点
  final FPage businessParent;
  final _parentContext = Get.find<AuthBoardController>().currentContext;
  final _colorScheme = FTheme.ins.colorScheme;

  void _onBuildAccountFieldClick(String val) {
    controller.state.account = val;
    controller.formValidateState.accountBeOccupied = false;
    controller.showAccountValidator();
    controller.accountValidatorController.removeCustomError();
  }

  @override
  FWidget build(BuildContext context) {
    final spaceBetween = FSizedBox(height: 14.sp);
    final state = controller.state;
    final children = [
      if (!kIsMobile) ...[
        FText(
          i18nBook.auth.signUp.t,
          style: TextStyle(fontSize: 20.sp, color: _colorScheme.primary),
        ),
        FSizedBox(height: 32.sp),
      ],
      _buildAccountField(),
      spaceBetween,
      _buildVerificationCodeField(),
      spaceBetween,
      _buildPwdField(),
      spaceBetween,
      _buildReenterPwdField(),
      FSizedBox(height: 20.sp),
      _buildSubmitButton(),
      if (!kIsMobile) spaceBetween,
      FContainer(
        width: double.infinity,
        child: FormSecondaryButton(
          businessParent: businessParent,
          onPressed: controller.onRouteBack,
          text: i18nBook.auth.back4Login.t,
          description: "_BuildLayout back4Login",
        ),
      ),
      if (kIsMobile) FSizedBox(height: 42.sp),
      if (kIsWeb) FSizedBox(height: 15.sp),
      FCenter(
        child: FObx(
          () => ClauseCheckRow(
            initalValue: state.isAgreeClause,
            onChanged: controller.onAgreeClauseChanged,
          ),
        ),
      ),
    ];

    final form = FForm(
      child: kIsMobile
          ? FListView(
              children: children,
            )
          : FColumn(
              children: children,
            ),
    );

    return FContainer(
      color: kIsMobile ? Colors.white : Color.fromARGB(255, 247, 251, 255),
      child: form,
    );
  }

  FWidget _buildAccountField() {
    final validateState = controller.formValidateState;
    final txtField = FObx(
      () => FBorderTextFormField(
        controller: controller.accountTextController,
        focusNode: controller.accountFocusNode,
        maxLength: 254,
        inError: !validateState.accountChecked &&
            controller.formEditState.accountEdited,
        onChanged: (val) => _onBuildAccountFieldClick(
          val,
        ),
        inputFormatters: [
          FilteringTextInputFormatter.deny(RegExp("[\u4e00-\u9fa5]")),
          FilteringTextInputFormatter.deny(RegExp("\\s")),
        ],
        hintText: ServerConfigManager.isSMSOn
            ? i18nBook.auth.hint4AccountDouble.t
            : i18nBook.auth.enterEmail.t,
      ),
    );

    return FFormItemValidator(
      key: ValueKey("Signup.FormItem.Account"),
      child: txtField,
      overlayContext: _parentContext,
      controller: controller.accountValidatorController,
      validateSteps: [
        FFormItemValidateStep(
          validateFn: () => validateState.accountFormatCheck,
          tips: ServerConfigManager.isSMSOn
              ? i18nBook.auth.toast4AccountDouble.t
              : i18nBook.auth.enterValidEmail.t,
        ),
      ],
    );
  }

  FWidget _buildPwdField() {
    final validateState = controller.formValidateState;
    final txtField = FObx(
      () => FBorderTextFormField(
        controller: controller.passwordTextController,
        focusNode: controller.passwordFocusNode,
        inError:
            !validateState.pwdChecked && controller.formEditState.pwdEdited,
        maxLength: 20,
        obscureText: true,
        onChanged: (val) {
          controller.state.password = val;
          controller.showPwdValidator();
        },
        hintText: i18nBook.auth.hint4Pwd.t,
        isShowVisibilityIcon: true,
      ),
    );

    return FFormItemValidator(
      key: ValueKey("Signup.FormItem.Pwd"),
      child: txtField,
      overlayContext: _parentContext,
      controller: controller.passwordValidatorController,
      validateSteps: [
        FFormItemValidateStep(
          tips: i18nBook.auth.toast4PwdBlankError.t,
          validateFn: () => validateState.pwdNotContainBlank,
        ),
        FFormItemValidateStep(
          tips: i18nBook.auth.toast4PwdLengthError.t,
          validateFn: () => validateState.pwdLengthChecked,
        ),
        FFormItemValidateStep(
          tips: i18nBook.auth.toast4PwdCharCombinError.t,
          validateFn: () => validateState.pwdCharCombinChecked,
        ),
      ],
    );
  }

  FWidget _buildReenterPwdField() {
    final validateState = controller.formValidateState;
    final txtField = FObx(
      () => FBorderTextFormField(
        controller: controller.reenterPasswordTextController,
        focusNode: controller.reenterPasswordFocusNode,
        maxLength: 20,
        inError: !validateState.reenterPwdChecked &&
            controller.formEditState.reenterPwdEdited,
        obscureText: true,
        onChanged: (val) {
          controller.state.reenterPassword = val;
          controller.showReenterPwdValidator();
        },
        hintText: i18nBook.auth.hint4ConfirmPwd.t,
        isShowVisibilityIcon: true,
      ),
    );

    return FFormItemValidator(
      key: ValueKey("Signup.FormItem.ReenterPwd"),
      child: txtField,
      overlayContext: _parentContext,
      controller: controller.reenterPasswordValidatorController,
      validateSteps: [
        FFormItemValidateStep(
          tips: i18nBook.auth.toast4ConfirmPwdMatchError.t,
          validateFn: () => validateState.reenterPwdEqualsPwd,
        ),
      ],
    );
  }

  FWidget _buildSubmitButton() {
    return FContainer(
      width: double.infinity,
      child: FObx(
        () => SubmitButton(
          businessParent: businessParent,
          text: i18nBook.auth.signUp4Btn.t,
          onPressed: controller.onSubmit,
          loading: controller.state.onSubmit,
          loadingText: i18nBook.common.submitting.t,
          description: "_BuildLayout SubmitButton",
          disabled: !controller.formValidateState.isCanSubmit,
        ),
      ),
    );
  }

  FWidget _buildVerificationCodeField() {
    return FObx(
      () => VerificationCodeField(
        key: ValueKey("Signup.FormItem.VerificationCode"),
        tag: SignUpController.C_VERIFICATION_CONTROLLER_TAG,
        textFocusNode: controller.verificationCodeFocusNode,
        textController: controller.verificationCodeTextController,
        onTextChanged: (val) => controller.state.verificationCode = val,
        inError: !controller.formValidateState.verificationCodeChecked &&
            controller.formEditState.verificationCodeEdited,
        fetchCodeFunc: controller.onFetchCodeClick,
      ),
    );
  }
}
