import 'package:cpt_profile/modules/profile_edit/profile_edit_state.dart';
import 'package:cpt_profile/modules/profile_edit/profile_edit_view_model.dart';
import 'package:cpt_profile/router/page/profile_page_router.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/material.dart';
import 'package:auto_route/auto_route.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.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/widget_export.dart';

@RoutePage()
class ProfileEditPage extends HookConsumerWidget {
  const ProfileEditPage({Key? key}) : super(key: key);

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

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

    useEffect(() {
      // 执行接口请求
      Future.microtask(() => viewModel.fetchDefaultAvatar());
      return () {
      };
    }, []);

    return Scaffold(
      appBar: MyAppBar.appBar(context, S.current.edit_profile,backgroundColor: context.appColors.backgroundWhite),
      backgroundColor: context.appColors.backgroundDefault,
      body: SingleChildScrollView(
        scrollDirection: Axis.vertical,
        physics: const BouncingScrollPhysics(),
        child: Container(
          margin: const EdgeInsets.symmetric(horizontal: 15),
          width: double.infinity,
          child: Column(
            mainAxisSize: MainAxisSize.max,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Center(
                child: Container(
                  width: 80,
                  height: 80,
                  decoration: BoxDecoration(color: context.appColors.avatarBg, shape: BoxShape.circle),
                  child: Stack(
                    children: [
                      //默认的占位图
                      Visibility(
                        visible: state.avatarPath == null,
                        child: const Align(
                          alignment: Alignment.bottomCenter,
                          child: MyAssetImage(
                            Assets.profileEditProfileAvatarDefault,
                            width: 49,
                            height: 64,
                          ),
                        ),
                      ),

                      //用户的头像
                      Visibility(
                        visible: state.avatarPath != null,
                        child: MyLoadImage(
                          state.avatarPath,
                          width: 80,
                          height: 80,
                          isCircle: true,
                        ),
                      ),

                      //底部的背景色
                      const Align(
                        alignment: Alignment.bottomCenter,
                        child: MyAssetImage(
                          Assets.profileEditProfileAvatarBottom,
                          width: 71,
                          height: 21.5,
                        ),
                      ),
                      //照相机Icon
                      const Align(
                        alignment: Alignment.bottomCenter,
                        child: MyAssetImage(
                          Assets.profileEditProfileAdd,
                          width: 12,
                          height: 11.5,
                        ),
                      ).marginOnly(bottom: 4),
                    ],
                  ),
                ).onTap((){
                  viewModel.showAvatarEditDialog(context);
                }),
              ).marginOnly(top: 23),

              // 表单 - 名
              MyTextView(
                S.current.first_name,
                fontSize: 17,
                marginTop: 33,
                marginBottom: 16,
                isFontMedium: true,
                textColor: context.appColors.textBlack,
              ),
              //表单
              _buildInputLayout(
                context,
                state,
                "first_name",
                textInputType: TextInputType.text,
                textInputAction: TextInputAction.next,
                onSubmit: (formKey, value) {
                  state.formData[formKey]!['focusNode'].unfocus();
                  FocusScope.of(context).requestFocus(state.formData['last_name']!['focusNode']);
                },
              ),

              // 表单 - 姓
              MyTextView(
                S.current.last_name,
                fontSize: 17,
                marginTop: 15,
                marginBottom: 16,
                isFontMedium: true,
                textColor: context.appColors.textBlack,
              ),
              //表单
              _buildInputLayout(
                context,
                state,
                "last_name",
                textInputType: TextInputType.text,
                textInputAction: TextInputAction.next,
                onSubmit: (formKey, value) {
                  state.formData[formKey]!['focusNode'].unfocus();
                  FocusScope.of(context).requestFocus(state.formData['email']!['focusNode']);
                },
              ),

              // 表单 - 邮箱
              MyTextView(
                S.current.email,
                fontSize: 17,
                marginTop: 15,
                marginBottom: 16,
                isFontMedium: true,
                textColor: context.appColors.textBlack,
              ),
              //表单
              _buildInputLayout(
                context,
                state,
                "email",
                textInputType: TextInputType.emailAddress,
                textInputAction: TextInputAction.next,
                onSubmit: (formKey, value) {
                  state.formData[formKey]!['focusNode'].unfocus();
                },
              ),

              //提交
              MyButton(
                onPressed: viewModel.submitEdit,
                text: S.current.submit,
                textColor: Colors.white,
                backgroundColor: context.appColors.btnBgDefault,
                fontWeight: FontWeight.w500,
                type: ClickType.throttle,
                fontSize: 16,
                minHeight: 50,
                radius: 5,
              ).marginOnly(top: 50, bottom: 50),
            ],
          ),
        ),
      ),
    );
  }

  /// 输入框
  Widget _buildInputLayout(
    BuildContext context,
    ProfileEditState state,
    String key, {
    double marginTop = 0,
    bool? showRightIcon = false, //是否展示右侧的布局
    Widget? rightWidget, //右侧的布局
    TextInputType textInputType = TextInputType.text,
    String? errorText,
    bool obscureText = false,
    TextInputAction textInputAction = TextInputAction.done,
    Function? onSubmit,
  }) {
    return IgnoreKeyboardDismiss(
      child: MyTextField(
        key,
        fillBackgroundColor: 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,
      ),
    );
  }
}
