<template>
  <div class="min-h-full py-16 bg-gray-50">
    <div class="max-w-7xl 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">
            Mitgliederliste
          </h1>
          <div class="w-24 h-1 bg-primary-600 mb-4" />
        </div>
        <button
          v-if="canEdit"
          @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"
        >
          <UserPlus :size="20" class="mr-2" />
          Mitglied hinzufügen
        </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>

      <!-- Members List -->
      <div v-else class="space-y-4">
        <div
          v-for="member in members"
          :key="member.id"
          class="bg-white p-6 rounded-xl shadow-lg border border-gray-100"
        >
          <div class="flex justify-between items-start">
            <div class="flex-1">
              <div class="flex items-center mb-2">
                <h3 class="text-xl font-semibold text-gray-900">{{ member.name }}</h3>
                <span
                  v-if="member.hasLogin"
                  class="ml-3 px-2 py-1 bg-green-100 text-green-800 text-xs font-medium rounded-full"
                >
                  Hat Login
                </span>
                <span
                  v-if="member.source === 'manual'"
                  class="ml-2 px-2 py-1 bg-blue-100 text-blue-800 text-xs font-medium rounded-full"
                >
                  Manuell
                </span>
                <span
                  v-else
                  class="ml-2 px-2 py-1 bg-purple-100 text-purple-800 text-xs font-medium rounded-full"
                >
                  Aus Login-System
                </span>
              </div>

              <div class="grid sm:grid-cols-2 gap-3 text-gray-600">
                <div v-if="member.email" class="flex items-center">
                  <Mail :size="16" class="mr-2 text-primary-600" />
                  <a :href="`mailto:${member.email}`" class="hover:text-primary-600">{{ member.email }}</a>
                </div>
                <div v-if="member.phone" class="flex items-center">
                  <Phone :size="16" class="mr-2 text-primary-600" />
                  <a :href="`tel:${member.phone}`" class="hover:text-primary-600">{{ member.phone }}</a>
                </div>
                <div v-if="member.address" class="flex items-start col-span-2">
                  <MapPin :size="16" class="mr-2 text-primary-600 mt-0.5" />
                  <span>{{ member.address }}</span>
                </div>
                <div v-if="member.notes" class="flex items-start col-span-2">
                  <FileText :size="16" class="mr-2 text-primary-600 mt-0.5" />
                  <span>{{ member.notes }}</span>
                </div>
                <div v-if="member.lastLogin" class="flex items-center col-span-2 text-sm text-gray-500">
                  <Clock :size="16" class="mr-2" />
                  Letzter Login: {{ formatDate(member.lastLogin) }}
                </div>
              </div>
            </div>

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

        <div v-if="members.length === 0" class="text-center py-12 text-gray-500">
          Keine Mitglieder gefunden.
        </div>
      </div>

      <!-- Edit/Add 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-2xl w-full p-8">
          <h2 class="text-2xl font-display font-bold text-gray-900 mb-6">
            {{ editingMember ? 'Mitglied bearbeiten' : 'Mitglied hinzufügen' }}
          </h2>

          <form @submit.prevent="saveMember" class="space-y-4">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">Name *</label>
              <input
                v-model="formData.name"
                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">E-Mail</label>
              <input
                v-model="formData.email"
                type="email"
                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">Telefon</label>
              <input
                v-model="formData.phone"
                type="tel"
                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">Adresse</label>
              <input
                v-model="formData.address"
                type="text"
                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">Notizen</label>
              <textarea
                v-model="formData.notes"
                rows="3"
                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 { Users, UserPlus, Mail, Phone, MapPin, FileText, Clock, Edit, Trash2, Loader2, AlertCircle } from 'lucide-vue-next'

const authStore = useAuthStore()

const isLoading = ref(true)
const isSaving = ref(false)
const members = ref([])
const showModal = ref(false)
const editingMember = ref(null)
const errorMessage = ref('')

const formData = ref({
  name: '',
  email: '',
  phone: '',
  address: '',
  notes: ''
})

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

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

const openAddModal = () => {
  editingMember.value = null
  formData.value = {
    name: '',
    email: '',
    phone: '',
    address: '',
    notes: ''
  }
  showModal.value = true
  errorMessage.value = ''
}

const openEditModal = (member) => {
  editingMember.value = member
  formData.value = {
    name: member.name,
    email: member.email || '',
    phone: member.phone || '',
    address: member.address || '',
    notes: member.notes || ''
  }
  showModal.value = true
  errorMessage.value = ''
}

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

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

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

    closeModal()
    await loadMembers()
  } catch (error) {
    errorMessage.value = error.data?.message || 'Fehler beim Speichern des Mitglieds.'
  } finally {
    isSaving.value = false
  }
}

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

  try {
    await $fetch('/api/members', {
      method: 'DELETE',
      body: { id: member.id }
    })

    await loadMembers()
  } catch (error) {
    alert('Fehler beim Löschen des Mitglieds.')
  }
}

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

onMounted(() => {
  loadMembers()
})

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

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

