<template>
  <div class="min-h-full py-16 bg-gray-50">
    <div class="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">
      <div class="flex justify-between items-center mb-6">
        <div>
          <h1 class="text-4xl sm:text-5xl font-display font-bold text-gray-900 mb-2">
            Interne News
          </h1>
          <div class="w-24 h-1 bg-primary-600 mb-4" />
        </div>
        <button
          v-if="canWrite"
          @click="openAddModal"
          class="flex items-center px-4 py-2 bg-primary-600 hover:bg-primary-700 text-white font-semibold rounded-lg transition-colors"
        >
          <Plus :size="20" class="mr-2" />
          News erstellen
        </button>
      </div>

      <!-- Loading State -->
      <div v-if="isLoading" class="flex items-center justify-center py-12">
        <Loader2 :size="40" class="animate-spin text-primary-600" />
      </div>

      <!-- News List -->
      <div v-else class="space-y-6">
        <article
          v-for="item in news"
          :key="item.id"
          class="bg-white rounded-xl shadow-lg p-6 border border-gray-100"
        >
          <div class="flex justify-between items-start mb-4">
            <div class="flex-1">
              <h2 class="text-2xl font-display font-bold text-gray-900 mb-2">
                {{ item.title }}
              </h2>
              <div class="flex items-center text-sm text-gray-500 space-x-4">
                <div class="flex items-center">
                  <User :size="16" class="mr-1" />
                  {{ item.author }}
                </div>
                <div class="flex items-center">
                  <Calendar :size="16" class="mr-1" />
                  {{ formatDate(item.created) }}
                </div>
                <div v-if="item.updated !== item.created" class="flex items-center">
                  <Edit :size="16" class="mr-1" />
                  Aktualisiert: {{ formatDate(item.updated) }}
                </div>
              </div>
            </div>

            <div v-if="canWrite" class="flex space-x-2 ml-4">
              <button
                @click="openEditModal(item)"
                class="p-2 text-blue-600 hover:bg-blue-50 rounded-lg transition-colors"
                title="Bearbeiten"
              >
                <Edit :size="20" />
              </button>
              <button
                @click="confirmDelete(item)"
                class="p-2 text-red-600 hover:bg-red-50 rounded-lg transition-colors"
                title="Löschen"
              >
                <Trash2 :size="20" />
              </button>
            </div>
          </div>

          <div class="prose prose-lg max-w-none text-gray-700 whitespace-pre-wrap">
            {{ item.content }}
          </div>
        </article>

        <div v-if="news.length === 0" class="text-center py-12">
          <Newspaper :size="48" class="mx-auto text-gray-400 mb-4" />
          <p class="text-gray-500 text-lg">Noch keine internen News vorhanden.</p>
          <p v-if="canWrite" class="text-gray-400 text-sm mt-2">
            Klicken Sie auf "News erstellen", um die erste News zu veröffentlichen.
          </p>
        </div>
      </div>

      <!-- Add/Edit Modal -->
      <div
        v-if="showModal"
        class="fixed inset-0 z-50 bg-black/50 flex items-center justify-center p-4"
        @click.self="closeModal"
      >
        <div class="bg-white rounded-xl shadow-2xl max-w-3xl w-full p-8 max-h-[90vh] overflow-y-auto">
          <h2 class="text-2xl font-display font-bold text-gray-900 mb-6">
            {{ editingNews ? 'News bearbeiten' : 'News erstellen' }}
          </h2>

          <form @submit.prevent="saveNews" class="space-y-4">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">Titel *</label>
              <input
                v-model="formData.title"
                type="text"
                required
                class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500"
                :disabled="isSaving"
              />
            </div>

            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">Inhalt *</label>
              <textarea
                v-model="formData.content"
                rows="12"
                required
                class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500"
                :disabled="isSaving"
              />
            </div>

            <div v-if="errorMessage" class="flex items-center p-3 rounded-md bg-red-50 text-red-700 text-sm">
              <AlertCircle :size="20" class="mr-2" />
              {{ errorMessage }}
            </div>

            <div class="flex justify-end space-x-4 pt-4">
              <button
                type="button"
                @click="closeModal"
                class="px-6 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors"
                :disabled="isSaving"
              >
                Abbrechen
              </button>
              <button
                type="submit"
                class="px-6 py-2 bg-primary-600 hover:bg-primary-700 text-white font-semibold rounded-lg transition-colors flex items-center"
                :disabled="isSaving"
              >
                <Loader2 v-if="isSaving" :size="20" class="animate-spin mr-2" />
                <span>{{ isSaving ? 'Speichert...' : 'Speichern' }}</span>
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { Newspaper, Plus, User, Calendar, Edit, Trash2, Loader2, AlertCircle } from 'lucide-vue-next'

const authStore = useAuthStore()

const isLoading = ref(true)
const isSaving = ref(false)
const news = ref([])
const showModal = ref(false)
const editingNews = ref(null)
const errorMessage = ref('')

const formData = ref({
  title: '',
  content: ''
})

const canWrite = computed(() => {
  return authStore.role === 'admin' || authStore.role === 'vorstand'
})

const loadNews = async () => {
  isLoading.value = true
  try {
    const response = await $fetch('/api/news')
    news.value = response.news
  } catch (error) {
    console.error('Fehler beim Laden der News:', error)
  } finally {
    isLoading.value = false
  }
}

const openAddModal = () => {
  editingNews.value = null
  formData.value = {
    title: '',
    content: ''
  }
  showModal.value = true
  errorMessage.value = ''
}

const openEditModal = (item) => {
  editingNews.value = item
  formData.value = {
    title: item.title,
    content: item.content
  }
  showModal.value = true
  errorMessage.value = ''
}

const closeModal = () => {
  showModal.value = false
  editingNews.value = null
  errorMessage.value = ''
}

const saveNews = async () => {
  isSaving.value = true
  errorMessage.value = ''

  try {
    await $fetch('/api/news', {
      method: 'POST',
      body: {
        id: editingNews.value?.id,
        ...formData.value
      }
    })

    closeModal()
    await loadNews()
  } catch (error) {
    errorMessage.value = error.data?.message || 'Fehler beim Speichern der News.'
  } finally {
    isSaving.value = false
  }
}

const confirmDelete = async (item) => {
  if (!confirm(`Möchten Sie die News "${item.title}" wirklich löschen?`)) {
    return
  }

  try {
    await $fetch(`/api/news?id=${item.id}`, {
      method: 'DELETE'
    })

    await loadNews()
  } catch (error) {
    console.error('Delete error:', error)
    alert('Fehler beim Löschen der News: ' + (error.data?.message || error.message))
  }
}

const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('de-DE', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit'
  })
}

onMounted(() => {
  loadNews()
})

definePageMeta({
  middleware: 'auth',
  layout: 'default'
})

useHead({
  title: 'Interne News - Harheimer TC',
})
</script>

