<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">
      <h1 class="text-4xl sm:text-5xl font-display font-bold text-gray-900 mb-6">
        Einstellungen
      </h1>
      <div class="w-24 h-1 bg-primary-600 mb-8" />

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

      <div v-else class="space-y-6">
        <!-- Tabs -->
        <div class="bg-white rounded-xl shadow-lg border border-gray-100 overflow-hidden">
          <div class="flex border-b border-gray-200">
            <button
              v-for="tab in tabs"
              :key="tab.id"
              @click="activeTab = tab.id"
              :class="[
                'flex-1 px-6 py-4 text-sm font-medium transition-colors',
                activeTab === tab.id
                  ? 'bg-primary-600 text-white'
                  : 'bg-gray-50 text-gray-700 hover:bg-gray-100'
              ]"
            >
              <component :is="tab.icon" :size="18" class="inline mr-2" />
              {{ tab.label }}
            </button>
          </div>

          <!-- Tab Content -->
          <div class="p-8">
            <!-- Trainingszeiten -->
            <div v-if="activeTab === 'training'">
              <h2 class="text-2xl font-display font-bold text-gray-900 mb-6">Trainingszeiten & Trainingsort</h2>
              
              <!-- Trainingsort -->
              <div class="mb-8 p-6 bg-gray-50 rounded-lg">
                <h3 class="text-lg font-semibold text-gray-900 mb-4">Trainingsort</h3>
                <div class="grid sm:grid-cols-2 gap-4">
                  <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Name</label>
                    <input
                      v-model="config.training.ort.name"
                      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"
                    />
                  </div>
                  <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Straße</label>
                    <input
                      v-model="config.training.ort.strasse"
                      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"
                    />
                  </div>
                  <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">PLZ</label>
                    <input
                      v-model="config.training.ort.plz"
                      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"
                    />
                  </div>
                  <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Ort</label>
                    <input
                      v-model="config.training.ort.ort"
                      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"
                    />
                  </div>
                </div>
              </div>

              <!-- Trainingszeiten -->
              <div>
                <div class="flex justify-between items-center mb-4">
                  <h3 class="text-lg font-semibold text-gray-900">Trainingszeiten</h3>
                  <button
                    @click="addTrainingTime"
                    class="flex items-center px-3 py-1 bg-primary-600 hover:bg-primary-700 text-white text-sm rounded-lg transition-colors"
                  >
                    <Plus :size="16" class="mr-1" />
                    Zeit hinzufügen
                  </button>
                </div>

                <div class="space-y-4">
                  <div
                    v-for="(zeit, index) in config.training.zeiten"
                    :key="zeit.id"
                    class="p-4 bg-gray-50 rounded-lg border border-gray-200"
                  >
                    <div class="grid sm:grid-cols-4 gap-4">
                      <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Tag</label>
                        <select
                          v-model="zeit.tag"
                          class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500"
                        >
                          <option>Montag</option>
                          <option>Dienstag</option>
                          <option>Mittwoch</option>
                          <option>Donnerstag</option>
                          <option>Freitag</option>
                          <option>Samstag</option>
                          <option>Sonntag</option>
                        </select>
                      </div>
                      <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Von</label>
                        <input
                          v-model="zeit.von"
                          type="time"
                          class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500"
                        />
                      </div>
                      <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Bis</label>
                        <input
                          v-model="zeit.bis"
                          type="time"
                          class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500"
                        />
                      </div>
                      <div class="sm:col-span-2">
                        <label class="block text-sm font-medium text-gray-700 mb-2">Gruppe</label>
                        <div class="flex space-x-2">
                          <input
                            v-model="zeit.gruppe"
                            type="text"
                            class="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500"
                          />
                          <button
                            @click="removeTrainingTime(index)"
                            class="px-3 py-2 text-red-600 hover:bg-red-50 rounded-lg transition-colors"
                            title="Löschen"
                          >
                            <Trash2 :size="18" />
                          </button>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- Trainer -->
            <div v-if="activeTab === 'trainer'">
              <div class="flex justify-between items-center mb-6">
                <h2 class="text-2xl font-display font-bold text-gray-900">Trainer</h2>
                <button
                  @click="addTrainer"
                  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" />
                  Trainer hinzufügen
                </button>
              </div>

              <div class="space-y-6">
                <div
                  v-for="(trainer, index) in config.trainer"
                  :key="trainer.id"
                  class="p-6 bg-gray-50 rounded-lg border border-gray-200"
                >
                  <div class="grid sm:grid-cols-2 gap-4">
                    <div>
                      <label class="block text-sm font-medium text-gray-700 mb-2">Name</label>
                      <input
                        v-model="trainer.name"
                        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"
                      />
                    </div>
                    <div>
                      <label class="block text-sm font-medium text-gray-700 mb-2">Lizenz</label>
                      <input
                        v-model="trainer.lizenz"
                        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"
                      />
                    </div>
                    <div>
                      <label class="block text-sm font-medium text-gray-700 mb-2">Schwerpunkt</label>
                      <input
                        v-model="trainer.schwerpunkt"
                        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"
                      />
                    </div>
                    <div>
                      <label class="block text-sm font-medium text-gray-700 mb-2">Zusatzinfo</label>
                      <div class="flex space-x-2">
                        <input
                          v-model="trainer.zusatz"
                          type="text"
                          class="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500"
                        />
                        <button
                          @click="removeTrainer(index)"
                          class="px-3 py-2 text-red-600 hover:bg-red-50 rounded-lg transition-colors"
                          title="Löschen"
                        >
                          <Trash2 :size="18" />
                        </button>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- Mitgliedschaft -->
            <div v-if="activeTab === 'mitgliedschaft'">
              <div class="flex justify-between items-center mb-6">
                <h2 class="text-2xl font-display font-bold text-gray-900">Mitgliedschaftsoptionen</h2>
                <button
                  @click="addMembership"
                  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" />
                  Option hinzufügen
                </button>
              </div>

              <div class="space-y-6">
                <div
                  v-for="(membership, index) in config.mitgliedschaft"
                  :key="membership.id"
                  class="p-6 bg-gray-50 rounded-lg border border-gray-200"
                >
                  <div class="grid sm:grid-cols-3 gap-4 mb-4">
                    <div>
                      <label class="block text-sm font-medium text-gray-700 mb-2">Typ</label>
                      <input
                        v-model="membership.typ"
                        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"
                      />
                    </div>
                    <div>
                      <label class="block text-sm font-medium text-gray-700 mb-2">Beschreibung</label>
                      <input
                        v-model="membership.beschreibung"
                        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"
                      />
                    </div>
                    <div>
                      <label class="block text-sm font-medium text-gray-700 mb-2">Preis (€/Jahr)</label>
                      <div class="flex space-x-2">
                        <input
                          v-model.number="membership.preis"
                          type="number"
                          class="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500"
                        />
                        <button
                          @click="removeMembership(index)"
                          class="px-3 py-2 text-red-600 hover:bg-red-50 rounded-lg transition-colors"
                          title="Löschen"
                        >
                          <Trash2 :size="18" />
                        </button>
                      </div>
                    </div>
                  </div>

                  <!-- Features -->
                  <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Leistungen</label>
                    <div class="space-y-2">
                      <div
                        v-for="(feature, fIndex) in membership.features"
                        :key="fIndex"
                        class="flex space-x-2"
                      >
                        <input
                          v-model="membership.features[fIndex]"
                          type="text"
                          class="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500"
                        />
                        <button
                          @click="membership.features.splice(fIndex, 1)"
                          class="px-3 py-2 text-red-600 hover:bg-red-50 rounded-lg transition-colors"
                        >
                          <X :size="18" />
                        </button>
                      </div>
                      <button
                        @click="membership.features.push('')"
                        class="flex items-center px-3 py-1 text-primary-600 hover:bg-primary-50 rounded-lg transition-colors text-sm"
                      >
                        <Plus :size="16" class="mr-1" />
                        Leistung hinzufügen
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- Vorstand -->
            <div v-if="activeTab === 'vorstand'">
              <h2 class="text-2xl font-display font-bold text-gray-900 mb-6">Vorstandsdaten</h2>
              
              <div class="space-y-8">
                <div
                  v-for="(position, key) in config.vorstand"
                  :key="key"
                  class="p-6 bg-gray-50 rounded-lg border border-gray-200"
                >
                  <h3 class="text-lg font-semibold text-gray-900 mb-4 capitalize">
                    {{ key.replace(/([A-Z])/g, ' $1').trim() }}
                  </h3>
                  <div class="grid sm:grid-cols-2 gap-4">
                    <div>
                      <label class="block text-sm font-medium text-gray-700 mb-2">Vorname</label>
                      <input
                        v-model="position.vorname"
                        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"
                      />
                    </div>
                    <div>
                      <label class="block text-sm font-medium text-gray-700 mb-2">Nachname</label>
                      <input
                        v-model="position.nachname"
                        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"
                      />
                    </div>
                    <div>
                      <label class="block text-sm font-medium text-gray-700 mb-2">Telefon</label>
                      <input
                        v-model="position.telefon"
                        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"
                      />
                    </div>
                    <div>
                      <label class="block text-sm font-medium text-gray-700 mb-2">E-Mail</label>
                      <input
                        v-model="position.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"
                      />
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- Error/Success Messages -->
        <div v-if="errorMessage" class="flex items-center p-4 rounded-lg bg-red-50 text-red-700">
          <AlertCircle :size="20" class="mr-2" />
          {{ errorMessage }}
        </div>

        <div v-if="successMessage" class="flex items-center p-4 rounded-lg bg-green-50 text-green-700">
          <Check :size="20" class="mr-2" />
          {{ successMessage }}
        </div>

        <!-- Save Button -->
        <div class="flex justify-end">
          <button
            @click="saveConfig"
            class="flex items-center px-8 py-3 bg-primary-600 hover:bg-primary-700 text-white font-semibold rounded-lg transition-colors shadow-lg"
            :disabled="isSaving"
          >
            <Loader2 v-if="isSaving" :size="20" class="animate-spin mr-2" />
            <Save v-else :size="20" class="mr-2" />
            <span>{{ isSaving ? 'Speichert...' : 'Änderungen speichern' }}</span>
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Settings, Calendar, Users as UsersIcon, CreditCard, Plus, Trash2, X, Loader2, AlertCircle, Check, Save } from 'lucide-vue-next'

const authStore = useAuthStore()

const isLoading = ref(true)
const isSaving = ref(false)
const errorMessage = ref('')
const successMessage = ref('')
const activeTab = ref('training')

const config = ref({
  training: { ort: {}, zeiten: [] },
  trainer: [],
  mitgliedschaft: [],
  vorstand: {},
  website: {}
})

const tabs = [
  { id: 'training', label: 'Training', icon: Calendar },
  { id: 'trainer', label: 'Trainer', icon: UsersIcon },
  { id: 'mitgliedschaft', label: 'Mitgliedschaft', icon: CreditCard },
  { id: 'vorstand', label: 'Vorstand', icon: UsersIcon }
]

const loadConfig = async () => {
  isLoading.value = true
  try {
    const response = await $fetch('/api/config')
    config.value = response.config
  } catch (error) {
    errorMessage.value = 'Fehler beim Laden der Konfiguration.'
  } finally {
    isLoading.value = false
  }
}

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

  try {
    await $fetch('/api/config', {
      method: 'PUT',
      body: { config: config.value }
    })

    successMessage.value = 'Konfiguration erfolgreich gespeichert!'
    setTimeout(() => {
      successMessage.value = ''
    }, 3000)
  } catch (error) {
    errorMessage.value = error.data?.message || 'Fehler beim Speichern der Konfiguration.'
  } finally {
    isSaving.value = false
  }
}

const addTrainingTime = () => {
  config.value.training.zeiten.push({
    id: Date.now().toString(),
    tag: 'Montag',
    von: '19:00',
    bis: '22:00',
    gruppe: ''
  })
}

const removeTrainingTime = (index) => {
  config.value.training.zeiten.splice(index, 1)
}

const addTrainer = () => {
  config.value.trainer.push({
    id: Date.now().toString(),
    name: '',
    lizenz: '',
    schwerpunkt: '',
    zusatz: ''
  })
}

const removeTrainer = (index) => {
  config.value.trainer.splice(index, 1)
}

const addMembership = () => {
  config.value.mitgliedschaft.push({
    id: Date.now().toString(),
    typ: '',
    beschreibung: '',
    preis: 0,
    features: []
  })
}

const removeMembership = (index) => {
  config.value.mitgliedschaft.splice(index, 1)
}

onMounted(() => {
  loadConfig()
})

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

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

