<script lang="ts" setup>
import { Link, useForm } from '@inertiajs/vue3'
import { watch } from 'vue'
import AdminLayout from '@/Layouts/AdminLayout.vue'
import type { ArticleRevision, KnowledgeBaseArticle, KnowledgeBaseCategory } from '@/types'

interface Props {
  article: KnowledgeBaseArticle
  categories: Pick<KnowledgeBaseCategory, 'id' | 'name'>[]
}

defineOptions({ layout: AdminLayout })

const props = defineProps<Props>()

const categoryOptions = props.categories.map(c => ({
  title: c.name,
  value: c.id,
}))

const statusOptions = [
  { title: 'Draft', value: 'draft' },
  { title: 'Published', value: 'published' },
  { title: 'Archived', value: 'archived' },
]

const form = useForm({
  title: props.article.title,
  slug: props.article.slug,
  category_id: props.article.category_id,
  content: props.article.content,
  excerpt: props.article.excerpt ?? '',
  status: props.article.status,
  is_featured: props.article.is_featured,
})

function generateSlug(title: string): string {
  return title
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, '-')
    .replace(/^-|-$/g, '')
}

let slugManuallyEdited = true

watch(() => form.title, (newTitle: string) => {
  if (!slugManuallyEdited) {
    form.slug = generateSlug(newTitle)
  }
})

function onSlugInput(): void {
  slugManuallyEdited = true
}

function formatDate(dateString: string): string {
  const date = new Date(dateString)
  return date.toLocaleDateString('en-US', {
    month: 'short',
    day: 'numeric',
    year: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
  })
}

function submit(): void {
  form.put(`/knowledge-base/articles/${props.article.id}`, {
    preserveScroll: true,
  })
}
</script>

<template>
  <div>
    <!-- Header -->
    <div class="d-flex align-center justify-space-between mb-6">
      <div>
        <div class="d-flex align-center gap-2 mb-1">
          <Link href="/knowledge-base/articles" class="text-decoration-none">
            <VBtn icon="tabler-arrow-left" variant="text" size="small" />
          </Link>
          <span class="text-h4 font-weight-bold">Edit Article</span>
        </div>
        <div class="text-body-2 text-medium-emphasis ms-10">
          Update "{{ article.title }}"
        </div>
      </div>
    </div>

    <form @submit.prevent="submit">
      <VRow>
        <!-- Article Content -->
        <VCol cols="12" lg="8">
          <VCard title="Article Details" class="mb-6">
            <VCardText>
              <VRow>
                <VCol cols="12">
                  <VTextField
                    v-model="form.title"
                    label="Title"
                    placeholder="e.g. How to Set Up Your VPS"
                    :error-messages="form.errors.title"
                  />
                </VCol>
                <VCol cols="12">
                  <VTextField
                    v-model="form.slug"
                    label="Slug"
                    placeholder="e.g. how-to-set-up-your-vps"
                    :error-messages="form.errors.slug"
                    @input="onSlugInput"
                  />
                </VCol>
                <VCol cols="12">
                  <VTextarea
                    v-model="form.excerpt"
                    label="Excerpt"
                    placeholder="Brief summary of the article"
                    rows="2"
                    :error-messages="form.errors.excerpt"
                  />
                </VCol>
                <VCol cols="12">
                  <VTextarea
                    v-model="form.content"
                    label="Content (Markdown)"
                    placeholder="Write your article content in Markdown format..."
                    rows="20"
                    style="font-family: 'JetBrains Mono', monospace; font-size: 0.875rem;"
                    :error-messages="form.errors.content"
                  />
                </VCol>
              </VRow>
            </VCardText>
          </VCard>
        </VCol>

        <!-- Sidebar -->
        <VCol cols="12" lg="4">
          <VCard title="Publishing" class="mb-6">
            <VCardText>
              <VSelect
                v-model="form.status"
                label="Status"
                :items="statusOptions"
                :error-messages="form.errors.status"
                class="mb-4"
              />
              <VSelect
                v-model="form.category_id"
                label="Category"
                :items="categoryOptions"
                placeholder="Select a category"
                :error-messages="form.errors.category_id"
                class="mb-4"
              />
              <VSwitch
                v-model="form.is_featured"
                label="Featured Article"
                color="primary"
                :error-messages="form.errors.is_featured"
              />
              <p class="text-body-2 text-medium-emphasis mt-1">
                Featured articles appear on the KB homepage.
              </p>
            </VCardText>
          </VCard>

          <!-- Article Stats -->
          <VCard title="Statistics" class="mb-6">
            <VCardText>
              <div class="d-flex justify-space-between align-center mb-3">
                <span class="text-body-2 text-medium-emphasis">Views</span>
                <span class="text-body-2 font-weight-medium">{{ article.view_count.toLocaleString() }}</span>
              </div>
              <div class="d-flex justify-space-between align-center mb-3">
                <span class="text-body-2 text-medium-emphasis">Helpful</span>
                <span class="text-body-2 font-weight-medium">{{ article.helpful_count }}</span>
              </div>
              <div class="d-flex justify-space-between align-center mb-3">
                <span class="text-body-2 text-medium-emphasis">Not Helpful</span>
                <span class="text-body-2 font-weight-medium">{{ article.not_helpful_count }}</span>
              </div>
              <div v-if="article.published_at" class="d-flex justify-space-between align-center">
                <span class="text-body-2 text-medium-emphasis">Published</span>
                <span class="text-body-2">{{ formatDate(article.published_at) }}</span>
              </div>
            </VCardText>
          </VCard>

          <!-- Revision History -->
          <VCard v-if="article.revisions && article.revisions.length > 0" title="Revision History" class="mb-6">
            <VCardText>
              <VList density="compact" class="pa-0">
                <VListItem
                  v-for="revision in article.revisions"
                  :key="revision.id"
                  class="px-0"
                >
                  <template #prepend>
                    <VIcon icon="tabler-history" size="18" class="me-2" />
                  </template>
                  <VListItemTitle class="text-body-2">
                    {{ revision.editor?.name ?? 'Unknown' }}
                  </VListItemTitle>
                  <VListItemSubtitle class="text-caption">
                    {{ formatDate(revision.created_at) }}
                  </VListItemSubtitle>
                </VListItem>
              </VList>
            </VCardText>
          </VCard>

          <!-- Actions -->
          <VCard>
            <VCardText>
              <VBtn
                type="submit"
                color="primary"
                block
                :loading="form.processing"
                :disabled="form.processing"
                prepend-icon="tabler-check"
                class="mb-3"
              >
                {{ form.status === 'published' ? 'Update & Publish' : 'Update Article' }}
              </VBtn>
              <Link href="/knowledge-base/articles" class="text-decoration-none">
                <VBtn
                  variant="outlined"
                  block
                >
                  Cancel
                </VBtn>
              </Link>
            </VCardText>
          </VCard>
        </VCol>
      </VRow>
    </form>
  </div>
</template>
