<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useTasksStore } from "@/stores/tasks";
import type { Task, TaskStatus } from "@/types/task";
import { apiGet } from "@/api/client";
import SearchBar from "@/components/SearchBar.vue";
import TaskCard from "@/components/TaskCard.vue";
import TagPill from "@/components/TagPill.vue";
import PaginationBar from "@/components/PaginationBar.vue";

type ViewMode = "flat" | "grouped";

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

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

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

function onKeydown(e: KeyboardEvent) {
  if (viewMode.value !== "flat") return;
  const el = document.activeElement;
  const tag = el ? (el as HTMLElement).tagName : "";
  const isInput = tag === "INPUT" || tag === "TEXTAREA" || (el as HTMLElement)?.isContentEditable;
  if (isInput || e.ctrlKey || e.metaKey || e.altKey) return;
  const count = store.tasks.length;
  if (e.key === "j") {
    e.preventDefault();
    activeIndex.value = Math.min(activeIndex.value + 1, count - 1);
    document.querySelector(".kb-active-item")?.scrollIntoView({ block: "nearest" });
  } else if (e.key === "k") {
    e.preventDefault();
    activeIndex.value = Math.max(activeIndex.value - 1, 0);
    document.querySelector(".kb-active-item")?.scrollIntoView({ block: "nearest" });
  } else if (e.key === "Enter" && activeIndex.value >= 0) {
    const task = store.tasks[activeIndex.value];
    if (task) router.push(`/tasks/${task.id}`);
  }
}

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

function setViewMode(mode: ViewMode) {
  viewMode.value = mode;
  localStorage.setItem("fabled-tasks-view-mode", mode);
  if (mode === "grouped") {
    store.limit = 100;
    store.offset = 0;
  } else {
    store.limit = 20;
    store.offset = 0;
  }
  store.refresh();
}

// Project map for group labels and task breadcrumbs
const projectMap = ref<Map<number, string>>(new Map());

async function loadProjects() {
  try {
    const data = await apiGet<{ projects: { id: number; title: string }[] }>("/api/projects");
    projectMap.value = new Map(data.projects.map((p) => [p.id, p.title]));
  } catch {
    // non-fatal — labels just won't show
  }
}

// Grouped tasks: [{projectId, title, tasks[]}]
interface TaskGroup {
  projectId: number | null;
  title: string;
  tasks: Task[];
}

const groupedTasks = computed<TaskGroup[]>(() => {
  if (viewMode.value !== "grouped") return [];
  const map = new Map<number | null, Task[]>();
  for (const task of store.tasks) {
    const key = task.project_id ?? null;
    if (!map.has(key)) map.set(key, []);
    map.get(key)!.push(task);
  }
  const groups: TaskGroup[] = [];
  // Named projects first (sorted by title), then "No Project"
  for (const [id, tasks] of map) {
    if (id !== null) {
      groups.push({
        projectId: id,
        title: projectMap.value.get(id) ?? `Project #${id}`,
        tasks,
      });
    }
  }
  groups.sort((a, b) => a.title.localeCompare(b.title));
  if (map.has(null)) {
    groups.push({ projectId: null, title: "No Project", tasks: map.get(null)! });
  }
  return groups;
});

onMounted(async () => {
  const tag = route.query.tag;
  if (tag) {
    const tags = Array.isArray(tag) ? (tag as string[]) : [tag as string];
    store.activeTagFilters = tags;
  }
  if (route.query.status) {
    store.statusFilter = route.query.status as TaskStatus;
  }
  if (viewMode.value === "grouped") {
    store.limit = 100;
  }
  await Promise.all([store.refresh(), loadProjects()]);
  document.addEventListener("shortcut:focus-search", onFocusSearch);
  document.addEventListener("keydown", onKeydown);
});

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

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

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

function onStatusFilterChange(e: Event) {
  const value = (e.target as HTMLSelectElement).value;
  store.setStatusFilter(value as TaskStatus | "");
}

function onPriorityFilterChange(e: Event) {
  const value = (e.target as HTMLSelectElement).value;
  store.setPriorityFilter(value as any);
}

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 onStatusToggle(id: number, status: TaskStatus) {
  store.patchStatus(id, status);
}

function onOffsetUpdate(offset: number) {
  store.setOffset(offset);
}

// Collapse state for grouped sections
const collapsedGroups = ref<Set<string>>(new Set());
function toggleGroup(key: string) {
  if (collapsedGroups.value.has(key)) {
    collapsedGroups.value.delete(key);
  } else {
    collapsedGroups.value.add(key);
  }
}
</script>

<template>
  <main class="tasks-list">
    <div class="header">
      <h1>Tasks</h1>
      <router-link to="/tasks/new" class="btn-new">+ New Task</router-link>
    </div>
    <SearchBar ref="searchBarRef" @search="onSearch" />

    <div class="controls">
      <div class="filter-controls">
        <select :value="store.statusFilter" @change="onStatusFilterChange" class="filter-select">
          <option value="">All Statuses</option>
          <option value="todo">Todo</option>
          <option value="in_progress">In Progress</option>
          <option value="done">Done</option>
        </select>
        <select :value="store.priorityFilter" @change="onPriorityFilterChange" class="filter-select">
          <option value="">All Priorities</option>
          <option value="none">None</option>
          <option value="low">Low</option>
          <option value="medium">Medium</option>
          <option value="high">High</option>
        </select>
      </div>
      <div class="right-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>
            <option value="due_date">Due Date</option>
            <option value="priority">Priority</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 === 'flat' }]"
            title="Flat list"
            @click="setViewMode('flat')"
          >☰</button>
          <button
            :class="['toggle-btn', { active: viewMode === 'grouped' }]"
            title="Group by project"
            @click="setViewMode('grouped')"
          >⊟</button>
        </div>
      </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.tasks.length === 0" class="empty-state">
      <template v-if="store.searchQuery || store.activeTagFilters.length || store.statusFilter || store.priorityFilter">
        <p class="empty-title">No tasks 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 tasks yet</p>
        <p class="empty-subtitle">Create your first task to get started.</p>
        <router-link to="/tasks/new" class="btn-cta">+ New Task</router-link>
      </template>
    </div>

    <!-- Grouped view -->
    <template v-else-if="viewMode === 'grouped'">
      <div
        v-for="group in groupedTasks"
        :key="group.projectId ?? 'none'"
        class="task-group"
      >
        <button
          class="group-header"
          @click="toggleGroup(String(group.projectId))"
        >
          <span class="group-chevron">{{ collapsedGroups.has(String(group.projectId)) ? '▶' : '▼' }}</span>
          <span class="group-title">{{ group.title }}</span>
          <span class="group-count">{{ group.tasks.length }}</span>
          <router-link
            v-if="group.projectId"
            :to="`/projects/${group.projectId}`"
            class="group-open-link"
            @click.stop
          >Open project →</router-link>
        </button>
        <div v-if="!collapsedGroups.has(String(group.projectId))" class="group-tasks">
          <TaskCard
            v-for="task in group.tasks"
            :key="task.id"
            :task="task"
            compact
            @tag-click="onTagClick"
            @status-toggle="onStatusToggle"
          />
        </div>
      </div>
    </template>

    <!-- Flat compact list -->
    <div v-else class="cards-list">
      <div
        v-for="(task, i) in store.tasks"
        :key="task.id"
        :class="{ 'kb-active-item': activeIndex === i }"
      >
        <TaskCard
          :task="task"
          compact
          :project-title="task.project_id ? (projectMap.get(task.project_id) ?? undefined) : undefined"
          @tag-click="onTagClick"
          @status-toggle="onStatusToggle"
        />
      </div>
    </div>

    <PaginationBar
      v-if="viewMode === 'flat'"
      :total="store.total"
      :limit="store.limit"
      :offset="store.offset"
      @update:offset="onOffsetUpdate"
    />
  </main>
</template>

<style scoped>
.tasks-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: var(--color-primary);
  color: #fff;
  border-radius: var(--radius-sm);
  text-decoration: none;
  font-size: 0.9rem;
}
.controls {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 0.75rem;
  gap: 0.5rem;
  flex-wrap: wrap;
}
.filter-controls {
  display: flex;
  gap: 0.5rem;
}
.right-controls {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}
.filter-select,
.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-controls {
  display: flex;
  align-items: center;
  gap: 0.25rem;
}
.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;
}

/* Flat compact list */
.cards-list {
  display: flex;
  flex-direction: column;
  gap: 0.3rem;
  margin-top: 1rem;
}

/* Grouped view */
.task-group {
  margin-top: 1.25rem;
}
.group-header {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  width: 100%;
  background: none;
  border: none;
  border-bottom: 1px solid var(--color-border);
  padding: 0.3rem 0 0.3rem 0;
  cursor: pointer;
  text-align: left;
  color: var(--color-text);
}
.group-header:hover {
  color: var(--color-primary);
}
.group-chevron {
  font-size: 0.65rem;
  color: var(--color-text-muted);
  flex-shrink: 0;
}
.group-title {
  font-size: 0.8rem;
  font-weight: 700;
  text-transform: uppercase;
  letter-spacing: 0.06em;
  flex: 1;
}
.group-count {
  font-size: 0.75rem;
  color: var(--color-text-muted);
  background: var(--color-bg-secondary);
  border-radius: 999px;
  padding: 0.1rem 0.45rem;
}
.group-open-link {
  font-size: 0.75rem;
  color: var(--color-primary);
  text-decoration: none;
  flex-shrink: 0;
}
.group-open-link:hover {
  text-decoration: underline;
}
.group-tasks {
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
  margin-top: 0.4rem;
}

.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;
}

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