<template>
  <div class="min-h-screen bg-gray-50">
    <!-- Header -->
    <header class="bg-white shadow-sm border-b">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="flex justify-between items-center py-4">
          <div class="flex items-center">
            <img src="/logos/logo.png" alt="New Life Christian Church" class="h-10 w-auto mr-4" />
            <UButton
              @click="navigateTo('/')"
              variant="ghost"
              color="gray"
              icon="i-heroicons-arrow-left"
              class="mr-4"
            >
              Back to Sermons
            </UButton>
            <h1 class="text-2xl font-bold text-gray-900">Create New Sermon</h1>
          </div>
          <UButton
            @click="handleLogout"
            variant="outline"
            color="gray"
          >
            Logout
          </UButton>
        </div>
      </div>
    </header>

    <main class="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <UCard>
        <template #header>
          <h2 class="text-xl font-semibold">Sermon Details</h2>
        </template>

        <form @submit.prevent="handleSubmit" class="space-y-8">
          <!-- Basic Information -->
          <div class="space-y-4">
            <h3 class="text-lg font-medium text-gray-900">Basic Information</h3>

            <UFormGroup label="Sermon Title" name="title" required>
              <UInput
                v-model="form.title"
                placeholder="Enter sermon title"
                :disabled="loading"
              />
            </UFormGroup>

            <UFormGroup label="Sermon Date" name="date" required>
              <UInput
                v-model="form.date"
                type="date"
                :disabled="loading"
              />
            </UFormGroup>

            <div class="bg-blue-50 p-4 rounded-lg">
              <p class="text-sm text-blue-800">
                <strong>Generated URL:</strong>
                <span v-if="form.title && form.date" class="font-mono">
                  {{ generateSlug(form.title, form.date) }}
                </span>
                <span v-else class="text-blue-600">Enter title and date to see URL</span>
              </p>
            </div>
          </div>

          <!-- Bible References -->
          <div class="space-y-4">
            <div class="flex justify-between items-center">
              <h3 class="text-lg font-medium text-gray-900">Bible References</h3>
              <UButton
                @click="addBibleReference"
                variant="outline"
                size="sm"
                icon="i-heroicons-plus"
                :disabled="loading"
              >
                Add Reference
              </UButton>
            </div>

            <div class="space-y-2">
              <div
                v-for="(reference, index) in form.bibleReferences"
                :key="index"
                class="flex gap-2"
              >
                <UInput
                  v-model="form.bibleReferences[index]"
                  :placeholder="`Bible reference ${index + 1}`"
                  :disabled="loading"
                  class="flex-1"
                />
                <UButton
                  @click="removeBibleReference(index)"
                  variant="outline"
                  color="red"
                  size="sm"
                  icon="i-heroicons-minus"
                  :disabled="loading"
                />
              </div>
            </div>
          </div>

          <!-- Personal Application -->
          <div class="space-y-4">
            <h3 class="text-lg font-medium text-gray-900">Personal Application</h3>
            <UTextarea
              v-model="form.personalApplication"
              :rows="4"
              placeholder="Describe how this sermon applies to daily life..."
              :disabled="loading"
            />
          </div>

          <!-- Pastor's Challenge -->
          <div class="space-y-4">
            <h3 class="text-lg font-medium text-gray-900">Pastor's Challenge</h3>
            <UTextarea
              v-model="form.pastorChallenge"
              :rows="4"
              placeholder="What challenge does the pastor give to the congregation?"
              :disabled="loading"
            />
          </div>

          <!-- Submit -->
          <div class="flex justify-end space-x-4">
            <UButton
              type="button"
              variant="outline"
              :disabled="loading"
              @click="resetForm"
            >
              Reset
            </UButton>
            <UButton
              type="submit"
              variant="solid"
              color="primary"
              :loading="loading"
            >
              Create Sermon
            </UButton>
          </div>
        </form>
      </UCard>

      <!-- Success Message -->
      <div v-if="successMessage" class="mt-4 p-4 bg-green-50 border border-green-200 rounded-lg">
        <p class="text-green-800">{{ successMessage }}</p>
      </div>
    </main>
  </div>
</template>

<script setup lang="ts">
import { generateSlug } from '~/server/utils/auth'

const form = reactive({
  title: '',
  date: '',
  bibleReferences: [''],
  personalApplication: '',
  pastorChallenge: ''
})

const loading = ref(false)
const successMessage = ref('')

const generateSlug = (title: string, date: string) => {
  if (!title || !date) return ''

  const formattedTitle = title
    .toLowerCase()
    .replace(/[^a-z0-9\s-]/g, '')
    .replace(/\s+/g, '-')
    .replace(/-+/g, '-')
    .trim()

  const dateObj = new Date(date)
  const month = String(dateObj.getMonth() + 1).padStart(2, '0')
  const day = String(dateObj.getDate()).padStart(2, '0')
  const year = dateObj.getFullYear()

  return `sermon-${month}${day}${year}`
}

const addBibleReference = () => {
  form.bibleReferences.push('')
}

const removeBibleReference = (index: number) => {
  if (form.bibleReferences.length > 1) {
    form.bibleReferences.splice(index, 1)
  }
}

const resetForm = () => {
  form.title = ''
  form.date = ''
  form.bibleReferences = ['']
  form.personalApplication = ''
  form.pastorChallenge = ''
  successMessage.value = ''
}

const handleSubmit = async () => {
  loading.value = true
  successMessage.value = ''

  try {
    await $fetch('/api/sermons', {
      method: 'POST',
      body: {
        title: form.title,
        date: form.date,
        bibleReferences: form.bibleReferences.filter(ref => ref.trim() !== ''),
        personalApplication: form.personalApplication,
        pastorChallenge: form.pastorChallenge
      }
    })

    successMessage.value = 'Sermon created successfully!'
    resetForm()
  } catch (error: any) {
    console.error('Failed to create sermon:', error)
    // Error handling is done by Nuxt automatically
  } finally {
    loading.value = false
  }
}

const handleLogout = async () => {
  await $fetch('/api/auth/logout', { method: 'POST' })
  await navigateTo('/')
}
</script>
