<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { useRoute } from 'vue-router'
import draggable from 'vuedraggable'
import TodoItemRow from '../components/TodoItemRow.vue'
import { ApiError, apiRequest } from '../lib/api'
import { useItemsStore } from '../stores/items'
import type { TodoItem, TodoList } from '../types'

const route = useRoute()
const items = useItemsStore()

const listId = Number(route.params.id)
const list = ref<TodoList | null>(null)
const loadError = ref<string | null>(null)
const actionError = ref<string | null>(null)

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

const summary = computed(() => {
  const total = items.items.length
  if (total === 0) return 'No items yet.'
  return `${items.completedCount()} of ${total} done.`
})

onMounted(load)

async function load() {
  loadError.value = null
  try {
    const [{ list: fetched }] = await Promise.all([
      apiRequest<{ list: TodoList }>(`/lists/${listId}`, { auth: true }),
      items.load(listId),
    ])
    list.value = fetched
  } catch (e) {
    if (e instanceof ApiError && e.status === 404) {
      loadError.value = 'That list does not exist.'
    } else {
      loadError.value = e instanceof ApiError ? e.message : 'Could not load the list.'
    }
  }
}

/** 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 items.load(listId)
  }
}

function onReorder(event: { oldIndex?: number; newIndex?: number }) {
  if (event.oldIndex === event.newIndex) return
  void run(items.persistOrder())
}

async function onCreate() {
  submitting.value = true
  actionError.value = null
  try {
    await items.add(newText.value)
    newText.value = ''
  } catch (e) {
    actionError.value = e instanceof ApiError ? e.message : 'Could not add the item.'
  } finally {
    submitting.value = false
  }
}
</script>

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

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

    <template v-else-if="list">
      <h1>{{ list.title }}</h1>
      <p v-if="list.description" class="muted">{{ list.description }}</p>

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

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

      <draggable
        v-else-if="items.items.length"
        :list="items.items"
        item-key="id"
        tag="ul"
        class="items"
        handle=".item__handle"
        ghost-class="item--ghost"
        :animation="150"
        @end="onReorder"
      >
        <template #item="{ element }: { element: TodoItem }">
          <TodoItemRow
            :item="element"
            @toggle="(v) => run(items.setComplete(element, v))"
            @save-text="(v) => run(items.setText(element, v))"
            @delete="run(items.remove(element))"
          />
        </template>
      </draggable>

      <p v-else class="muted">No items yet &mdash; add one below.</p>

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