<script>
  import { invoke } from "@tauri-apps/api/core";
  import {
    tasks, addTask, completeTask, uncompleteTask, deleteTask, updateTask,
    taskLists, addTaskList, renameTaskList, deleteTaskList,
  } from "$lib/stores/page.svelte.js";
  import Card from "$lib/components/Card.svelte";
  import { formatTimestamp } from "$lib/utils/time.js";
  import { BUCKET_COLORS, EFFORT_LABELS, EFFORT_ORDER } from "$lib/utils/constants.js";

  let activeBucket = $state("all");
  let activeListId = $state("all");
  let showCompleted = $state(false);
  let quickInput = $state("");
  let searchQuery = $state("");
  let sidebarCollapsed = $state(false);
  let showNewList = $state(false);
  let newListName = $state("");
  let sortMode = $state("date");
  let showSortMenu = $state(false);
  let contextMenuListId = $state(null);
  let editingListId = $state(null);
  let editingName = $state("");

  const buckets = [
    { id: "all", label: "All", icon: "M4 6h16M4 12h16M4 18h16" },
    { id: "inbox", label: "Inbox", icon: "M20 12V6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v6m16 0v6a2 2 0 0 0-2 2H6a2 2 0 0 0-2-2v-6m16 0H4" },
    { id: "today", label: "Today", icon: "M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20Zm0 18a8 8 0 1 1 0-16 8 8 0 0 1 0 16Zm-1-13v5l4.28 2.54.72-1.21-3.5-2.08V7h-1.5Z" },
    { id: "soon", label: "Soon", icon: "M17 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V5a2 2 0 0 0-2-2ZM7 7h10M7 11h10M7 15h5" },
    { id: "later", label: "Later", icon: "M5 3v18l7-3 7 3V3H5Z" },
  ];


  let filteredTasks = $derived.by(() => {
    let list = tasks.filter((t) => !t.done);
    // Bucket filter
    if (activeBucket !== "all") {
      list = list.filter((t) => t.bucket === activeBucket);
    }
    // List filter
    if (activeListId !== "all") {
      if (activeListId === "inbox") {
        list = list.filter((t) => !t.listId);
      } else {
        list = list.filter((t) => t.listId === activeListId);
      }
    }
    // Search
    if (searchQuery.trim()) {
      const q = searchQuery.toLowerCase();
      list = list.filter((t) => t.text.toLowerCase().includes(q));
    }
    // Sort
    if (sortMode === "quick-first") {
      list.sort((a, b) => (EFFORT_ORDER[a.effort] || 4) - (EFFORT_ORDER[b.effort] || 4));
    } else if (sortMode === "deep-first") {
      list.sort((a, b) => (EFFORT_ORDER[b.effort] || 4) - (EFFORT_ORDER[a.effort] || 4));
    }
    return list;
  });

  let completedTasks = $derived.by(() => {
    let list = tasks.filter((t) => t.done);
    if (activeBucket !== "all") {
      list = list.filter((t) => t.bucket === activeBucket);
    }
    if (activeListId !== "all") {
      if (activeListId === "inbox") {
        list = list.filter((t) => !t.listId);
      } else {
        list = list.filter((t) => t.listId === activeListId);
      }
    }
    if (searchQuery.trim()) {
      const q = searchQuery.toLowerCase();
      list = list.filter((t) => t.text.toLowerCase().includes(q));
    }
    return list.slice(0, 20);
  });

  let bucketCounts = $derived.by(() => {
    const counts = { all: 0, inbox: 0, today: 0, soon: 0, later: 0 };
    for (const t of tasks) {
      if (t.done) continue;
      counts.all++;
      if (counts[t.bucket] !== undefined) counts[t.bucket]++;
    }
    return counts;
  });

  function countForList(listId) {
    if (listId === "all") return tasks.filter((t) => !t.done).length;
    if (listId === "inbox") return tasks.filter((t) => !t.done && !t.listId).length;
    return tasks.filter((t) => !t.done && t.listId === listId).length;
  }

  let activeListName = $derived(
    activeListId === "all" ? "All Lists" : (taskLists.find((l) => l.id === activeListId)?.name || "Tasks")
  );

  function handleQuickAdd(e) {
    if (e.key === "Enter" && quickInput.trim()) {
      const listId = (activeListId === "all" || activeListId === "inbox") ? null : activeListId;
      addTask({
        text: quickInput.trim(),
        bucket: activeBucket === "all" ? "inbox" : activeBucket,
        listId,
      });
      quickInput = "";
    }
  }

  function setBucket(taskId, bucket) {
    updateTask(taskId, { bucket });
  }

  function setEffort(taskId, effort) {
    updateTask(taskId, { effort: effort === tasks.find((t) => t.id === taskId)?.effort ? "" : effort });
  }


  function getListName(listId) {
    if (!listId) return null;
    return taskLists.find((l) => l.id === listId)?.name || null;
  }

  async function popOutTasks() {
    try {
      await invoke("open_task_window");
    } catch {
      window.open("/float", "_blank", "width=380,height=520");
    }
  }

  // List management
  function handleCreateList(e) {
    if (e.key === "Enter" && newListName.trim()) {
      addTaskList(newListName.trim());
      newListName = "";
      showNewList = false;
    }
    if (e.key === "Escape") { showNewList = false; newListName = ""; }
  }

  function startRenaming(list) {
    editingListId = list.id;
    editingName = list.name;
    contextMenuListId = null;
  }

  function finishRenaming() {
    if (editingListId && editingName.trim()) {
      renameTaskList(editingListId, editingName.trim());
    }
    editingListId = null;
    editingName = "";
  }

  function handleDeleteList(id) {
    if (activeListId === id) activeListId = "all";
    deleteTaskList(id);
    contextMenuListId = null;
  }

  function toggleContextMenu(e, listId) {
    e.preventDefault();
    e.stopPropagation();
    contextMenuListId = contextMenuListId === listId ? null : listId;
  }
</script>

<div class="flex flex-col h-full animate-fade-in">
  <!-- Header -->
  <div class="flex items-center px-7 pt-6 pb-2">
    <div>
      <h2 class="text-xl font-display text-text italic">Tasks</h2>
      <p class="text-[11px] text-text-tertiary mt-1">Extracted from transcripts or added manually</p>
    </div>
    <div class="flex-1"></div>
    <button
      class="flex items-center gap-1.5 btn-md rounded-lg text-text-secondary hover:bg-hover hover:text-text"
      onclick={popOutTasks}
      aria-label="Pop out task window"
    >
      <svg class="w-3.5 h-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
        <path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6M15 3h6v6M10 14L21 3" />
      </svg>
      Pop out
    </button>
  </div>

  <!-- Search -->
  <div class="px-7 pb-2">
    <div class="flex items-center gap-2 bg-bg-input border border-border rounded-lg px-3 py-1.5 focus-within:border-accent transition-colors">
      <svg class="w-3.5 h-3.5 text-text-tertiary flex-shrink-0" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
        <circle cx="11" cy="11" r="8" />
        <path d="M21 21l-4.35-4.35" stroke-linecap="round" />
      </svg>
      <input
        type="text"
        class="flex-1 bg-transparent text-[12px] text-text placeholder:text-text-tertiary focus:outline-none"
        placeholder="Search tasks..."
        bind:value={searchQuery}
        data-no-transition
      />
      {#if searchQuery}
        <button class="text-[10px] text-text-tertiary hover:text-text" onclick={() => searchQuery = ""}>Clear</button>
      {/if}
    </div>
  </div>

  <!-- Quick capture -->
  <div class="px-7 pb-3">
    <div class="flex items-center gap-2 bg-bg-input border border-border rounded-xl px-4 py-2.5 focus-within:border-accent transition-colors">
      <svg class="w-4 h-4 text-text-tertiary flex-shrink-0" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
        <path d="M12 5v14M5 12h14" stroke-linecap="round" />
      </svg>
      <input
        type="text"
        class="flex-1 bg-transparent text-[13px] text-text placeholder:text-text-tertiary focus:outline-none"
        placeholder="Add a task to {activeListName}{activeBucket !== 'all' ? ` (${activeBucket})` : ''}... (Enter to save)"
        bind:value={quickInput}
        onkeydown={handleQuickAdd}
      />
      {#if quickInput.trim()}
        <span class="text-[10px] text-text-tertiary px-1.5 py-0.5 rounded bg-bg-elevated border border-border-subtle">
          &rarr; {activeBucket === "all" ? "inbox" : activeBucket}
        </span>
      {/if}
    </div>
  </div>

  <!-- Bucket tabs + sort -->
  <div class="flex items-center gap-1 px-7 pb-3">
    <nav aria-label="Task filters">
    {#each buckets as bucket}
      <button
        class="flex items-center gap-1.5 btn-md rounded-lg transition-colors
          {activeBucket === bucket.id
            ? 'bg-nav-active text-text font-medium'
            : 'text-text-secondary hover:bg-hover hover:text-text'}"
        onclick={() => activeBucket = bucket.id}
      >
        <svg class="w-3.5 h-3.5 {activeBucket === bucket.id ? 'text-accent' : 'text-text-tertiary'}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
          <path d={bucket.icon} />
        </svg>
        {bucket.label}
        {#if bucketCounts[bucket.id] > 0}
          <span class="text-[10px] px-1.5 py-0.5 rounded-full bg-bg-elevated text-text-tertiary">
            {bucketCounts[bucket.id]}
          </span>
        {/if}
      </button>
    {/each}
    </nav>

    <div class="flex-1"></div>

    <!-- Sort dropdown -->
    <div class="relative">
      <button
        class="flex items-center gap-1 px-2 py-1.5 rounded-lg text-[11px] text-text-tertiary hover:text-text-secondary hover:bg-hover"
        onclick={() => showSortMenu = !showSortMenu}
        aria-label="Sort tasks"
      >
        <svg class="w-3.5 h-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <path d="M3 6h18M3 12h12M3 18h6" stroke-linecap="round" />
        </svg>
        {sortMode === "date" ? "" : sortMode === "quick-first" ? "Quick first" : "Deep first"}
      </button>
      {#if showSortMenu}
        <div class="absolute right-0 top-full mt-1 bg-bg-card border border-border rounded-lg shadow-lg py-1 z-20 animate-fade-in min-w-[120px]">
          {#each [["date", "By date"], ["quick-first", "Quick first"], ["deep-first", "Deep first"]] as [mode, label]}
            <button
              class="w-full text-left px-3 py-1 text-[11px] hover:bg-hover
                {sortMode === mode ? 'text-accent font-medium' : 'text-text-secondary hover:text-text'}"
              onclick={() => { sortMode = mode; showSortMenu = false; }}
            >{label}</button>
          {/each}
        </div>
      {/if}
    </div>
  </div>

  <!-- Main content: sidebar + tasks -->
  <div class="flex flex-1 min-h-0 px-7 pb-4 gap-3">
    <!-- List sidebar -->
    <div
      class="flex flex-col bg-bg-elevated rounded-2xl border border-border-subtle overflow-hidden transition-[width] duration-150
        {sidebarCollapsed ? 'w-[40px] min-w-[40px]' : 'w-[160px] min-w-[160px]'}"
    >
      <!-- Collapse toggle -->
      <button
        class="flex items-center justify-center h-[32px] text-text-tertiary hover:text-text-secondary border-b border-border-subtle"
        onclick={() => sidebarCollapsed = !sidebarCollapsed}
        aria-label={sidebarCollapsed ? "Expand list sidebar" : "Collapse list sidebar"}
      >
        <svg class="w-3 h-3 transition-transform {sidebarCollapsed ? 'rotate-180' : ''}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <path d="M15 18l-6-6 6-6" stroke-linecap="round" stroke-linejoin="round" />
        </svg>
      </button>

      <!-- List items -->
      <div class="flex-1 overflow-y-auto py-1">
        {#each taskLists as list (list.id)}
          {#if editingListId === list.id && !sidebarCollapsed}
            <div class="px-1.5 py-0.5">
              <input
                type="text"
                class="w-full bg-bg-input border border-accent rounded px-2 py-1 text-[10px] text-text focus:outline-none"
                bind:value={editingName}
                onkeydown={(e) => { if (e.key === "Enter") finishRenaming(); if (e.key === "Escape") { editingListId = null; } }}
                onblur={finishRenaming}
                data-no-transition
                autofocus
              />
            </div>
          {:else}
            <div class="relative">
              <button
                class="w-full flex items-center gap-1.5 px-2 py-1.5 text-left text-[11px]
                  {activeListId === list.id
                    ? 'border-l-2 border-accent text-text font-medium bg-accent/5'
                    : 'border-l-2 border-transparent text-text-secondary hover:bg-hover hover:text-text'}"
                onclick={() => { activeListId = list.id; contextMenuListId = null; }}
                ondblclick={() => { if (!list.builtIn && !sidebarCollapsed) startRenaming(list); }}
                oncontextmenu={(e) => { if (!list.builtIn) toggleContextMenu(e, list.id); }}
                title={sidebarCollapsed ? `${list.name} (${countForList(list.id)})` : ""}
              >
                {#if sidebarCollapsed}
                  <span class="text-[9px] px-1 py-0 rounded-full bg-bg-card text-text-tertiary min-w-[16px] text-center mx-auto">
                    {countForList(list.id)}
                  </span>
                {:else}
                  <span class="flex-1 truncate">{list.name}</span>
                  {#if countForList(list.id) > 0}
                    <span class="text-[9px] px-1 py-0 rounded-full bg-bg-card text-text-tertiary min-w-[16px] text-center">
                      {countForList(list.id)}
                    </span>
                  {/if}
                {/if}
              </button>

              <!-- Context menu -->
              {#if contextMenuListId === list.id && !sidebarCollapsed}
                <div class="absolute left-2 top-full mt-0.5 bg-bg-card border border-border rounded-lg shadow-lg py-1 z-20 animate-fade-in min-w-[100px]">
                  <button
                    class="w-full text-left px-3 py-1 text-[10px] text-text-secondary hover:bg-hover hover:text-text"
                    onclick={() => startRenaming(list)}
                  >Rename</button>
                  <div class="my-1 h-px bg-border-subtle"></div>
                  <button
                    class="w-full text-left px-3 py-1 text-[10px] text-danger hover:bg-hover"
                    onclick={() => handleDeleteList(list.id)}
                  >Delete</button>
                </div>
              {/if}
            </div>
          {/if}
        {/each}
      </div>

      <!-- New list -->
      {#if !sidebarCollapsed}
        <div class="px-2 py-2 border-t border-border-subtle">
          {#if showNewList}
            <input
              type="text"
              class="w-full bg-bg-input border border-border rounded px-2 py-1 text-[10px] text-text
                     placeholder:text-text-tertiary focus:outline-none focus:border-accent"
              placeholder="List name..."
              bind:value={newListName}
              onkeydown={handleCreateList}
              onblur={() => { showNewList = false; newListName = ""; }}
              data-no-transition
              autofocus
            />
          {:else}
            <button
              class="w-full text-left text-[10px] text-accent hover:text-accent-hover px-1"
              onclick={() => showNewList = true}
            >+ New list</button>
          {/if}
        </div>
      {/if}
    </div>

    <!-- Task list -->
    <div class="flex-1 overflow-y-auto min-h-0">
      {#if filteredTasks.length === 0}
        <div class="flex flex-col items-center justify-center h-full text-center py-12 opacity-60">
          <svg class="w-10 h-10 text-text-tertiary mb-3" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
            <path d="M9 11l3 3L22 4M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11" stroke-linecap="round" stroke-linejoin="round" />
          </svg>
          <p class="text-[13px] text-text-secondary">
            {searchQuery ? "No matching tasks"
              : activeListId !== "all" && activeBucket !== "all"
                ? `No ${activeBucket} tasks in ${activeListName}`
                : activeListId !== "all"
                  ? `No tasks in ${activeListName}`
                  : activeBucket === "all" ? "No tasks yet" : `Nothing in ${activeBucket}`}
          </p>
          <p class="text-[11px] text-text-tertiary mt-1">
            {searchQuery ? "Try a different search" : "Tasks are extracted from transcripts or added above"}
          </p>
        </div>
      {:else}
        <div class="flex flex-col gap-1">
          {#each filteredTasks as task (task.id)}
            <div class="group flex items-start gap-3 p-3 rounded-xl bg-bg-card border border-border-subtle hover:border-border transition-colors">
              <!-- Checkbox -->
              <button
                aria-label="Complete task"
                class="mt-0.5 w-[18px] h-[18px] rounded-md border-2 border-border-subtle hover:border-accent flex-shrink-0 flex items-center justify-center transition-colors"
                onclick={() => completeTask(task.id)}
              ></button>

              <!-- Content -->
              <div class="flex-1 min-w-0">
                <p class="text-[13px] text-text leading-relaxed">{task.text}</p>
                <div class="flex items-center gap-2 mt-1.5">
                  <!-- Bucket pills -->
                  {#each ["today", "soon", "later"] as b}
                    <button
                      class="text-[10px] px-2 py-0.5 rounded-full border transition-colors
                        {task.bucket === b
                          ? `${BUCKET_COLORS[b]} border-current bg-current/10 font-medium`
                          : 'text-text-tertiary border-transparent hover:border-border-subtle hover:text-text-secondary'}"
                      onclick={() => setBucket(task.id, b)}
                    >{b}</button>
                  {/each}
                  <span class="text-border-subtle">&middot;</span>
                  <!-- Effort pills -->
                  {#each ["quick", "medium", "deep"] as e}
                    <button
                      class="text-[10px] px-2 py-0.5 rounded-full border transition-colors
                        {task.effort === e
                          ? 'text-accent border-accent/30 bg-accent/10 font-medium'
                          : 'text-text-tertiary border-transparent hover:border-border-subtle hover:text-text-secondary'}"
                      onclick={() => setEffort(task.id, e)}
                    >{EFFORT_LABELS[e]}</button>
                  {/each}
                  <!-- Timestamp -->
                  {#if task.createdAt}
                    <span class="text-[10px] text-text-tertiary ml-auto">{formatTimestamp(task.createdAt)}</span>
                  {/if}
                </div>
                <!-- List name (only when viewing all lists) -->
                {#if activeListId === "all" && getListName(task.listId)}
                  <p class="text-[10px] text-text-tertiary italic mt-1">{getListName(task.listId)}</p>
                {/if}
              </div>

              <!-- Delete -->
              <button
                aria-label="Delete task"
                class="mt-0.5 text-text-tertiary hover:text-danger opacity-0 group-hover:opacity-100 transition-opacity"
                onclick={() => deleteTask(task.id)}
              >
                <svg class="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <path d="M18 6L6 18M6 6l12 12" stroke-linecap="round" />
                </svg>
              </button>
            </div>
          {/each}
        </div>
      {/if}

      <!-- Completed section -->
      {#if completedTasks.length > 0}
        <div class="mt-6">
          <button
            class="flex items-center gap-2 text-[12px] text-text-tertiary hover:text-text-secondary mb-2"
            onclick={() => showCompleted = !showCompleted}
          >
            <svg class="w-3 h-3 transition-transform {showCompleted ? 'rotate-90' : ''}" viewBox="0 0 24 24" fill="currentColor">
              <path d="M8 5l8 7-8 7z" />
            </svg>
            Completed ({completedTasks.length})
          </button>
          {#if showCompleted}
            <div class="flex flex-col gap-1 animate-fade-in">
              {#each completedTasks as task (task.id)}
                <div class="group flex items-start gap-3 px-4 py-2.5 rounded-xl opacity-50 hover:opacity-70 transition-opacity">
                  <button
                    aria-label="Uncomplete task"
                    class="mt-0.5 w-[18px] h-[18px] rounded-md border-2 border-accent bg-accent/20 flex-shrink-0 flex items-center justify-center"
                    onclick={() => uncompleteTask(task.id)}
                  >
                    <svg class="w-3 h-3 text-accent" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3">
                      <path d="M5 12l5 5L20 7" stroke-linecap="round" stroke-linejoin="round" />
                    </svg>
                  </button>
                  <div class="flex-1 min-w-0">
                    <p class="text-[13px] text-text-secondary line-through">{task.text}</p>
                    {#if task.doneAt}
                      <p class="text-[10px] text-text-tertiary mt-0.5">Completed {formatTimestamp(task.doneAt)}</p>
                    {/if}
                  </div>
                  <button
                    aria-label="Delete completed task"
                    class="mt-0.5 text-text-tertiary hover:text-danger opacity-0 group-hover:opacity-100 transition-opacity"
                    onclick={() => deleteTask(task.id)}
                  >
                    <svg class="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                      <path d="M18 6L6 18M6 6l12 12" stroke-linecap="round" />
                    </svg>
                  </button>
                </div>
              {/each}
            </div>
          {/if}
        </div>
      {/if}
    </div>
  </div>
</div>
