<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, TaskPriority } from "@/types/task";
import { apiGet } from "@/api/client";
import { useListKeyboardNavigation } from "@/composables/useListKeyboardNavigation";
import SearchBar from "@/components/SearchBar.vue";
import TaskCard from "@/components/TaskCard.vue";
import TagPill from "@/components/TagPill.vue";

type ViewMode = "smart" | "grouped";

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

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

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

const _storedMode = localStorage.getItem("fabled-tasks-view-mode");
const viewMode = ref<ViewMode>(_storedMode === "grouped" ? "grouped" : "smart");

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

// Keyboard nav disabled — smart sections span multiple containers
useListKeyboardNavigation(
  computed(() => store.tasks),
  (task) => router.push(`/tasks/${task.id}`),
  ".kb-active-item",
  computed(() => false),
);

// 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[];
}

interface TaskSection {
  key: string;
  label: string;
  tasks: Task[];
}

const smartSections = computed<TaskSection[]>(() => {
  if (viewMode.value !== "smart") return [];
  const today = new Date().toISOString().slice(0, 10);
  const weekEnd = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString().slice(0, 10);
  const overdue: Task[] = [], dueToday: Task[] = [], thisWeek: Task[] = [],
        upcoming: Task[] = [], noDueDate: Task[] = [], done: Task[] = [];
  for (const task of store.tasks) {
    if (task.status === "done")   { done.push(task); continue; }
    if (!task.due_date)           { noDueDate.push(task); continue; }
    if (task.due_date < today)    { overdue.push(task); continue; }
    if (task.due_date === today)  { dueToday.push(task); continue; }
    if (task.due_date <= weekEnd) { thisWeek.push(task); continue; }
    upcoming.push(task);
  }
  const sections: TaskSection[] = [];
  if (overdue.length)   sections.push({ key: "overdue",  label: "Overdue",      tasks: overdue });
  if (dueToday.length)  sections.push({ key: "today",    label: "Due Today",    tasks: dueToday });
  if (thisWeek.length)  sections.push({ key: "week",     label: "This Week",    tasks: thisWeek });
  if (upcoming.length)  sections.push({ key: "upcoming", label: "Upcoming",     tasks: upcoming });
  if (noDueDate.length) sections.push({ key: "no-date",  label: "No Due Date",  tasks: noDueDate });
  if (done.length)      sections.push({ key: "done",     label: "Completed",    tasks: done });
  return sections;
});

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) {
    const qs = route.query.status;
    store.statusFilter = (Array.isArray(qs) ? qs : [qs]).filter(Boolean) as TaskStatus[];
  }
  store.limit = viewMode.value === "grouped" ? 100 : 200;
  collapsedGroups.value.add("done");
  await Promise.all([store.refresh(), loadProjects()]);
  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.activeTagFilters = tags;
      store.offset = 0;
      store.refresh();
    }
  }
);

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

function toggleStatusChip(value: TaskStatus) {
  const current = [...store.statusFilter];
  const idx = current.indexOf(value);
  if (idx === -1) current.push(value);
  else current.splice(idx, 1);
  store.setStatusFilter(current);
}

function togglePriorityChip(value: TaskPriority) {
  const current = [...store.priorityFilter];
  const idx = current.indexOf(value);
  if (idx === -1) current.push(value);
  else current.splice(idx, 1);
  store.setPriorityFilter(current);
}

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

// 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">
        <div class="filter-chip-group">
          <button v-for="s in (['todo', 'in_progress', 'done', 'cancelled'] as TaskStatus[])" :key="s"
            :class="['filter-chip', { active: store.statusFilter.includes(s) }]"
            @click="toggleStatusChip(s)">
            {{ { todo: 'Todo', in_progress: 'In Progress', done: 'Done', cancelled: 'Cancelled' }[s] }}
          </button>
        </div>
        <div class="filter-chip-group">
          <button v-for="p in (['low', 'medium', 'high'] as TaskPriority[])" :key="p"
            :class="['filter-chip', { active: store.priorityFilter.includes(p) }]"
            @click="togglePriorityChip(p)">
            {{ p.charAt(0).toUpperCase() + p.slice(1) }}
          </button>
        </div>
      </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 === 'smart' }]"
            title="Smart sections (by due date)"
            @click="setViewMode('smart')"
          >☰</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>

    <div v-if="store.loading" class="task-list-skeleton">
      <div class="skeleton-row" v-for="i in 6" :key="i"></div>
    </div>

    <div v-else-if="store.tasks.length === 0" class="empty-state">
      <template v-if="store.searchQuery || store.activeTagFilters.length || store.statusFilter.length || store.priorityFilter.length">
        <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>
        <div class="empty-state-rich">
          <div class="empty-icon">✓</div>
          <p class="empty-title">No tasks yet</p>
          <p class="empty-sub">Create your first task to start tracking work</p>
          <router-link to="/tasks/new" class="empty-action">New task →</router-link>
        </div>
      </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>

    <!-- Smart sections view (by due date) -->
    <template v-else>
      <div v-for="section in smartSections" :key="section.key" class="task-section">
        <button class="section-header" @click="toggleGroup(section.key)">
          <span :class="['section-dot', `dot-${section.key}`]"></span>
          <span class="section-label">{{ section.label }}</span>
          <span class="section-count">{{ section.tasks.length }}</span>
          <span class="section-chevron">{{ collapsedGroups.has(section.key) ? "▶" : "▼" }}</span>
        </button>
        <div v-show="!collapsedGroups.has(section.key)" class="section-tasks">
          <TaskCard
            v-for="task in section.tasks"
            :key="task.id"
            :task="task"
            compact
            :project-title="task.project_id ? (projectMap.get(task.project_id) ?? undefined) : undefined"
            @tag-click="onTagClick"
            @status-toggle="onStatusToggle"
          />
        </div>
      </div>
    </template>
  </main>
</template>

<style scoped>
.tasks-list {
  max-width: var(--page-max-width);
  margin: 2rem auto;
  padding: 0 var(--page-padding-x);
  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;
  gap: 0.5rem;
  flex-wrap: wrap;
}
.filter-controls {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
}
.filter-chip-group {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}
.filter-chip {
  padding: 3px 10px;
  border-radius: 999px;
  border: 1px solid var(--color-input-border);
  background: transparent;
  color: var(--color-text-muted);
  cursor: pointer;
  font-size: 0.78rem;
  transition: background 0.15s, color 0.15s, border-color 0.15s;
}
.filter-chip.active {
  background: var(--color-primary);
  color: #fff;
  border-color: var(--color-primary);
}
.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;
}

/* Skeleton loading */
.task-list-skeleton {
  margin-top: 1rem;
}
.skeleton-row {
  height: 44px;
  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;
  margin-bottom: 0.3rem;
}
@keyframes skeleton-shimmer {
  0% { background-position: 200% 0; }
  100% { background-position: -200% 0; }
}

/* Smart sections */
.task-section {
  margin-top: 1rem;
}
.section-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;
  cursor: pointer;
  text-align: left;
  color: var(--color-text);
}
.section-header:hover .section-label {
  color: var(--color-primary);
}
.section-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  flex-shrink: 0;
}
.dot-overdue  { background: var(--color-danger, #e74c3c); }
.dot-today    { background: var(--color-primary); }
.dot-week     { background: #f59e0b; }
.dot-upcoming { background: var(--color-text-secondary); }
.dot-no-date  { background: var(--color-text-muted); }
.dot-done     { background: var(--color-status-done, #22c55e); }
.section-label {
  font-size: 0.8rem;
  font-weight: 700;
  text-transform: uppercase;
  letter-spacing: 0.06em;
  flex: 1;
  transition: color 0.15s;
}
.section-count {
  font-size: 0.75rem;
  color: var(--color-text-muted);
  background: var(--color-bg-secondary);
  border-radius: 999px;
  padding: 0.1rem 0.45rem;
}
.section-chevron {
  font-size: 0.65rem;
  color: var(--color-text-muted);
  flex-shrink: 0;
}
.section-tasks {
  display: flex;
  flex-direction: column;
  gap: 0.35rem;
  padding: 0.5rem 0 0.25rem;
}

/* 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;
}
.empty-state-rich {
  text-align: center;
  padding: 3rem 1rem;
  color: var(--color-text-muted);
}
.empty-icon {
  font-size: 2.5rem;
  margin-bottom: 0.75rem;
  opacity: 0.3;
}
.empty-state-rich .empty-title {
  font-size: 1rem;
  font-weight: 600;
  color: var(--color-text-secondary);
  margin: 0 0 0.35rem;
}
.empty-sub {
  font-size: 0.85rem;
  margin: 0 0 1rem;
}
.empty-action {
  display: inline-block;
  padding: 0.4rem 1rem;
  border: 1px solid var(--color-primary);
  border-radius: var(--radius-sm);
  color: var(--color-primary);
  text-decoration: none;
  font-size: 0.85rem;
  transition: background 0.15s, color 0.15s;
}
.empty-action:hover {
  background: var(--color-primary);
  color: #fff;
}

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