import 'package:get/get.dart';
import 'package:on_field_work/helpers/services/api_service.dart';
import 'package:on_field_work/helpers/services/app_logger.dart';
import 'package:on_field_work/helpers/widgets/my_snackbar.dart';
import 'package:on_field_work/controller/directory/directory_controller.dart';
import 'package:on_field_work/controller/directory/notes_controller.dart';

class AddCommentController extends GetxController {
  final String contactId;

  AddCommentController({required this.contactId});

  final RxString note = ''.obs;
  final RxBool isSubmitting = false.obs;

  Future<void> submitComment() async {
    if (note.value.trim().isEmpty) {
      showAppSnackbar(
        title: "Missing Comment",
        message: "Please enter a comment before submitting.",
        type: SnackbarType.warning,
      );
      return;
    }

    isSubmitting.value = true;

    try {
      logSafe("Submitting comment for contactId: $contactId");

      final success = await ApiService.addContactComment(
        note.value.trim(),
        contactId,
      );

      if (success) {
        logSafe("Comment added successfully.");

        // Refresh UI
        final directoryController = Get.find<DirectoryController>();
        await directoryController.fetchCommentsForContact(contactId);

        final notesController = Get.find<NotesController>();
        await notesController.fetchNotes(
            pageSize: 1000, pageNumber: 1); // ✅ Fixed here

        Get.back(result: true);

        showAppSnackbar(
          title: "Comment Added",
          message: "Your comment has been successfully added.",
          type: SnackbarType.success,
        );
      }
    } catch (e) {
      logSafe("Error while submitting comment: $e", level: LogLevel.error);
      showAppSnackbar(
        title: "Unexpected Error",
        message: "Something went wrong while adding your comment.",
        type: SnackbarType.error,
      );
    } finally {
      isSubmitting.value = false;
    }
  }

  void updateNote(String value) {
    note.value = value;
    logSafe("Note updated: ${value.trim()}");
  }
}
