import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flashlink/app/components/ix_snackbar.dart';
import 'package:uuid/uuid.dart';

import '../../../../config/translations/strings_enum.dart';
import '../../../constants/configs.dart';
import '../../../constants/enums.dart';
import '../../../controllers/api_controller.dart';
import '../../../data/sp/ix_sp.dart';

class FeedbackController extends GetxController {
  final apiController = Get.find<ApiController>();
  // 反馈内容控制器
  final feedbackController = TextEditingController();

  // 邮箱控制器
  final emailController = TextEditingController();

  // 反馈内容焦点
  final feedbackFocusNode = FocusNode();
  // 邮箱焦点
  final emailFocusNode = FocusNode();

  // 是否正在提交
  final isSubmitting = false.obs;

  // 输入内容是否有效（用于按钮状态）
  final _feedbackText = ''.obs;
  final _emailText = ''.obs;

  @override
  void onInit() {
    super.onInit();
    // 监听输入变化
    feedbackController.addListener(() {
      _feedbackText.value = feedbackController.text;
    });
    emailController.addListener(() {
      _emailText.value = emailController.text;
    });
  }

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

  void onBackPressed() {
    // 判断软键盘是否弹出
    if (feedbackFocusNode.hasFocus || emailFocusNode.hasFocus) {
      FocusManager.instance.primaryFocus?.unfocus();
      // 延迟100毫秒后关闭页面
      Future.delayed(const Duration(milliseconds: 250), () {
        Get.back();
      });
    } else {
      Get.back();
    }
  }

  /// 提交反馈
  void submitFeedback() async {
    if (feedbackController.text.trim().isEmpty) {
      IXSnackBar.showIXErrorSnackBar(
        title: Strings.error.tr,
        message: Strings.pleaseEnterFeedback.tr,
      );
      return;
    }

    if (emailController.text.trim().isEmpty) {
      IXSnackBar.showIXErrorSnackBar(
        title: Strings.error.tr,
        message: Strings.pleaseEnterEmail.tr,
      );
      return;
    }

    // 简单的邮箱格式验证
    if (!GetUtils.isEmail(emailController.text.trim())) {
      IXSnackBar.showIXErrorSnackBar(
        title: Strings.error.tr,
        message: Strings.pleaseEnterValidEmail.tr,
      );
      return;
    }
    // 取消输入框焦点，关闭软键盘
    FocusManager.instance.primaryFocus?.unfocus();
    isSubmitting.value = true;

    try {
      final appConfig = IXSP.getAppConfig();

      if (!((appConfig?.disabledLogModules ?? [])).contains(
        LogModule.NM_FeedbackLog.name,
      )) {
        await apiController.uploadLogs([
          {
            "id": const Uuid().v4(),
            "time": DateTime.now().millisecondsSinceEpoch,
            "level": LogLevel.info.name,
            'module': LogModule.NM_FeedbackLog.name,
            "category": Configs.productCode,
            "fields": {
              'content': feedbackController.text.trim(),
              'email': emailController.text.trim(),
            },
          },
        ]);
      }

      // 提交成功
      IXSnackBar.showIXSnackBar(
        title: Strings.success.tr,
        message: Strings.feedbackSubmitted.tr,
      );

      // 清空输入框
      feedbackController.clear();
      emailController.clear();

      // 延迟返回
      Future.delayed(const Duration(milliseconds: 500), () {
        Get.back();
      });
    } catch (e) {
      IXSnackBar.showIXErrorSnackBar(
        title: Strings.error.tr,
        message: Strings.feedbackSubmitFailed.tr,
      );
    } finally {
      isSubmitting.value = false;
    }
  }

  /// 检查是否可以提交（响应式）
  bool get canSubmit {
    // 访问响应式变量以触发 Obx 更新
    return _feedbackText.value.trim().isNotEmpty &&
        _emailText.value.trim().isNotEmpty;
  }
}
