<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { usePublicationStore } from '../stores/publicationStore'

const router = useRouter()
const store = usePublicationStore()

const title = ref('')
const author = ref('')
const osdbPubId = ref('')
const saving = ref(false)
const serverError = ref<string | null>(null)

async function submit() {
  serverError.value = null
  saving.value = true
  try {
    const pub = await store.create({
      title: title.value,
      author: author.value || null,
      osdb_pub_id: osdbPubId.value,
    })
    router.push(`/publications/${pub.id}`)
  } catch (e) {
    serverError.value = e instanceof Error ? e.message : 'Fehler beim Speichern'
  } finally {
    saving.value = false
  }
}
</script>

<template>
  <div class="mx-auto max-w-lg p-6">
    <h1 class="mb-4 text-2xl font-bold">Neue Publikation</h1>

    <div v-if="serverError" class="mb-4 rounded bg-red-50 p-3 text-red-700">{{ serverError }}</div>

    <form class="space-y-4" @submit.prevent="submit">
      <div>
        <label class="mb-1 block text-sm font-medium">Titel *</label>
        <input v-model="title" required class="w-full rounded border px-3 py-2" />
      </div>
      <div>
        <label class="mb-1 block text-sm font-medium">Autor</label>
        <input v-model="author" class="w-full rounded border px-3 py-2" />
      </div>
      <div>
        <label class="mb-1 block text-sm font-medium">OSDB Kürzel *</label>
        <input v-model="osdbPubId" required class="w-full rounded border px-3 py-2 font-mono" />
      </div>
      <div class="flex gap-2">
        <button
          type="submit"
          :disabled="saving"
          class="rounded bg-blue-600 px-4 py-2 text-white hover:bg-blue-700 disabled:opacity-50"
        >
          {{ saving ? 'Speichern…' : 'Anlegen' }}
        </button>
        <router-link to="/publications" class="rounded border px-4 py-2 hover:bg-gray-50">
          Abbrechen
        </router-link>
      </div>
    </form>
  </div>
</template>
