import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:making_school_asignment_app/common/const_text.dart';
import 'package:making_school_asignment_app/common/job/user_register_params.dart';
import 'package:making_school_asignment_app/common/mixins/request_tool_mixin.dart';
import 'package:making_school_asignment_app/common/utils/toast_utils.dart';
import 'package:making_school_asignment_app/page/global_widget/my_text.dart';
import 'package:making_school_asignment_app/routes/app_pages.dart';

/// 注册页面
class Register extends StatefulWidget {
  const Register({super.key});

  @override
  State<Register> createState() => _RegisterState();
}

class _RegisterState extends State<Register> with RequestToolMixin {
  late final FocusNode _theFocus;
  late final FocusNode _pwdFocus; // 密码
  //文本输入框控制器
  late final TextEditingController _userNameController;
  late final TextEditingController _passwordController;

  bool readAgreement = false; // 阅读协议
  bool _isShowPwd = true;
  bool canLogin = true;

  @override
  void initState() {
    super.initState();
    _userNameController = TextEditingController();
    _passwordController = TextEditingController();
    _pwdFocus = FocusNode();
    _theFocus = FocusNode();
  }

  @override
  void dispose() {
    super.dispose();
    _userNameController.dispose();
    _passwordController.dispose();
    _pwdFocus.dispose();
    _theFocus.dispose();
  }

  void toRegister() async {
    if (!canLogin) return;
    setState(() => canLogin = false);
    void toMsg(msg) {
      Future.delayed(Duration.zero, () => ToastUtils.showError(msg));
      setState(() => canLogin = true);
    }

    FocusScope.of(context).requestFocus(_theFocus);
    try {
      String userName = _userNameController.text.trim();
      String userPwd = _passwordController.text.trim();
      if (userName == '') return toMsg('请填写用户账号');
      if (userPwd == '') return toMsg('请填写密码');
      if (userPwd.length < 6) return toMsg('密码长度不得少于6位');
      if (!readAgreement) return toMsg('请勾选我已阅读用户协议和隐私协议');
      EasyLoading.show(status: 'loading...');
      var resultData = await getClient().toRegister(UserRegisterParams(account: userName, password: userPwd));
      print(resultData);
      // if (resultData.success) return toMsg(resultData.message ?? '注册失败，请重试');
      ToastUtils.showSuccess('注册成功,请登录');
      // 跳转登录页
      Future.delayed(Duration.zero, () => Get.back());
    } catch (e) {
      setState(() => canLogin = true);
    } finally {
      EasyLoading.dismiss();
    }
  }

  void _showPassword() {
    setState(() {
      _isShowPwd = !_isShowPwd;
    });
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () {
        FocusScope.of(context).requestFocus(_theFocus);
      },
      child: AnnotatedRegion(
        value: const SystemUiOverlayStyle(
          statusBarColor: Colors.transparent,
          systemNavigationBarIconBrightness: Brightness.light,
          statusBarIconBrightness: Brightness.light,
          statusBarBrightness: Brightness.dark,
        ),
        child: Scaffold(
          backgroundColor: Colors.transparent,
          resizeToAvoidBottomInset: false,
          body: Stack(
            children: [
              Container(
                  width: double.infinity,
                  height: double.infinity,
                  alignment: Alignment.center,
                  decoration: const BoxDecoration(
                    image: DecorationImage(
                      image: AssetImage('assets/images/register_bg.png'),
                      fit: BoxFit.fill, // 完全填充
                    ),
                  ),
                  child: SingleChildScrollView(
                    child: Column(
                      children: [
                        Container(
                          width: 86.w,
                          height: 86.w,
                          alignment: Alignment.center,
                          child: SizedBox(
                            height: 86.w,
                            width: 86.w,
                            child: Image.asset('assets/images/login_logo_icon.png', fit: BoxFit.cover),
                          ),
                        ),
                        Container(
                          margin: EdgeInsets.symmetric(horizontal: 32.w, vertical: 24.h),
                          padding: EdgeInsets.only(top: 34.h, bottom: 16.h, left: 22.w, right: 22.w),
                          decoration: BoxDecoration(
                            color: Colors.white,
                            border: Border.all(width: 1.w, color: Colors.white),
                            borderRadius: BorderRadius.all(Radius.circular(10.w)),
                            boxShadow: const [
                              BoxShadow(
                                color: Color.fromRGBO(46, 91, 255, 0.1),
                                offset: Offset.zero, //阴影y轴偏移量
                                blurRadius: 100, //阴影模糊程度
                                spreadRadius: 100, //阴影扩散程度
                              )
                            ],
                          ),
                          child: Column(children: [
                            TextField(
                              controller: _userNameController,
                              maxLines: 1,
                              maxLength: 20,
                              textInputAction: TextInputAction.next,
                              enableInteractiveSelection: false,
                              onEditingComplete: () {
                                FocusScope.of(context).requestFocus(_pwdFocus);
                              },
                              style: TextStyle(
                                color: const Color.fromRGBO(80, 87, 103, 1),
                                fontSize: 15.sp,
                              ),
                              decoration: InputDecoration(
                                hintText: "请输入账号",
                                hintStyle: TextStyle(fontSize: 16.sp, color: const Color.fromRGBO(153, 153, 153, 1)),
                                labelText: "账号",
                                labelStyle: TextStyle(fontSize: 16.sp, color: const Color.fromRGBO(148, 163, 182, 1)),
                              ),
                            ),
                            TextField(
                              focusNode: _pwdFocus,
                              controller: _passwordController,
                              keyboardType: TextInputType.number,
                              maxLines: 1,
                              obscureText: _isShowPwd, //隐藏密码显示
                              textInputAction: TextInputAction.go,
                              enableInteractiveSelection: false,
                              onSubmitted: (_) => toRegister(),
                              style: TextStyle(
                                color: const Color.fromRGBO(80, 87, 103, 1),
                                fontSize: 15.sp,
                              ),
                              decoration: InputDecoration(
                                hintText: "请输入密码",
                                suffix: GestureDetector(
                                  onTap: _showPassword,
                                  child: Icon(
                                    Icons.remove_red_eye,
                                    color: !_isShowPwd ? Theme.of(context).primaryColor : Colors.grey,
                                  ),
                                ),
                                hintStyle: TextStyle(fontSize: 16.sp, color: const Color.fromRGBO(153, 153, 153, 1)),
                                labelText: "密码",
                                isDense: true,
                                labelStyle: TextStyle(fontSize: 16.sp, color: const Color.fromRGBO(148, 163, 182, 1)),
                              ),
                            ),
                            SizedBox(
                              height: 12.h,
                            ),
                            InkWell(
                              onTap: toRegister,
                              child: Container(
                                margin: EdgeInsets.symmetric(vertical: 10.h),
                                decoration: BoxDecoration(
                                  color: canLogin ? Theme.of(context).primaryColor : Colors.grey,
                                  boxShadow: [
                                    BoxShadow(
                                      color: const Color.fromRGBO(76, 199, 147, 0.5),
                                      offset: Offset(4.w, 6.h), //阴影y轴偏移量
                                      blurRadius: 10, //阴影模糊程度
                                      spreadRadius: 0.5, //阴影扩散程度
                                    )
                                  ],
                                  borderRadius: BorderRadius.all(
                                    Radius.circular(8.w),
                                  ),
                                ),
                                alignment: Alignment.center,
                                width: double.infinity,
                                height: 50.h,
                                child: Text(
                                  '注 册',
                                  style: TextStyle(fontSize: 16.sp, color: Colors.white),
                                ),
                              ),
                            ),
                            Row(
                              children: [
                                Container(
                                  width: 30.w,
                                  padding: EdgeInsets.only(right: 10.w),
                                  child: Checkbox(
                                    activeColor: Colors.deepOrangeAccent,
                                    checkColor: Colors.white,
                                    value: readAgreement,
                                    onChanged: (value) {
                                      FocusScope.of(context).requestFocus(_pwdFocus);
                                      FocusScope.of(context).requestFocus(_theFocus);
                                      setState(() {
                                        readAgreement = value ?? false;
                                      });
                                    },
                                  ),
                                ),
                                InkWell(
                                  onTap: () {
                                    // RouterManager.router.navigateTo(
                                    //   context,
                                    //   '${RouterManager.agreementPath}?type=${AGREEMENT_KEY.USER_AGREEMENT.name}',
                                    //   transition: getTransition(),
                                    // );
                                  },
                                  child: quickText('我已阅读', size: 11.sp),
                                ),
                                InkWell(
                                  onTap: () {
                                    Get.toNamed(Routes.agreementPage,
                                        arguments: {"type": AGREEMENT_KEY.USER_AGREEMENT.name});
                                  },
                                  child: quickText(
                                    '《用户协议》',
                                    size: 12.sp,
                                    color: Theme.of(context).primaryColor,
                                  ),
                                ),
                                InkWell(
                                  onTap: () {
                                    Get.toNamed(Routes.agreementPage,
                                        arguments: {"type": AGREEMENT_KEY.PRIVACY_GREEMENT.name});
                                  },
                                  child: quickText(
                                    '《隐私协议》',
                                    size: 12.sp,
                                    color: Theme.of(context).primaryColor,
                                  ),
                                ),
                              ],
                            ),
                          ]),
                        )
                      ],
                    ),
                  )),
              Positioned(
                top: MediaQuery.of(context).padding.top + 20.r,
                left: 20.r,
                child: InkWell(
                  onTap: () => Navigator.pop(context),
                  child: Icon(Icons.arrow_back_ios_new_rounded, color: Colors.white, size: 24.sp),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
