<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">
            News
          </h1>
          <div class="w-24 h-1 bg-primary-600 mb-4" />
        </div>
        <button
          v-if="canWrite"
          class="flex items-center px-4 py-2 bg-primary-600 hover:bg-primary-700 text-white font-semibold rounded-lg transition-colors"
          @click="openAddModal"
        >
          <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">
              <div class="flex items-center space-x-3 mb-2">
                <h2 class="text-2xl font-display font-bold text-gray-900">
                  {{ item.title }}
                </h2>
                <span
                  v-if="item.isPublic"
                  class="px-3 py-1 bg-blue-100 text-blue-800 text-xs font-semibold rounded-full flex items-center"
                >
                  <Globe
                    :size="14"
                    class="mr-1"
                  />
                  Öffentlich
                </span>
                <span
                  v-if="item.isHidden"
                  class="px-3 py-1 bg-yellow-100 text-yellow-800 text-xs font-semibold rounded-full flex items-center"
                >
                  <EyeOff
                    :size="14"
                    class="mr-1"
                  />
                  Ausgeblendet
                </span>
                <span
                  v-if="item.expiresAt && isExpired(item.expiresAt)"
                  class="px-3 py-1 bg-red-100 text-red-800 text-xs font-semibold rounded-full flex items-center"
                >
                  <Calendar
                    :size="14"
                    class="mr-1"
                  />
                  Abgelaufen
                </span>
              </div>
              <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
                class="p-2 text-blue-600 hover:bg-blue-50 rounded-lg transition-colors"
                title="Bearbeiten"
                @click="openEditModal(item)"
              >
                <Edit :size="20" />
              </button>
              <button
                class="p-2 text-red-600 hover:bg-red-50 rounded-lg transition-colors"
                title="Löschen"
                @click="confirmDelete(item)"
              >
                <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 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
            class="space-y-4"
            @submit.prevent="saveNews"
          >
            <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 class="flex items-center space-x-3 p-4 bg-blue-50 rounded-lg border border-blue-200">
              <input
                id="isPublic"
                v-model="formData.isPublic"
                type="checkbox"
                class="w-5 h-5 text-primary-600 border-gray-300 rounded focus:ring-primary-500"
                :disabled="isSaving"
              >
              <label
                for="isPublic"
                class="text-sm font-medium text-gray-900 cursor-pointer flex-1"
              >
                <div class="flex items-center">
                  <Globe
                    :size="18"
                    class="mr-2 text-blue-600"
                  />
                  <span>Öffentliche News (auf Startseite anzeigen)</span>
                </div>
                <p class="text-xs text-gray-600 mt-1 ml-6">
                  Wenn aktiviert, wird diese News auch für nicht angemeldete Besucher auf der Startseite sichtbar.
                </p>
              </label>
            </div>

            <div
              v-if="formData.isPublic"
              class="space-y-4"
            >
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Ablaufdatum (optional)</label>
                <input
                  v-model="formData.expiresAt"
                  type="datetime-local"
                  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"
                >
                <p class="text-xs text-gray-600 mt-1">
                  Nach diesem Datum wird die News automatisch nicht mehr auf der Startseite angezeigt.
                </p>
              </div>
              
              <div class="flex items-center space-x-3 p-4 bg-yellow-50 rounded-lg border border-yellow-200">
                <input
                  id="isHidden"
                  v-model="formData.isHidden"
                  type="checkbox"
                  class="w-5 h-5 text-primary-600 border-gray-300 rounded focus:ring-primary-500"
                  :disabled="isSaving"
                >
                <label
                  for="isHidden"
                  class="text-sm font-medium text-gray-900 cursor-pointer flex-1"
                >
                  <div class="flex items-center">
                    <EyeOff
                      :size="18"
                      class="mr-2 text-yellow-600"
                    />
                    <span>News ausblenden</span>
                  </div>
                  <p class="text-xs text-gray-600 mt-1 ml-6">
                    News wird nicht auf der Startseite angezeigt, bleibt aber im internen Bereich sichtbar.
                  </p>
                </label>
              </div>
            </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"
                class="px-6 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors"
                :disabled="isSaving"
                @click="closeModal"
              >
                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, Globe, EyeOff } 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: '',
  isPublic: false,
  expiresAt: '',
  isHidden: false
})

const canWrite = computed(() => {
  return authStore.hasAnyRole('admin', '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: '',
    isPublic: false,
    expiresAt: '',
    isHidden: false
  }
  showModal.value = true
  errorMessage.value = ''
}

const openEditModal = (item) => {
  editingNews.value = item
  formData.value = {
    title: item.title,
    content: item.content,
    isPublic: item.isPublic || false,
    expiresAt: item.expiresAt ? convertUTCToLocal(item.expiresAt) : '',
    isHidden: item.isHidden || false
  }
  showModal.value = true
  errorMessage.value = ''
}

// Convert UTC ISO string to datetime-local format
const convertUTCToLocal = (utcDateTime) => {
  // UTC ISO format: "2025-10-24T12:39:00.000Z"
  // Convert to local datetime-local format: "2025-10-24T12:39"
  const utcDate = new Date(utcDateTime)
  
  // Get local date components
  const year = utcDate.getFullYear()
  const month = String(utcDate.getMonth() + 1).padStart(2, '0')
  const day = String(utcDate.getDate()).padStart(2, '0')
  const hours = String(utcDate.getHours()).padStart(2, '0')
  const minutes = String(utcDate.getMinutes()).padStart(2, '0')
  
  return `${year}-${month}-${day}T${hours}:${minutes}`
}

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

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

  try {
    // Convert datetime-local to ISO string (local time to UTC)
    const dataToSend = {
      id: editingNews.value?.id,
      title: formData.value.title,
      content: formData.value.content,
      isPublic: formData.value.isPublic,
      isHidden: formData.value.isHidden,
      expiresAt: formData.value.expiresAt ? convertLocalToUTC(formData.value.expiresAt) : undefined
    }

    await $fetch('/api/news', {
      method: 'POST',
      body: dataToSend
    })

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

// Convert datetime-local to UTC ISO string
const convertLocalToUTC = (localDateTime) => {
  // datetime-local format: "2025-10-24T12:39"
  // Create Date object in local timezone
  const localDate = new Date(localDateTime)
  
  // Convert to UTC ISO string
  return localDate.toISOString()
}

const confirmDelete = async (item) => {
  window.showConfirmModal('News löschen', `Möchten Sie die News "${item.title}" wirklich löschen?`, async () => {
    if (!item.id) {
      window.showErrorModal('Fehler', 'News-ID fehlt!')
      return
    }

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

      await loadNews()
      window.showSuccessModal('Erfolg', 'News wurde erfolgreich gelöscht')
    } catch (error) {
      window.showErrorModal('Fehler', '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'
  })
}

const isExpired = (expiresAt) => {
  if (!expiresAt) return false
  return new Date(expiresAt) <= new Date()
}

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

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

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

