import 'package:cpt_auth/modules/auth_login/auth_login_state.dart';
import 'package:cs_resources/generated/assets.dart';
import 'package:cs_resources/generated/l10n.dart';
import 'package:cs_resources/theme/app_colors_theme.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:auto_route/auto_route.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:plugin_basic/dialog/country_code_selecter.dart';
import 'package:router/ext/auto_router_extensions.dart';
import 'package:widgets/ext/ex_widget.dart';
import 'package:widgets/my_appbar.dart';
import 'package:widgets/my_button.dart';
import 'package:widgets/my_load_image.dart';
import 'package:widgets/my_text_field.dart';
import 'package:widgets/my_text_view.dart';
import 'package:widgets/shatter/custom_check_box.dart';
import 'package:widgets/widget_export.dart';

import '../../router/page/auth_page_router.dart';
import 'auth_login_view_model.dart';

/*
 * 用户的登录页面
 */
@RoutePage()
class AuthLoginPage extends HookConsumerWidget {
  const AuthLoginPage({Key? key}) : super(key: key);

  //启动当前页面
  static void startInstance({BuildContext? context}) {
    if (context != null) {
      context.router.navigate(const AuthLoginPageRoute());
    } else {
      appRouter.navigate(const AuthLoginPageRoute());
    }
  }

  //替换之前的页面
  static void startAndPopAll({BuildContext? context}) {
    if (context != null) {
      context.router.popUntilRoot();
      context.router.replace(const AuthLoginPageRoute());
    } else {
      appRouter.popUntilRoot();
      appRouter.replace(const AuthLoginPageRoute());
    }
  }

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final viewModel = ref.read(authLoginViewModelProvider.notifier);
    final state = ref.watch(authLoginViewModelProvider);

    return Scaffold(
      appBar: MyAppBar.appBar(context, "", showBackButton: false),
      backgroundColor: context.appColors.backgroundDefault,
      body: SingleChildScrollView(
        scrollDirection: Axis.vertical,
        physics: const BouncingScrollPhysics(),
        child: Container(
          margin: const EdgeInsets.symmetric(horizontal: 38),
          width: double.infinity,
          child: Column(
            mainAxisSize: MainAxisSize.max,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              //顶部Logo
              const MyAssetImage(
                Assets.assetsYyHomeSplash,
                width: 109.5,
                height: 48,
              ).marginOnly(top: 45, bottom: 45),

              // 登录表单 - 账号
              Row(
                mainAxisSize: MainAxisSize.max,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  //封装的国家选择控件
                  CountryCodeSelector(
                    onChanged: (countryCode) {
                      viewModel.saveCountryCode(countryCode);
                    },
                  ).marginOnly(left: 15),

                  //电话输入框
                  _buildInputLayout(
                    context,
                    state,
                    "account",
                    fillBGColor: Colors.transparent,
                    textInputType: TextInputType.number,
                    textInputAction: TextInputAction.done,
                    errorText: state.accountErrorText,
                    onSubmit: (formKey, value) {
                      state.formData[formKey]!['focusNode'].unfocus();
                      FocusScope.of(context).requestFocus(state.formData['password']!['focusNode']);
                    },
                  ).expanded(),
                ],
              ).decorated(
                color: context.appColors.authFiledBG,
                borderRadius: BorderRadius.circular(5.0),
              ),

              // 登录表单 - 密码
              _buildInputLayout(
                context,
                state,
                "password",
                marginTop: 15,
                obscureText: !state.pwdVisibility,
                errorText: state.passwordErrorText,
                showRightIcon: true,
                rightWidget: IconButton(
                  highlightColor: Colors.transparent,
                  splashColor: Colors.transparent,
                  icon: !state.pwdVisibility
                      ? const MyAssetImage(
                          Assets.authPasswordHide,
                          width: 22.5,
                          height: 16.5,
                        )
                      : const MyAssetImage(
                          Assets.authPasswordShow,
                          width: 22.5,
                          height: 16.5,
                        ),
                  onPressed: () {
                    viewModel.switchPwdVisibility();
                  },
                ),
                onSubmit: (formKey, value) {
                  state.formData[formKey]!['focusNode'].unfocus();
                  viewModel.doLogin();
                },
              ),

              //登录按钮
              MyButton(
                onPressed: viewModel.doLogin,
                text: S.current.login,
                enable: state.isLoginBtnEnable,
                textColor: Colors.white,
                disabledTextColor: Colors.white,
                backgroundColor: context.appColors.btnBgDefault,
                disabledBackgroundColor: context.appColors.btnBgDefault.withOpacity(0.2),
                fontWeight: FontWeight.w500,
                type: ClickType.throttle,
                minHeight: 50,
                radius: 5,
              ).marginOnly(top: 20, bottom: 23),

              //忘记密码
              MyTextView(
                S.current.forgot_password,
                isFontMedium: true,
                fontSize: 16,
                textColor: context.appColors.textPrimary,
                onClick: viewModel.gotoForgotPage,
              ),

              //创建账户-注册
              MyButton(
                onPressed: viewModel.gotoSignUpPage,
                text: S.current.create_new_yy_home_account,
                textColor: Colors.white,
                backgroundColor: context.appColors.btnBgDefault,
                fontWeight: FontWeight.w500,
                type: ClickType.throttle,
                minHeight: 50,
                radius: 5,
              ).marginOnly(top: 28),

              //同意协议
              Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  MyAssetImage(
                    state.isAgreeTerms ? Assets.baseServiceCheckBoxChecked : Assets.baseServiceCheckBoxUncheck,
                    color: state.isAgreeTerms ? context.appColors.textPrimary : Colors.transparent,
                    width: 15.5,
                    height: 15.5,
                  ).onTap(viewModel.switchAgreeTerms, padding: 10),
                  RichText(
                    text: TextSpan(
                      children: [
                        TextSpan(
                          text: S.current.agree_to,
                          style: TextStyle(color: context.appColors.textDarkGray, fontWeight: FontWeight.w500, fontSize: 15), // 灰色文本
                        ),
                        const TextSpan(
                          text: " ",
                        ),
                        TextSpan(
                          text: S.current.terms_of_service,
                          style: TextStyle(color: context.appColors.textPrimary, fontWeight: FontWeight.w500, fontSize: 15), // 蓝色文本
                          recognizer: TapGestureRecognizer()..onTap = (){
                            viewModel.gotoTermsPage(context);
                          } ,
                        ),
                      ],
                    ),
                  ),
                ],
              ).marginOnly(top: 30, bottom: 30),

              //结束
            ],
          ),
        ),
      ),
    );
  }

  /// 输入框 账号与密码
  Widget _buildInputLayout(
    BuildContext context,
    LoginState state,
    String key, {
    double marginTop = 0,
    bool? showRightIcon = false, //是否展示右侧的布局
    Widget? rightWidget, //右侧的布局
    TextInputType textInputType = TextInputType.text,
    String? errorText,
    Color? fillBGColor,
    bool obscureText = false,
    TextInputAction textInputAction = TextInputAction.done,
    Function? onSubmit,
  }) {
    return IgnoreKeyboardDismiss(
      child: MyTextField(
        key,
        fillBackgroundColor: fillBGColor ?? context.appColors.authFiledBG,
        state.formData[key]!['value'],
        hintText: state.formData[key]!['hintText'],
        hintStyle: TextStyle(
          color: context.appColors.authFiledHint,
          fontSize: 16.0,
          fontWeight: FontWeight.w500,
        ),
        controller: state.formData[key]!['controller'],
        focusNode: state.formData[key]!['focusNode'],
        margin: EdgeInsets.only(top: marginTop),
        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 3),
        showDivider: false,
        height: 44,
        style: TextStyle(
          color: context.appColors.authFiledText,
          fontSize: 16.0,
          fontWeight: FontWeight.w500,
        ),
        inputType: textInputType,
        textInputAction: textInputAction,
        onSubmit: onSubmit,
        cursorColor: context.appColors.authFiledText,
        obscureText: obscureText,
        errorText: errorText,
        showLeftIcon: true,
        showRightIcon: showRightIcon,
        rightWidget: rightWidget,
      ),
    );
  }
}
