<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import draggable from 'vuedraggable'
import CardRow from '../components/CardRow.vue'
import KanbanCard from '../components/KanbanCard.vue'
import { ApiError, apiRequest } from '../lib/api'
import { useCardsStore } from '../stores/cards'
import { useProjectsStore } from '../stores/projects'
import type { Card, CardStatus, Project } from '../types'

const route = useRoute()
const router = useRouter()
const cards = useCardsStore()
const projects = useProjectsStore()

const projectId = Number(route.params.id)
const project = ref<Project | null>(null)
const statuses = ref<CardStatus[]>([])
const loadError = ref<string | null>(null)
const actionError = ref<string | null>(null)

const tabs = [
  { key: 'all', label: 'All tasks' },
  { key: 'kanban', label: 'Kanban' },
] as const
const activeTab = ref<(typeof tabs)[number]['key']>('all')

const titleDraft = ref('')
const descriptionDraft = ref('')

const menuOpen = ref(false)
const confirmingDelete = ref(false)
const deleting = ref(false)
const deleteError = ref<string | null>(null)
const cancelButton = ref<HTMLButtonElement>()

const newText = ref('')
const submitting = ref(false)

const newInboxText = ref('')
const addingToInbox = ref(false)

const summary = computed(() => {
  const total = cards.cards.length
  if (total === 0) return 'No cards yet.'
  return `${total} card${total === 1 ? '' : 's'}.`
})

// The "all tasks" list has no manual order — sort by name, case-insensitively.
const sortedCards = computed(() =>
  [...cards.cards].sort((a, b) => a.text.localeCompare(b.text, undefined, { sensitivity: 'base' })),
)

// --- Kanban board --------------------------------------------------------
interface Column {
  key: string
  title: string
  statusId: number | null
  cards: Card[]
}
type ColumnChange = {
  added?: { element: Card; newIndex: number }
  removed?: { element: Card; oldIndex: number }
  moved?: { element: Card; oldIndex: number; newIndex: number }
}

const board = ref<Column[]>([])

function buildColumns(): Column[] {
  const defs: Omit<Column, 'cards'>[] = [
    { key: 'inbox', title: 'Inbox', statusId: null },
    ...statuses.value.map((s) => ({ key: `status-${s.id}`, title: s.name, statusId: s.id })),
  ]
  return defs.map((def) => ({
    ...def,
    cards: cards.cards.filter((card) => card.status_id === def.statusId),
  }))
}

function rebuildBoard() {
  board.value = buildColumns()
}

// Re-derive the columns whenever the underlying cards or the status set change
// (e.g. after a move is persisted, or a failed move is rolled back).
watch([() => cards.cards, statuses], rebuildBoard, { deep: true })

function onColumnChange(change: ColumnChange, column: Column) {
  // `added` (card dragged in from another column) or `moved` (reordered within
  // this one): persist this column's new id order. The source column, if any,
  // is re-packed server-side. `removed` needs no action here.
  if (change.added || change.moved) {
    void run(cards.reorderColumn(column.statusId, column.cards.map((c) => c.id)))
  }
}

watch(project, (value) => {
  if (value) {
    titleDraft.value = value.title
    descriptionDraft.value = value.description
  }
})

watch(confirmingDelete, async (open) => {
  if (open) {
    await nextTick()
    cancelButton.value?.focus()
  }
})

onMounted(() => {
  void load()
  window.addEventListener('keydown', onKeydown)
})
onBeforeUnmount(() => window.removeEventListener('keydown', onKeydown))

function onKeydown(event: KeyboardEvent) {
  if (event.key !== 'Escape') return
  if (confirmingDelete.value) confirmingDelete.value = false
  else if (menuOpen.value) menuOpen.value = false
}

async function load() {
  loadError.value = null
  try {
    const [{ project: fetched }, { statuses: fetchedStatuses }] = await Promise.all([
      apiRequest<{ project: Project }>(`/projects/${projectId}`, { auth: true }),
      apiRequest<{ statuses: CardStatus[] }>(`/projects/${projectId}/statuses`, { auth: true }),
      cards.load(projectId),
    ])
    project.value = fetched
    statuses.value = fetchedStatuses
    rebuildBoard()
  } catch (e) {
    if (e instanceof ApiError && e.status === 404) {
      loadError.value = 'That project does not exist.'
    } else {
      loadError.value = e instanceof ApiError ? e.message : 'Could not load the project.'
    }
  }
}

async function patchProject(fields: { title?: string; description?: string }) {
  actionError.value = null
  try {
    const { project: updated } = await apiRequest<{ project: Project }>(`/projects/${projectId}`, {
      method: 'PATCH',
      auth: true,
      body: fields,
    })
    project.value = updated
  } catch (e) {
    actionError.value = e instanceof ApiError ? e.message : 'Could not save the change.'
    if (project.value) {
      titleDraft.value = project.value.title
      descriptionDraft.value = project.value.description
    }
  }
}

function saveTitle() {
  if (!project.value) return
  const next = titleDraft.value.trim()
  if (next === '') {
    titleDraft.value = project.value.title // title is required
    return
  }
  if (next !== project.value.title) void patchProject({ title: next })
}

function saveDescription() {
  if (!project.value) return
  const next = descriptionDraft.value.trim()
  if (next !== project.value.description) void patchProject({ description: next })
}

function askDelete() {
  menuOpen.value = false
  deleteError.value = null
  confirmingDelete.value = true
}

async function confirmDelete() {
  deleting.value = true
  deleteError.value = null
  try {
    await apiRequest(`/projects/${projectId}`, { method: 'DELETE', auth: true })
    projects.reset()
    cards.reset()
    await router.push('/')
  } catch (e) {
    deleteError.value = e instanceof ApiError ? e.message : 'Could not delete the project.'
    deleting.value = false
  }
}

/** Run a store mutation, surfacing failures and resyncing from the server. */
async function run(op: Promise<unknown>) {
  actionError.value = null
  try {
    await op
  } catch (e) {
    actionError.value = e instanceof ApiError ? e.message : 'Something went wrong.'
    await cards.load(projectId)
  }
}

async function onCreate() {
  submitting.value = true
  actionError.value = null
  try {
    await cards.add(newText.value)
    newText.value = ''
  } catch (e) {
    actionError.value = e instanceof ApiError ? e.message : 'Could not add the card.'
  } finally {
    submitting.value = false
  }
}

// New cards always land in the inbox (no status), so this just adds one.
async function onCreateInbox() {
  if (!newInboxText.value.trim()) return
  addingToInbox.value = true
  actionError.value = null
  try {
    await cards.add(newInboxText.value)
    newInboxText.value = ''
  } catch (e) {
    actionError.value = e instanceof ApiError ? e.message : 'Could not add the card.'
  } finally {
    addingToInbox.value = false
  }
}
</script>

<template>
  <section class="card project">
    <p><RouterLink to="/">&larr; All projects</RouterLink></p>

    <p v-if="loadError" class="form-error">{{ loadError }}</p>

    <template v-else-if="project">
      <div class="project__chrome">
        <div class="project-head">
          <h1 class="project-head__title">
            <input
              v-model="titleDraft"
              type="text"
              maxlength="255"
              aria-label="Project title"
              @blur="saveTitle"
              @keyup.enter="($event.target as HTMLInputElement).blur()"
            />
          </h1>

          <div class="menu">
            <button
              type="button"
              class="menu__toggle"
              aria-haspopup="true"
              :aria-expanded="menuOpen"
              @click="menuOpen = !menuOpen"
            >
              Manage &#9662;
            </button>

            <template v-if="menuOpen">
              <div class="menu__backdrop" @click="menuOpen = false" />
              <ul class="menu__list" role="menu">
                <li role="none">
                  <button
                    type="button"
                    role="menuitem"
                    class="menu__item menu__item--danger"
                    @click="askDelete"
                  >
                    Delete project
                  </button>
                </li>
              </ul>
            </template>
          </div>
        </div>

        <textarea
          v-model="descriptionDraft"
          class="project-head__desc"
          rows="2"
          maxlength="2000"
          placeholder="Add a description"
          aria-label="Project description"
          @blur="saveDescription"
        />
      </div>

      <p v-if="actionError" class="form-error">{{ actionError }}</p>

      <div class="tabs" role="tablist">
        <button
          v-for="tab in tabs"
          :key="tab.key"
          type="button"
          role="tab"
          :aria-selected="activeTab === tab.key"
          class="tabs__tab"
          :class="{ 'tabs__tab--active': activeTab === tab.key }"
          @click="activeTab = tab.key"
        >
          {{ tab.label }}
        </button>
      </div>

      <!-- Tab: All tasks -->
      <div v-show="activeTab === 'all'" class="tabs__panel tabs__panel--narrow" role="tabpanel">
        <p class="muted">{{ summary }}</p>

        <p v-if="cards.loading && !cards.loaded" class="muted">Loading…</p>

        <ul v-else-if="sortedCards.length" class="cards">
          <CardRow
            v-for="card in sortedCards"
            :key="card.id"
            :card="card"
            @save-text="(v) => run(cards.setText(card, v))"
            @delete="run(cards.remove(card))"
          />
        </ul>

        <form class="form form--new-card" @submit.prevent="onCreate">
          <label>
            <span>New card</span>
            <input v-model="newText" type="text" maxlength="1000" required />
          </label>
          <button type="submit" :disabled="submitting">
            {{ submitting ? 'Adding…' : 'Add card' }}
          </button>
        </form>
      </div>

      <!-- Tab: Kanban -->
      <div v-show="activeTab === 'kanban'" class="tabs__panel" role="tabpanel">
        <p v-if="cards.loading && !cards.loaded" class="muted">Loading…</p>

        <div v-else class="kanban">
          <section v-for="column in board" :key="column.key" class="kanban__col">
            <header class="kanban__head">
              <span class="kanban__title">{{ column.title }}</span>
              <span class="kanban__count">{{ column.cards.length }}</span>
            </header>

            <draggable
              :list="column.cards"
              :group="{ name: 'kanban' }"
              item-key="id"
              class="kanban__cards"
              ghost-class="kanban-card--ghost"
              :animation="150"
              @change="(e: ColumnChange) => onColumnChange(e, column)"
            >
              <template #item="{ element }: { element: Card }">
                <KanbanCard :card="element" />
              </template>
            </draggable>

            <form
              v-if="column.statusId === null"
              class="kanban__new"
              @submit.prevent="onCreateInbox"
            >
              <input
                v-model="newInboxText"
                type="text"
                maxlength="1000"
                required
                placeholder="New card"
                aria-label="New card"
              />
              <button type="submit" :disabled="addingToInbox">Add</button>
            </form>
          </section>
        </div>
      </div>
    </template>
  </section>

  <div
    v-if="confirmingDelete"
    class="modal"
    role="dialog"
    aria-modal="true"
    aria-labelledby="confirm-delete-title"
  >
    <div class="modal__backdrop" @click="confirmingDelete = false" />
    <div class="modal__dialog">
      <h2 id="confirm-delete-title">Delete this project?</h2>
      <p class="muted">
        &ldquo;{{ project?.title }}&rdquo; and its {{ cards.cards.length }}
        card{{ cards.cards.length === 1 ? '' : 's' }} will be permanently deleted.
      </p>
      <p v-if="deleteError" class="form-error">{{ deleteError }}</p>
      <div class="modal__actions">
        <button
          ref="cancelButton"
          type="button"
          class="btn-secondary"
          :disabled="deleting"
          @click="confirmingDelete = false"
        >
          Cancel
        </button>
        <button type="button" class="btn-danger" :disabled="deleting" @click="confirmDelete">
          {{ deleting ? 'Deleting…' : 'Delete project' }}
        </button>
      </div>
    </div>
  </div>
</template>
