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/model/directory/note_list_response_model.dart';

class NotesController extends GetxController {
  RxList<NoteModel> notesList = <NoteModel>[].obs;
  RxBool isLoading = false.obs;
  RxnString editingNoteId = RxnString();
  RxString searchQuery = ''.obs;

  List<NoteModel> get filteredNotesList {
    if (searchQuery.isEmpty) return notesList;

    final query = searchQuery.value.toLowerCase();
    return notesList.where((note) {
      return note.note.toLowerCase().contains(query) ||
          note.contactName.toLowerCase().contains(query) ||
          note.organizationName.toLowerCase().contains(query) ||
          note.createdBy.firstName.toLowerCase().contains(query);
    }).toList();
  }

  @override
  void onInit() {
    super.onInit();
    fetchNotes();
  }

  Future<void> fetchNotes({int pageSize = 1000, int pageNumber = 1}) async {
    isLoading.value = true;
    logSafe(
        "📤 Fetching directory notes with pageSize=$pageSize & pageNumber=$pageNumber");

    try {
      final response = await ApiService.getDirectoryNotes(
          pageSize: pageSize, pageNumber: pageNumber);
      logSafe("💡 Directory Notes Response: $response");

      if (response == null) {
        logSafe("⚠️ Response is null while fetching directory notes");
        notesList.clear();
      } else {
        logSafe("💡 Directory Notes Response: $response");
        notesList.value = NotePaginationData.fromJson(response).data;
      }
    } catch (e, st) {
      logSafe("💥 Error occurred while fetching directory notes",
          error: e, stackTrace: st);
      notesList.clear();
    } finally {
      isLoading.value = false;
    }
  }

  Future<void> updateNote(NoteModel updatedNote) async {
    try {
      logSafe(
          "Attempting to update note. id: ${updatedNote.id}, contactId: ${updatedNote.contactId}");

      final oldNote = notesList.firstWhereOrNull((n) => n.id == updatedNote.id);

      if (oldNote != null && oldNote.note.trim() == updatedNote.note.trim()) {
        logSafe("No changes detected in note. id: ${updatedNote.id}");
        showAppSnackbar(
          title: "No Changes",
          message: "No changes were made to the note.",
          type: SnackbarType.info,
        );
        return;
      }

      final success = await ApiService.updateContactComment(
        updatedNote.id,
        updatedNote.note,
        updatedNote.contactId,
      );

      if (success) {
        logSafe("Note updated successfully. id: ${updatedNote.id}");
        final index = notesList.indexWhere((n) => n.id == updatedNote.id);
        if (index != -1) {
          notesList[index] = updatedNote;
          notesList.refresh();
        }
        showAppSnackbar(
          title: "Success",
          message: "Note updated successfully.",
          type: SnackbarType.success,
        );
      } else {
        showAppSnackbar(
          title: "Error",
          message: "Failed to update note.",
          type: SnackbarType.error,
        );
      }
    } catch (e, stackTrace) {
      logSafe("Update note failed: ${e.toString()}");
      logSafe("StackTrace: ${stackTrace.toString()}");
      showAppSnackbar(
        title: "Error",
        message: "Failed to update note.",
        type: SnackbarType.error,
      );
    }
  }

  Future<void> restoreOrDeleteNote(NoteModel note,
      {bool restore = true}) async {
    final action = restore ? "restore" : "delete"; 

    try {
      logSafe("Attempting to $action note id: ${note.id}");

      final success = await ApiService.restoreContactComment(
        note.id,
        restore, // true = restore, false = delete
      );

      if (success) {
        final index = notesList.indexWhere((n) => n.id == note.id);
        if (index != -1) {
          notesList[index] = note.copyWith(isActive: restore);
          notesList.refresh();
        }
        showAppSnackbar(
          title: restore ? "Restored" : "Deleted",
          message: restore
              ? "Note has been restored successfully."
              : "Note has been deleted successfully.",
          type: SnackbarType.success,
        );
      } else {
        showAppSnackbar(
          title: "Error",
          message:
              restore ? "Failed to restore note." : "Failed to delete note.",
          type: SnackbarType.error,
        );
      }
    } catch (e, st) {
      logSafe("$action note failed: $e", error: e, stackTrace: st);
      showAppSnackbar(
        title: "Error",
        message: "Something went wrong while trying to $action the note.",
        type: SnackbarType.error,
      );
    }
  }

  void addNote(NoteModel note) {
    notesList.insert(0, note);
    logSafe("Note added to list");
  }

  void deleteNote(int index) {
    if (index >= 0 && index < notesList.length) {
      notesList.removeAt(index);
      logSafe("Note removed from list at index $index");
    }
  }

  void clearAllNotes() {
    notesList.clear();
    logSafe("All notes cleared from list");
  }
}
