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:domain/repository/auth_repository.dart';
import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:plugin_basic/dialog/verify_code_view_model.dart';
import 'package:plugin_platform/engine/toast/toast_engine.dart';
import 'package:shared/utils/util.dart';
import 'package:widgets/ext/ex_widget.dart';
import 'package:widgets/my_load_image.dart';
import 'dart:ui';
import 'package:flutter/cupertino.dart';
import 'package:flutter/widgets.dart';
import 'package:widgets/my_text_field.dart';
import 'package:widgets/my_text_view.dart';
import 'package:widgets/widget_export.dart';

import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';

/*
 * 验证码校验弹窗，输入四位数的验证才能发送短信
 */
class VerifyCodeDialog extends HookConsumerWidget {
  void Function(String? key, String? code) confirmAction;

  VerifyCodeDialog({
    required this.confirmAction,
  });

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    // 使用 useState 来持久化 TextEditingController 和 FocusNode
    final viewModel = ref.watch(verifyCodeProvider.notifier);
    final state = ref.watch(verifyCodeProvider);

    useEffect(() {
      //赋值State的值
      Future.microtask(() {
        viewModel.fetchCode();
      });
      return () {};
    }, []);

    return Column(
      crossAxisAlignment: CrossAxisAlignment.center,
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        //Title （如果使用 Container 为最外层容器则默认为 match_parent 的效果，除非我们限制宽度和最大高度最小高度）
        Container(
          width: double.infinity,
          height: 55,
          decoration: BoxDecoration(
            color: context.appColors.btnBgDefault,
            borderRadius: const BorderRadius.only(
              topRight: Radius.circular(15),
              topLeft: Radius.circular(15),
            ),
          ),
          child: Row(
            children: [
              const SizedBox(width: 45),
              MyTextView(
                S.current.captcha,
                fontSize: 18,
                textAlign: TextAlign.center,
                isFontMedium: true,
                textColor: Colors.white,
              ).expanded(),
              const MyAssetImage(
                Assets.baseServiceDialogDeleteIcon,
                width: 25,
                height: 25.5,
              ).onTap(() {
                onCancel();
              }, padding: 10)
            ],
          ),
        ),

        Container(
          width: double.infinity,
          padding: const EdgeInsets.only(top: 40),
          decoration: BoxDecoration(
            color: context.appColors.whiteSecondBG,
            borderRadius: const BorderRadius.only(
              bottomLeft: Radius.circular(15),
              bottomRight: Radius.circular(15),
            ),
          ),
          child: Column(
            children: [
              //图片与输入框
              Row(
                mainAxisSize: MainAxisSize.max,
                children: [
                  IgnoreKeyboardDismiss(
                    child: MyTextField(
                      'code',
                      "",
                      enabled: true,
                      fillCornerRadius: 1,
                      padding: const EdgeInsets.symmetric(horizontal: 10),
                      fillBackgroundColor: context.appColors.authFiledBG,
                      border: InputBorder.none,
                      showDivider: false,
                      hintText: S.current.enter_captcha,
                      hintStyle: TextStyle(
                        color: context.appColors.authFiledHint,
                        fontSize: 16,
                        fontWeight: FontWeight.w500,
                      ),
                      controller: state.textEditingController,
                      focusNode: state.focusNode,
                      style: TextStyle(
                        color: context.appColors.authFiledText,
                        fontSize: 16,
                        fontWeight: FontWeight.w500,
                      ),
                      height: 48,
                      cursorWidth: 1.5,
                      cursorColor: context.appColors.authFiledText,
                      margin: const EdgeInsets.only(right: 5),
                      onSubmit: (formKey, value) {
                        String? code = state.textEditingController.text.toString();
                        if (Utils.isNotEmpty(code)) {
                          state.focusNode.unfocus();
                          confirmAction.call(state.key, code);
                          onCancel();
                        } else {
                          ToastEngine.show("Enter Code");
                        }
                      },
                    ),
                  ).expanded(),

                  //图片验证码
                  MyLoadImage(
                    state.imgFilePath,
                    width: 100,
                    height: 45,
                    fit: BoxFit.fill,
                    onClick: () {
                      //刷新验证码
                      viewModel.fetchCode();
                    },
                  ),
                ],
              ).marginOnly(left: 15, right: 15),

              //按钮获取验证码
              Row(
                children: [
                  InkWell(
                    onTap: () async {
                      String? code = state.textEditingController.text.toString();
                      if (Utils.isNotEmpty(code)) {
                        state.focusNode.unfocus();
                        confirmAction.call(state.key, code);
                        onCancel();
                      } else {
                        ToastEngine.show("Enter Code");
                      }
                    },
                    child: MyTextView(
                      S.current.get_verification_code,
                      fontSize: 16,
                      paddingTop: 13,
                      paddingBottom: 13,
                      isFontMedium: true,
                      textAlign: TextAlign.center,
                      textColor: Colors.white,
                      backgroundColor: context.appColors.btnBgDefault,
                      cornerRadius: 7,
                    ),
                  ).expanded(),
                ],
              ).marginOnly(bottom: 30, top: 28, left: 15, right: 15),
            ],
          ),
        ),
      ],
    )
        .constrained(width: 300)
        //跟随软键盘滚动，适配居中于剩余的空间
        .padding(bottom: MediaQuery.of(context).viewInsets.bottom);
  }

  //取消弹框
  void onCancel() async {
    SmartDialog.dismiss();
  }
}
