<script setup lang="ts">
import { computed, watch } from "vue";
import { useRoute } from "vue-router";
import { repo } from "../adapters";
import { useNoteList } from "../composables/useNoteList";
import { useNoteEditor } from "../composables/useNoteEditor";
import AsyncState from "../components/AsyncState.vue";
import EmptyState from "../components/EmptyState.vue";
import NoteGrid from "../components/NoteGrid.vue";
import NoteEditor from "../components/NoteEditor.vue";

const route = useRoute();
const query = computed(() => (typeof route.query.q === "string" ? route.query.q : ""));
const noMatchSubtitle = computed(() => `Nothing found for "${query.value}".`);

const { items: results, loading, error, load: run } = useNoteList(async () => {
  const q = query.value.trim();
  if (!q) return [];
  return repo.notes.search(q);
}, "Search failed.");

const { editing, open: openEditor, close: closeEditor, navigate: onNavigate } = useNoteEditor({
  list: () => results.value,
  onClose: run, // reflect any edits made from a result
});

watch(query, run, { immediate: true });
</script>

<template>
  <div class="mx-auto w-full max-w-6xl px-4 py-6">
    <p class="mb-4 text-sm text-neutral-500 dark:text-neutral-400">
      <template v-if="query"
        >Results for <span class="font-semibold text-neutral-800 dark:text-neutral-200">{{ query }}</span></template
      >
      <template v-else>Type in the search box to find your notes.</template>
    </p>

    <AsyncState :loading="loading" :error="error || undefined" error-title="Couldn't search" @retry="run">
      <EmptyState v-if="query && results.length === 0" title="No matches" :subtitle="noMatchSubtitle" />
      <NoteGrid v-else-if="results.length" :notes="results" @open="openEditor" />
    </AsyncState>
  </div>

  <template v-if="editing">
    <NoteEditor :note="editing" @close="closeEditor" @navigate="onNavigate" />
  </template>
</template>
