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

type ViewMode = "grid" | "list";

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

const searchBarRef = ref<{ focus: () => void } | null>(null);

function onFocusSearch() {
  searchBarRef.value?.focus();
}

const { activeIndex } = useListKeyboardNavigation(
  computed(() => store.notes),
  (note) => router.push(`/notes/${note.id}`),
);

const viewMode = ref<ViewMode>(
  (localStorage.getItem("fabled-notes-view-mode") as ViewMode) ?? "grid"
);

function setViewMode(mode: ViewMode) {
  viewMode.value = mode;
  localStorage.setItem("fabled-notes-view-mode", mode);
}

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();
  }
  document.addEventListener("shortcut:focus-search", onFocusSearch);
});

onUnmounted(() => {
  document.removeEventListener("shortcut:focus-search", onFocusSearch);
});

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 ref="searchBarRef" @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" ? "↑" : "↓" }}
        </button>
      </div>
      <!-- View mode toggle -->
      <div class="view-toggle">
        <button
          :class="['toggle-btn', { active: viewMode === 'grid' }]"
          title="Grid view"
          @click="setViewMode('grid')"
        >⊞</button>
        <button
          :class="['toggle-btn', { active: viewMode === 'list' }]"
          title="Compact list"
          @click="setViewMode('list')"
        >☰</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>

    <div v-if="store.loading" class="note-list-skeleton">
      <div v-if="viewMode === 'grid'" class="skeleton-grid">
        <div class="skeleton-card" v-for="i in 6" :key="i"></div>
      </div>
      <div v-else class="skeleton-rows">
        <div class="skeleton-row" v-for="i in 8" :key="i"></div>
      </div>
    </div>
    <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>

    <!-- Grid view -->
    <div v-else-if="viewMode === 'grid'" class="cards-grid">
      <div
        v-for="(note, i) in store.notes"
        :key="note.id"
        :class="{ 'kb-active-item': activeIndex === i }"
      >
        <NoteCard :note="note" @tag-click="onTagClick" />
      </div>
    </div>

    <!-- Compact list view -->
    <div v-else class="cards-list">
      <div
        v-for="(note, i) in store.notes"
        :key="note.id"
        :class="{ 'kb-active-item': activeIndex === i }"
      >
        <NoteCard :note="note" compact @tag-click="onTagClick" />
      </div>
    </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;
  overflow-x: clip;
}
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
}
.header h1 {
  margin: 0;
}
.btn-new {
  padding: 0.45rem 1rem;
  background: linear-gradient(135deg, #6366f1, #4f46e5);
  color: #fff;
  border-radius: var(--radius-sm);
  text-decoration: none;
  font-size: 0.9rem;
  box-shadow: 0 1px 6px rgba(99, 102, 241, 0.25);
}
.btn-new:hover {
  box-shadow: 0 3px 12px rgba(99, 102, 241, 0.45);
  filter: brightness(1.08);
}
.controls {
  display: flex;
  justify-content: space-between;
  align-items: center;
  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;
}
.view-toggle {
  display: flex;
  gap: 0.2rem;
}
.toggle-btn {
  padding: 0.3rem 0.55rem;
  border: 1px solid var(--color-input-border);
  border-radius: var(--radius-sm);
  background: var(--color-bg-card);
  color: var(--color-text-muted);
  cursor: pointer;
  font-size: 1rem;
  line-height: 1;
  transition: color 0.15s, border-color 0.15s, background 0.15s;
}
.toggle-btn.active {
  background: var(--color-primary);
  border-color: var(--color-primary);
  color: #fff;
}
.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;
}

/* Skeleton loading */
.note-list-skeleton {
  margin-top: 1rem;
}
.skeleton-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
  gap: 0.75rem;
}
.skeleton-card {
  height: 140px;
  border-radius: var(--radius-md);
  background: linear-gradient(90deg, var(--color-bg-secondary) 25%, var(--color-border) 50%, var(--color-bg-secondary) 75%);
  background-size: 200% 100%;
  animation: skeleton-shimmer 1.4s ease infinite;
}
.skeleton-rows {
  display: flex;
  flex-direction: column;
  gap: 0.3rem;
}
.skeleton-row {
  height: 40px;
  border-radius: var(--radius-sm);
  background: linear-gradient(90deg, var(--color-bg-secondary) 25%, var(--color-border) 50%, var(--color-bg-secondary) 75%);
  background-size: 200% 100%;
  animation: skeleton-shimmer 1.4s ease infinite;
}
@keyframes skeleton-shimmer {
  0% { background-position: 200% 0; }
  100% { background-position: -200% 0; }
}

/* Grid layout */
.cards-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
  gap: 0.75rem;
  margin-top: 1rem;
}
.cards-grid > * {
  min-width: 0;
}

/* Compact list layout */
.cards-list {
  display: flex;
  flex-direction: column;
  gap: 0.3rem;
  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: linear-gradient(135deg, #6366f1, #4f46e5);
  color: #fff;
  border-radius: var(--radius-sm);
  text-decoration: none;
  font-size: 0.9rem;
  box-shadow: 0 1px 6px rgba(99, 102, 241, 0.25);
}
.btn-cta:hover {
  box-shadow: 0 3px 12px rgba(99, 102, 241, 0.45);
  filter: brightness(1.08);
}

.kb-active-item {
  outline: 2px solid var(--color-primary);
  border-radius: var(--radius-md);
}
</style>
