import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:flutter/services.dart';
import 'package:kaer_with_panels/app/common/app_run_data.dart';
import 'package:kaer_with_panels/app/widgets/hi_base_scaffold.dart';
import 'package:kaer_with_panels/app/widgets/kr_local_image.dart';
import 'package:kaer_with_panels/app/widgets/kr_subscription_expiry_text.dart';
import '../controllers/kr_delete_account_controller.dart';
import 'package:kaer_with_panels/app/localization/app_translations.dart';
import 'package:kaer_with_panels/app/widgets/kr_app_text_style.dart';

class KRDeleteAccountView extends GetView<KRDeleteAccountController> {
  const KRDeleteAccountView({super.key});

  @override
  Widget build(BuildContext context) {
    return HIBaseScaffold(
      child: GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () {
          FocusScope.of(context).unfocus();
        },
        child: SingleChildScrollView(
          child: Padding(
            padding: EdgeInsets.all(40.w),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                _buildUserInfoSection(),
                SizedBox(height: 12.w),
                // 验证码输入框
                ConstrainedBox(
                  constraints: BoxConstraints(
                    minHeight: 250.h, // 2. 设置最小高度为 300 (使用 .h 适配屏幕)
                  ),
                  // 3. 使用 Column 和 MainAxisAlignment.center 使其垂直居中
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      _buildVerificationCodeField(), // 4. 在这里调用，不修改其内部
                    ],
                  ),
                ),
                SizedBox(height: 20.w),
                GestureDetector(
                  onTap: () {
                    controller.requestDeleteAccount();
                  },
                  child: Container(
                    width: double.infinity,
                    padding: EdgeInsets.symmetric(vertical: 12.w),
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(24.w),
                      border:
                          Border.all(color: const Color(0xFFFF2ED1), width: 2),
                    ),
                    alignment: Alignment.center,
                    child: Text(
                      '注销账户',
                      style: TextStyle(
                        color: const Color(0xFFFF2ED1),
                        fontSize: 16.sp,
                        fontWeight: FontWeight.w700,
                      ),
                    ),
                  ),
                ),
                /*SizedBox(
                width: double.infinity,
                child: ElevatedButton(
                  onPressed: controller.requestDeleteAccount,
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.red,
                    padding: EdgeInsets.symmetric(vertical: 12.w),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(8.w),
                    ),
                  ),
                  child: Text(
                    AppTranslations.kr_userInfo.requestDelete,
                    style: TextStyle(
                      fontSize: 16.sp,
                      color: Colors.white,
                    ),
                  ),
                ),
              ),*/
                SizedBox(height: 20.w),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildUserInfoSection() {
    return Row(
      children: [
        Container(
          width: 60.w,
          height: 60.w,
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(18.r),
          ),
          alignment: Alignment.center,
          child: KrLocalImage(
            imageName: 'hi-home-logo',
            imageType: ImageType.svg,
            width: 30.w,
            height: 30.w,
            color: Colors.black,
          ),
        ),
        SizedBox(width: 12.w),
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Obx(() {
                final authType = KRAppRunData.getInstance().kr_authType.value;
                final accountText = authType == 'email' ? '${KRAppRunData.getInstance().kr_account.value.toString()}' : '待绑定';
                return Text(
                  accountText,
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 20,
                    fontWeight: FontWeight.bold,
                  ),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                );
              }),
              KRSubscriptionExpiryText(
                expireTimeProvider: () => controller
                    .kr_subscribeService.kr_currentSubscribe.value?.expireTime,
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 12,
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  /// 构建注册页面的验证码输入框（包含间距）
  Widget _buildVerificationCodeField() {
    return SizedBox(
      height: 50.w,
      child: TextField(
        controller: controller.kr_codeController,
        contextMenuBuilder: (context, editableTextState) => const SizedBox.shrink(),
        keyboardType: TextInputType.number,
        textInputAction: TextInputAction.done,
        autofillHints: const [AutofillHints.oneTimeCode],
        enableSuggestions: false,
        autocorrect: false,
        inputFormatters: [FilteringTextInputFormatter.digitsOnly],
        onChanged: (value) {
          var v = value.replaceAll(RegExp(r"\s+"), "");
          if (v.length % 2 == 0 && v.isNotEmpty) {
            final half = v.length ~/ 2;
            final first = v.substring(0, half);
            final second = v.substring(half);
            if (first == second) {
              v = first;
            }
          }
          const maxLen = 6;
          if (v.length > maxLen) {
            v = v.substring(0, maxLen);
          }
          if (controller.kr_codeController.text != v) {
            controller.kr_codeController.value =
                controller.kr_codeController.value.copyWith(
              text: v,
              selection: TextSelection.collapsed(offset: v.length),
              composing: TextRange.empty,
            );
          }
          if (v.isNotEmpty && (v.length >= 6)) {
            FocusScope.of(Get.context!).unfocus();
          }
        },
        onSubmitted: (_) {
          FocusScope.of(Get.context!).unfocus();
        },
        style: KrAppTextStyle(
          fontSize: 16,
          color: Colors.white,
        ),
        decoration: InputDecoration(
          hintText: '验证码',
          hintStyle: KrAppTextStyle(
            fontSize: 16,
            color: const Color(0xFFA6A6A6),
            fontWeight: FontWeight.w600,
          ),
          contentPadding:
              EdgeInsets.symmetric(horizontal: 16.w, vertical: 10.w),
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(25.w),
            borderSide: const BorderSide(color: Colors.white, width: 2),
          ),
          enabledBorder: OutlineInputBorder(
            borderRadius: BorderRadius.circular(25.w),
            borderSide: const BorderSide(color: Colors.white, width: 2),
          ),
          focusedBorder: OutlineInputBorder(
            borderRadius: BorderRadius.circular(25.w),
            borderSide: const BorderSide(color: Colors.white, width: 2),
          ),
          isDense: true,
          suffixIconConstraints: BoxConstraints(
            maxHeight: 50.w,
            maxWidth: 190.w,
          ),
          suffixIcon: Padding(
            padding: EdgeInsets.symmetric(horizontal: 5.w, vertical: 5.w),
            child: Obx(() {
              return GestureDetector(
                onTap: controller.kr_canSendCode.value
                    ? controller.kr_sendCode
                    : null,
                child: Container(
                  width: 100.w,
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                    color: controller.kr_canSendCode.value
                        ? Theme.of(Get.context!).primaryColor
                        : const Color(0xFFD5D5D5),
                    borderRadius: BorderRadius.circular(100.r),
                  ),
                  child: Text(
                    controller.kr_canSendCode.value
                        ? AppTranslations.kr_login.sendCode
                        : '${controller.kr_countdown}s',
                    style: KrAppTextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.w600,
                      color: controller.kr_canSendCode.value
                          ? Colors.black
                          : const Color(0xFF464655),
                    ),
                  ),
                ),
              );
            }),
          ),
        ),
      ),
    );
  }

  /*Widget _buildSendCodeButton(BuildContext context) {
    return Obx(() => GestureDetector(
      onTap: controller.kr_canSendCode.value ? controller.kr_sendCode : null,
      child: Container(
        height: double.infinity,
        padding: EdgeInsets.symmetric(horizontal: 12.w),
        decoration: BoxDecoration(
          border: Border(
            left: BorderSide(
              width: 0.5,
              color: const Color(0xFFD2D2D2),
            ),
          ),
        ),
        child: Center(
          child: Text(
            controller.kr_canSendCode.value 
              ? AppTranslations.kr_login.sendCode
              : '${controller.kr_countdown}s',
            style: TextStyle(
              fontSize: 14.sp,
              color: controller.kr_canSendCode.value 
                ? const Color(0xFF2196F3)
                : Theme.of(context).textTheme.bodySmall?.color,
              fontFamily: 'AlibabaPuHuiTi-Regular',
              fontWeight: FontWeight.w500,
            ),
          ),
        ),
      ),
    ));
  }*/
}
