import 'package:flutter/material.dart';
import 'package:get/get.dart';

class PrecodeSendemailController extends GetxController {
  // 邮箱输入控制器
  final emailController = TextEditingController();

  // 输入框焦点
  final emailFocusNode = FocusNode();

  // 是否聚焦
  final isFocused = false.obs;

  // 是否正在发送
  final isSending = false.obs;

  // 邮箱地址
  final email = ''.obs;

  // 是否可以发送（邮箱格式验证）
  bool get canSend => _isValidEmail(email.value) && !isSending.value;

  @override
  void onInit() {
    super.onInit();
    // 监听输入变化
    emailController.addListener(() {
      email.value = emailController.text;
    });
    // 监听焦点变化
    emailFocusNode.addListener(() {
      isFocused.value = emailFocusNode.hasFocus;
    });
  }

  @override
  void onClose() {
    emailController.dispose();
    emailFocusNode.dispose();
    super.onClose();
  }

  // 验证邮箱格式
  bool _isValidEmail(String email) {
    if (email.isEmpty) return false;
    final emailRegex = RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$');
    return emailRegex.hasMatch(email);
  }

  // 发送邮件
  Future<void> sendEmail() async {
    if (!canSend) return;

    isSending.value = true;

    try {
      // TODO: 实现实际的发送邮件功能
      await Future.delayed(const Duration(seconds: 2));

      Get.snackbar(
        '发送成功',
        'Pre Code 已发送到 ${email.value}',
        snackPosition: SnackPosition.bottom,
      );

      // 发送成功后返回
      await Future.delayed(const Duration(milliseconds: 500));
      Get.back();
    } catch (e) {
      Get.snackbar('发送失败', '请检查邮箱地址后重试', snackPosition: SnackPosition.bottom);
    } finally {
      isSending.value = false;
    }
  }
}
