<script setup lang="ts">
import { useRoute } from 'vue-router'
import { useQuery } from '@tanstack/vue-query'
import { computed, ref } from 'vue'
import { fetchTasks } from '@/api/tasks'
import LoadingSpinner from '@/components/common/LoadingSpinner.vue'
import type { TaskItem } from '@/api/types'

const route = useRoute()
const org = computed(() => route.params.org as string)

const statusFilter = ref<string>('')
const repoFilter = ref<string>('')

const { data, isLoading } = useQuery({
  queryKey: ['tasks', org, statusFilter, repoFilter],
  queryFn: () =>
    fetchTasks(org.value, {
      status: statusFilter.value || undefined,
      repo: repoFilter.value || undefined,
    }),
})

const tasks = computed(() => data.value?.tasks ?? [])
const total = computed(() => data.value?.total ?? 0)

// Derive unique repos and statuses for filter dropdowns
const repos = computed(() => {
  const set = new Set(tasks.value.map((t) => `${t.repo_owner}/${t.repo_name}`))
  return [...set].sort()
})

const statusOptions = ['todo', 'in_progress', 'blocked']

function statusBadgeClass(status: string) {
  const map: Record<string, string> = {
    todo: 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-300',
    in_progress: 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-300',
    blocked: 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-300',
    done: 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-300',
    draft: 'bg-slate-100 text-slate-600 dark:bg-slate-700 dark:text-slate-300',
  }
  return map[status] ?? 'bg-slate-100 text-slate-600'
}

function acPercent(task: TaskItem) {
  if (task.total_ac === 0) return 0
  return Math.round((task.done_ac / task.total_ac) * 100)
}
</script>

<template>
  <div>
    <div class="flex items-center justify-between mb-6">
      <div>
        <h1 class="text-2xl font-bold font-display text-slate-800 dark:text-slate-100">
          Tasks
        </h1>
        <p class="text-sm text-slate-500 mt-1">
          {{ total }} actionable work item{{ total !== 1 ? 's' : '' }} across specs
        </p>
      </div>
    </div>

    <!-- Filters -->
    <div class="flex gap-3 mb-6">
      <select
        v-model="statusFilter"
        class="rounded-md border border-border-light dark:border-slate-600 bg-surface-light dark:bg-slate-800 text-sm px-3 py-1.5 text-slate-700 dark:text-slate-200"
      >
        <option value="">All statuses</option>
        <option v-for="s in statusOptions" :key="s" :value="s">
          {{ s.replace('_', ' ') }}
        </option>
      </select>
      <select
        v-model="repoFilter"
        class="rounded-md border border-border-light dark:border-slate-600 bg-surface-light dark:bg-slate-800 text-sm px-3 py-1.5 text-slate-700 dark:text-slate-200"
      >
        <option value="">All repos</option>
        <option v-for="r in repos" :key="r" :value="r">{{ r }}</option>
      </select>
    </div>

    <LoadingSpinner v-if="isLoading" />

    <!-- Tasks table -->
    <div v-else-if="tasks.length > 0" class="bg-surface-light dark:bg-slate-800 rounded-lg border border-border-light dark:border-slate-700 overflow-hidden">
      <table class="w-full text-sm">
        <thead class="bg-surface-light-alt dark:bg-slate-900/50 border-b border-border-light dark:border-slate-700">
          <tr>
            <th class="text-left px-4 py-3 font-medium text-slate-500 dark:text-slate-400">Section</th>
            <th class="text-left px-4 py-3 font-medium text-slate-500 dark:text-slate-400">Spec</th>
            <th class="text-left px-4 py-3 font-medium text-slate-500 dark:text-slate-400">Status</th>
            <th class="text-left px-4 py-3 font-medium text-slate-500 dark:text-slate-400">ACs</th>
            <th class="text-left px-4 py-3 font-medium text-slate-500 dark:text-slate-400">Ticket</th>
          </tr>
        </thead>
        <tbody class="divide-y divide-border-light/60 dark:divide-slate-700/50">
          <tr
            v-for="task in tasks"
            :key="`${task.repo_owner}/${task.repo_name}/${task.section_id}`"
            class="hover:bg-surface-light-alt dark:hover:bg-slate-700/30 transition-colors"
          >
            <td class="px-4 py-3">
              <router-link
                :to="`/app/${org}/specs/${task.repo_owner}/${task.repo_name}/${task.spec_file_path}`"
                class="font-medium text-slate-800 dark:text-slate-100 hover:text-accent-600 dark:hover:text-accent-400"
              >
                <span v-if="task.section_number" class="text-slate-400 mr-1">{{ task.section_number }}.</span>
                {{ task.title }}
              </router-link>
            </td>
            <td class="px-4 py-3 text-slate-500 dark:text-slate-400">
              {{ task.spec_title }}
              <span class="text-xs text-slate-400 ml-1">{{ task.repo_owner }}/{{ task.repo_name }}</span>
            </td>
            <td class="px-4 py-3">
              <span
                class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium"
                :class="statusBadgeClass(task.status)"
              >
                {{ task.status.replace('_', ' ') }}
              </span>
              <span v-if="task.blocked_by" class="text-xs text-red-500 ml-1">
                ({{ task.blocked_by }})
              </span>
            </td>
            <td class="px-4 py-3">
              <div class="flex items-center gap-2">
                <div class="w-16 h-1.5 bg-border-light dark:bg-slate-600 rounded-full overflow-hidden">
                  <div
                    class="h-full rounded-full"
                    :class="acPercent(task) === 100 ? 'bg-green-500' : 'bg-accent-500'"
                    :style="{ width: `${acPercent(task)}%` }"
                  ></div>
                </div>
                <span class="text-xs text-slate-500 dark:text-slate-400">
                  {{ task.done_ac }}/{{ task.total_ac }}
                </span>
              </div>
            </td>
            <td class="px-4 py-3 text-xs text-slate-400">
              <span v-if="task.ticket_id">
                {{ task.ticket_system }}#{{ task.ticket_id }}
              </span>
              <span v-else class="text-slate-300 dark:text-slate-600">&mdash;</span>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- Empty state -->
    <div v-else class="text-center py-12 text-slate-500">
      <p class="text-lg font-medium">No tasks found</p>
      <p class="text-sm mt-1">All spec sections are done, or no specs have been created yet.</p>
    </div>
  </div>
</template>
