import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:location/base/base_page.dart';
import 'package:location/data/consts/web_url.dart';
import 'package:location/resource/assets.gen.dart';
import 'package:location/resource/colors.gen.dart';
import 'package:location/resource/string.gen.dart';
import 'package:location/router/app_pages.dart';
import 'package:location/utils/common_expand.dart';
import '../browser/browser_view.dart';
import 'login_controller.dart';

class LoginPage extends BasePage<LoginController> {
  const LoginPage({super.key});

  static Future<bool> start() async {
    return await Get.toNamed(RoutePath.login) == true;
  }

  @override
  bool immersive() {
    return true;
  }

  @override
  Widget buildBody(BuildContext context) {
    return Obx(() {
      if (controller.loginStatus == LoginStatus.loading ||
          controller.loginStatus == LoginStatus.oneLogin) {
        return _buildLoadingView();
      } else {
        return _buildPhoneNumberLoginView(context);
      }
    });
  }

  Widget _buildLoadingView() {
    return Center(
      child: CircularProgressIndicator(
        strokeWidth: 3.5.w,
        valueColor: const AlwaysStoppedAnimation(ColorName.black30),
      ),
    );
  }

  Widget _buildPhoneNumberLoginView(BuildContext context) {
    return GestureDetector(
      onTap: () {
        // 点击空白处关闭键盘
        FocusScope.of(context).unfocus();
      },
      child: Stack(
        children: [
          AspectRatio(
              aspectRatio: 360 / 285,
              child: Assets.images.bgLoginHeadContainer
                  .image(width: double.infinity)),
          buildLoginHeader(),
          SafeArea(
            child: Column(
              children: [
                SizedBox(height: 150.5.w),
                Expanded(
                  child: Container(
                    width: double.infinity,
                    height: double.infinity,
                    decoration: BoxDecoration(
                      color: ColorName.white,
                      borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(18.w),
                        topRight: Radius.circular(18.w),
                      ),
                    ),
                    child: Column(
                      children: [
                        SizedBox(height: 27.w),
                        buildPhoneTextFiled(),
                        SizedBox(height: 12.w),
                        buildCodeTextFiled(),
                        SizedBox(height: 10.w),
                        buildPrivacyTxt(),
                        SizedBox(height: 148.h),
                        buildLoginBtn(),
                        SizedBox(height: 10.w),
                        buildOneLoginTxt()
                      ],
                    ),
                  ),
                )
              ],
            ),
          )
        ],
      ),
    );
  }

  Widget buildOneLoginTxt() {
    return Obx(() {
      return Visibility(
        visible: controller.isSupportOneLogin,
        child: GestureDetector(
          onTap: controller.onOneLoginClick,
          child: Padding(
            padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 6.w),
            child: Text(StringName.oneLoginTxt,
                style: TextStyle(fontSize: 14.sp, color: ColorName.black50)),
          ),
        ),
      );
    });
  }

  Widget buildPrivacyTxt() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 24.w),
      child: GestureDetector(
        onTap: controller.onPrivacyClick,
        child: Row(
          children: [
            Obx(() {
              return Image(
                  image: controller.isAgreePrivacy
                      ? Assets.images.iconCheckboxSelected.provider()
                      : Assets.images.iconCheckboxUnSelect.provider(),
                  width: 20.w,
                  height: 20.w);
            }),
            RichText(
                text: TextSpan(
                    style: TextStyle(
                        color: '#A7A7A7'.color,
                        fontSize: 12.sp,
                        decoration: TextDecoration.none),
                    children: [
                  TextSpan(text: StringName.loginEtPrivacyRead),
                  buildLinkText(StringName.privacyPolicy, WebUrl.privacyPolicy),
                  TextSpan(text: StringName.loginEtPrivacyAnd),
                  buildLinkText(StringName.termOfService, WebUrl.userAgreement),
                ]))
          ],
        ),
      ),
    );
  }

  TextSpan buildLinkText(String text, String url) {
    return TextSpan(
      text: text,
      style: TextStyle(color: '#2F79FF'.color),
      recognizer: TapGestureRecognizer()
        ..onTap = () {
          BrowserPage.start(url);
        },
    );
  }

  Widget buildCodeTextFiled() {
    return Container(
      height: 50.w,
      margin: EdgeInsets.symmetric(horizontal: 24.w),
      padding: EdgeInsets.symmetric(horizontal: 12.w),
      decoration: BoxDecoration(
          color: '#FAFAFA'.color, borderRadius: BorderRadius.circular(6.w)),
      child: Row(
        children: [
          Expanded(
            child: TextField(
              cursorHeight: 20.w,
              style: TextStyle(
                  fontSize: 16.sp,
                  color: ColorName.primaryTextColor,
                  fontWeight: FontWeight.bold),
              maxLines: 1,
              maxLength: 4,
              keyboardType: TextInputType.phone,
              textAlignVertical: TextAlignVertical.center,
              textInputAction: TextInputAction.next,
              decoration: InputDecoration(
                hintText: StringName.loginPrintVerificationCode,
                counterText: '',
                hintStyle: TextStyle(
                    fontSize: 16.sp,
                    color: "#A7A7A7".toColor(),
                    fontWeight: FontWeight.normal),
                labelStyle: TextStyle(
                  fontSize: 16.sp,
                  color: ColorName.primaryTextColor,
                ),
                contentPadding: const EdgeInsets.all(0),
                border: const OutlineInputBorder(borderSide: BorderSide.none),
                enabled: true,
              ),
              onChanged: controller.onCodeChanged,
            ),
          ),
          buildVerificationCodeSendBtn()
        ],
      ),
    );
  }

  Widget buildVerificationCodeSendBtn() {
    return Obx(() {
      return GestureDetector(
        onTap: controller.onSendVerificationCode,
        child: Container(
            margin: EdgeInsets.only(left: 12.w),
            decoration: BoxDecoration(
                color: controller.phone.length == 11 &&
                        controller.countDown == null
                    ? '#7B7DFF'.color
                    : '#337B7DFF'.color,
                borderRadius: BorderRadius.circular(4.w)),
            padding: EdgeInsets.symmetric(horizontal: 10.w, vertical: 6.w),
            child: Obx(() {
              String txt = "";
              if (controller.countDown != null) {
                txt =
                    '${controller.countDown}${StringName.loginRetransmissionCode}';
              } else {
                txt = StringName.loginSendVerificationCode;
              }
              return Text(txt,
                  style: TextStyle(fontSize: 14.sp, color: ColorName.white));
            })),
      );
    });
  }

  Widget buildPhoneTextFiled() {
    return Container(
      height: 50.w,
      margin: EdgeInsets.symmetric(horizontal: 24.w),
      padding: EdgeInsets.symmetric(horizontal: 12.w),
      decoration: BoxDecoration(
          color: '#FAFAFA'.color, borderRadius: BorderRadius.circular(6.w)),
      child: Row(
        children: [
          Text('+86',
              style: TextStyle(
                  fontSize: 16.sp,
                  color: '#202020'.color,
                  fontWeight: FontWeight.bold)),
          SizedBox(width: 8.w),
          Container(width: 1.w, height: 20.w, color: '#E2E2E2'.color),
          SizedBox(width: 25.w),
          Expanded(
            child: TextField(
              cursorHeight: 20.w,
              style: TextStyle(
                  fontSize: 16.sp,
                  color: ColorName.primaryTextColor,
                  fontWeight: FontWeight.bold),
              maxLines: 1,
              maxLength: 11,
              keyboardType: TextInputType.phone,
              textAlignVertical: TextAlignVertical.center,
              textInputAction: TextInputAction.next,
              decoration: InputDecoration(
                hintText: StringName.loginEtPhoneHint,
                counterText: '',
                hintStyle: TextStyle(
                    fontSize: 16.sp,
                    color: "#A7A7A7".toColor(),
                    fontWeight: FontWeight.normal),
                labelStyle: TextStyle(
                  fontSize: 16.sp,
                  color: ColorName.primaryTextColor,
                ),
                contentPadding: const EdgeInsets.all(0),
                border: const OutlineInputBorder(borderSide: BorderSide.none),
                enabled: true,
              ),
              onChanged: controller.onPhoneChanged,
            ),
          )
        ],
      ),
    );
  }

  Widget buildLoginHeader() {
    return SafeArea(
      child: Container(
          margin: EdgeInsets.only(top: 23.w, left: 12.w),
          child: Row(
            children: [
              GestureDetector(
                  onTap: controller.onBackClick,
                  child: Assets.images.iconWhiteBack
                      .image(width: 25.w, height: 25.w)),
              SizedBox(width: 4.w),
              Text(StringName.login,
                  style: TextStyle(fontSize: 17.sp, color: ColorName.white))
            ],
          )),
    );
  }

  Widget buildLoginBtn() {
    return Obx(() {
      return GestureDetector(
        onTap: controller.onLoginClick,
        child: Container(
          decoration: BoxDecoration(
              color: controller.phone.length == 11 &&
                      controller.code.isNotEmpty &&
                      controller.isAgreePrivacy
                  ? '#7B7DFF'.color
                  : '#337B7DFF'.color,
              borderRadius: BorderRadius.circular(30.w)),
          width: 280.w,
          height: 44.w,
          child: Center(
            child: Text(StringName.login,
                style: TextStyle(
                    fontSize: 16.sp,
                    color: ColorName.white,
                    fontWeight: FontWeight.bold)),
          ),
        ),
      );
    });
  }
}
