import 'dart:async';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:kaer_with_panels/app/common/app_run_data.dart';
import 'package:kaer_with_panels/app/model/enum/kr_request_type.dart';
import 'package:kaer_with_panels/app/services/api_service/kr_auth_api.dart';
import 'package:kaer_with_panels/app/utils/kr_common_util.dart';

import '../../../localization/app_translations.dart';

class KRDeleteAccountController extends GetxController {
  // 验证码输入框控制器
  final TextEditingController kr_codeController = TextEditingController();
  
  // 验证码输入框是否有文本
  final RxBool kr_codeHasText = false.obs;
  
  // 是否可以发送验证码
  final RxBool kr_canSendCode = true.obs;
  
  // 倒计时秒数
  final RxInt kr_countdown = 60.obs;
  
  // 定时器
  Timer? _timer;

  // API 实例
  final KRAuthApi _authApi = KRAuthApi();

  @override
  void onInit() {
    super.onInit();
    // 监听验证码输入框文本变化
    kr_codeController.addListener(() {
      kr_codeHasText.value = kr_codeController.text.isNotEmpty;
    });
  }

  @override
  void onClose() {
    kr_codeController.dispose();
    _timer?.cancel();
    super.onClose();
  }

  // 发送验证码
  Future<void> kr_sendCode() async {
    final account = KRAppRunData.getInstance().kr_account;
    if (account == null || account.isEmpty) {
      KRCommonUtil.kr_showToast('账号不能为空');
      return;
    }

    // 判断账号类型
    final isEmail = KRAppRunData.getInstance().kr_loginType == KRLoginType.kr_email;
    final type = isEmail ? KRLoginType.kr_email : KRLoginType.kr_telephone;
    
    // 发送验证码
    final result = await _authApi.kr_sendCode(
      type,
      account,
      KRAppRunData.getInstance().kr_areaCode,  // 手机号不需要区号
      2,  // 删除账号的验证码类型
    );

    result.fold(
      (error) {
        KRCommonUtil.kr_showToast(error.msg);
      },
      (success) {
        kr_canSendCode.value = false;
        kr_countdown.value = 60;
        
        _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
          if (kr_countdown.value > 0) {
            kr_countdown.value--;
          } else {
            timer.cancel();
            kr_canSendCode.value = true;
          }
        });
      },
    );
  }

  // 请求删除账号
  Future<void> requestDeleteAccount() async {
    if (kr_codeController.text.isEmpty) {
      KRCommonUtil.kr_showToast(AppTranslations.kr_login.sendCode);
      return;
    }
    final result = await _authApi.kr_deleteAccount(
      KRAppRunData.getInstance().kr_loginType ?? KRLoginType.kr_telephone,

      kr_codeController.text,
    );
    result.fold(
      (error) {
        KRCommonUtil.kr_showToast(error.msg);
      },
      (success) {
        KRCommonUtil.kr_showToast('删除账号成功');
        KRAppRunData.getInstance().kr_loginOut();
      },
    );
    // TODO: 实现删除账号的逻辑
   
  }
}
