<script setup lang="ts">
import { onMounted, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useNotesStore } from "@/stores/notes";
import SearchBar from "@/components/SearchBar.vue";
import NoteCard from "@/components/NoteCard.vue";
import TagPill from "@/components/TagPill.vue";
import PaginationBar from "@/components/PaginationBar.vue";

const route = useRoute();
const router = useRouter();
const store = useNotesStore();

onMounted(() => {
  const tag = route.query.tag;
  if (tag) {
    const tags = Array.isArray(tag) ? (tag as string[]) : [tag as string];
    store.setTagFilters(tags);
  } else {
    store.refresh();
  }
});

watch(
  () => route.query.tag,
  (tag) => {
    if (tag) {
      const tags = Array.isArray(tag) ? (tag as string[]) : [tag as string];
      store.setTagFilters(tags);
    }
  }
);

function onSearch(q: string) {
  store.setSearch(q);
}

function onTagClick(tag: string) {
  store.addTagFilter(tag);
  router.replace({ query: { ...route.query, tag: store.activeTagFilters } });
}

function onTagDismiss(tag: string) {
  store.removeTagFilter(tag);
  const newQuery = { ...route.query };
  if (store.activeTagFilters.length > 0) {
    newQuery.tag = store.activeTagFilters;
  } else {
    delete newQuery.tag;
  }
  router.replace({ query: newQuery });
}

function onSortChange(e: Event) {
  const value = (e.target as HTMLSelectElement).value;
  store.setSort(value, store.sortOrder);
}

function toggleOrder() {
  store.setSort(store.sortField, store.sortOrder === "asc" ? "desc" : "asc");
}

function onOffsetUpdate(offset: number) {
  store.setOffset(offset);
}
</script>

<template>
  <main class="notes-list">
    <div class="header">
      <h1>Notes</h1>
      <router-link to="/notes/new" class="btn-new">+ New Note</router-link>
    </div>
    <SearchBar @search="onSearch" />

    <div class="controls">
      <div class="sort-controls">
        <select :value="store.sortField" @change="onSortChange" class="sort-select">
          <option value="updated_at">Updated</option>
          <option value="created_at">Created</option>
          <option value="title">Title</option>
        </select>
        <button class="sort-order" @click="toggleOrder" :title="store.sortOrder === 'asc' ? 'Ascending' : 'Descending'">
          {{ store.sortOrder === "asc" ? "\u2191" : "\u2193" }}
        </button>
      </div>
    </div>

    <div v-if="store.activeTagFilters.length" class="active-filters">
      <span class="filter-label">Filtering by:</span>
      <TagPill
        v-for="tag in store.activeTagFilters"
        :key="tag"
        :tag="tag"
        dismissible
        @dismiss="onTagDismiss"
      />
      <button class="clear-filters" @click="store.clearTagFilters()">Clear all</button>
    </div>

    <p v-if="store.loading">Loading...</p>
    <div
      v-else-if="store.notes.length === 0"
      class="empty-state"
    >
      <template v-if="store.searchQuery || store.activeTagFilters.length">
        <p class="empty-title">No notes match your filters</p>
        <p class="empty-subtitle">Try adjusting your search or removing filters.</p>
      </template>
      <template v-else>
        <p class="empty-title">No notes yet</p>
        <p class="empty-subtitle">Create your first note to get started.</p>
        <router-link to="/notes/new" class="btn-cta">+ New Note</router-link>
      </template>
    </div>
    <div v-else class="cards">
      <NoteCard
        v-for="note in store.notes"
        :key="note.id"
        :note="note"
        @tag-click="onTagClick"
      />
    </div>

    <PaginationBar
      :total="store.total"
      :limit="store.limit"
      :offset="store.offset"
      @update:offset="onOffsetUpdate"
    />
  </main>
</template>

<style scoped>
.notes-list {
  max-width: 1200px;
  margin: 2rem auto;
  padding: 0 1rem;
}
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
}
.header h1 {
  margin: 0;
}
.btn-new {
  padding: 0.45rem 1rem;
  background: var(--color-primary);
  color: #fff;
  border-radius: var(--radius-sm);
  text-decoration: none;
  font-size: 0.9rem;
}
.controls {
  display: flex;
  justify-content: flex-end;
  margin-top: 0.75rem;
}
.sort-controls {
  display: flex;
  align-items: center;
  gap: 0.25rem;
}
.sort-select {
  padding: 0.3rem 0.5rem;
  border: 1px solid var(--color-input-border);
  border-radius: var(--radius-sm);
  background: var(--color-bg-card);
  color: var(--color-text);
  font-size: 0.85rem;
}
.sort-order {
  padding: 0.3rem 0.5rem;
  border: 1px solid var(--color-input-border);
  border-radius: var(--radius-sm);
  background: var(--color-bg-card);
  color: var(--color-text);
  cursor: pointer;
  font-size: 0.95rem;
}
.active-filters {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  margin-top: 0.75rem;
  flex-wrap: wrap;
}
.filter-label {
  font-size: 0.85rem;
  color: var(--color-text-secondary);
}
.clear-filters {
  background: none;
  border: none;
  color: var(--color-danger);
  cursor: pointer;
  font-size: 0.8rem;
  padding: 0;
}
.cards {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
  margin-top: 1rem;
}
.empty-state {
  text-align: center;
  margin-top: 3rem;
}
.empty-title {
  font-size: 1.1rem;
  font-weight: 600;
  margin: 0 0 0.25rem;
  color: var(--color-text);
}
.empty-subtitle {
  color: var(--color-text-muted);
  margin: 0 0 1rem;
  font-size: 0.95rem;
}
.btn-cta {
  display: inline-block;
  padding: 0.45rem 1rem;
  background: var(--color-primary);
  color: #fff;
  border-radius: var(--radius-sm);
  text-decoration: none;
  font-size: 0.9rem;
}
</style>
