<template>
  <div class="min-h-full bg-gray-50">
    <!-- Fixed Header below navigation -->
    <div class="fixed top-20 left-0 right-0 z-40 bg-white border-b border-gray-200 shadow-sm">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-3 sm:py-4">
        <div class="flex items-center justify-between">
          <div>
            <h1 class="text-xl sm:text-4xl font-display font-bold text-gray-900">
              Einstellungen
            </h1>
            <div class="w-16 sm:w-24 h-1 bg-primary-600 mt-1 sm:mt-2" />
          </div>
          <div class="space-x-3">
            <button
              class="inline-flex items-center px-3 py-1.5 sm:px-4 sm:py-2 rounded-lg bg-primary-600 text-white hover:bg-primary-700 disabled:opacity-50 disabled:cursor-not-allowed text-sm sm:text-base"
              :disabled="isSaving"
              @click="saveConfig"
            >
              <Loader2
                v-if="isSaving"
                :size="16"
                class="animate-spin mr-2"
              />
              {{ isSaving ? 'Speichern...' : 'Speichern' }}
            </button>
          </div>
        </div>
      </div>
    </div>
    
    <!-- Content with top padding -->
    <div class="pt-28 sm:pt-32 pb-16">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-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"
                :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'
                ]"
                @click="activeTab = tab.id"
              >
                <component
                  :is="tab.icon"
                  :size="18"
                  class="inline mr-2"
                />
                {{ tab.label }}
              </button>
            </div>

            <!-- Tab Content -->
            <div class="p-8">
              <!-- Vereinsdaten -->
              <div v-if="activeTab === 'verein'">
                <h2 class="text-2xl font-display font-bold text-gray-900 mb-6">
                  Vereinsdaten
                </h2>
              
                <div class="space-y-6">
                  <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Vereinsname</label>
                    <input
                      v-model="config.verein.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 class="p-4 bg-blue-50 rounded-lg border border-blue-200">
                    <label class="flex items-center cursor-pointer">
                      <input
                        v-model="config.verein.useVorsitzenderAddress"
                        type="checkbox"
                        class="w-5 h-5 text-primary-600 border-gray-300 rounded focus:ring-primary-500"
                      >
                      <span class="ml-3 text-sm font-medium text-gray-900">
                        Adresse des 1. Vorsitzenden als Vereinsadresse verwenden
                      </span>
                    </label>
                    <p class="text-xs text-gray-600 mt-2 ml-8">
                      Wenn deaktiviert, können Sie unten eine separate Vereinsadresse angeben.
                    </p>
                  </div>

                  <div
                    v-if="!config.verein.useVorsitzenderAddress"
                    class="p-6 bg-gray-50 rounded-lg border border-gray-200"
                  >
                    <h3 class="text-lg font-semibold text-gray-900 mb-4">
                      Separate Vereinsadresse
                    </h3>
                    <div class="grid sm:grid-cols-2 gap-4">
                      <div class="sm:col-span-2">
                        <label class="block text-sm font-medium text-gray-700 mb-2">Straße & Hausnummer</label>
                        <input
                          v-model="config.verein.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.verein.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.verein.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>
                </div>
              </div>

              <!-- 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
                      class="flex items-center px-3 py-1 bg-primary-600 hover:bg-primary-700 text-white text-sm rounded-lg transition-colors"
                      @click="addTrainingTime"
                    >
                      <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>
                          <label class="block text-sm font-medium text-gray-700 mb-2">Gruppe</label>
                          <input
                            v-model="zeit.gruppe"
                            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 class="mt-4">
                        <label class="block text-sm font-medium text-gray-700 mb-2">Zusätzliche Information (optional)</label>
                        <div class="flex space-x-2">
                          <input
                            v-model="zeit.info"
                            type="text"
                            placeholder="z.B. 'Nur in der Schulzeit', 'Ab 10 Jahren', etc."
                            class="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500"
                          >
                          <button
                            class="px-3 py-2 text-red-600 hover:bg-red-50 rounded-lg transition-colors"
                            title="Löschen"
                            @click="removeTrainingTime(index)"
                          >
                            <Trash2 :size="18" />
                          </button>
                        </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
                    class="flex items-center px-4 py-2 bg-primary-600 hover:bg-primary-700 text-white font-semibold rounded-lg transition-colors"
                    @click="addTrainer"
                  >
                    <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">E-Mail</label>
                        <input
                          v-model="trainer.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>
                        <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
                            class="px-3 py-2 text-red-600 hover:bg-red-50 rounded-lg transition-colors"
                            title="Löschen"
                            @click="removeTrainer(index)"
                          >
                            <Trash2 :size="18" />
                          </button>
                        </div>
                      </div>
                      <div class="sm:col-span-2">
                        <ImageUpload
                          v-model="trainer.imageFilename"
                          label="Foto"
                        />
                      </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
                    class="flex items-center px-4 py-2 bg-primary-600 hover:bg-primary-700 text-white font-semibold rounded-lg transition-colors"
                    @click="addMembership"
                  >
                    <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
                            class="px-3 py-2 text-red-600 hover:bg-red-50 rounded-lg transition-colors"
                            title="Löschen"
                            @click="removeMembership(index)"
                          >
                            <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
                            class="px-3 py-2 text-red-600 hover:bg-red-50 rounded-lg transition-colors"
                            @click="membership.features.splice(fIndex, 1)"
                          >
                            <X :size="18" />
                          </button>
                        </div>
                        <button
                          class="flex items-center px-3 py-1 text-primary-600 hover:bg-primary-50 rounded-lg transition-colors text-sm"
                          @click="membership.features.push('')"
                        >
                          <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">
                      {{ formatPositionName(key) }}
                    </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 class="sm:col-span-2">
                        <label class="block text-sm font-medium text-gray-700 mb-2">Straße & Hausnummer</label>
                        <input
                          v-model="position.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="position.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="position.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>
                        <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 class="sm:col-span-2">
                        <ImageUpload
                          v-model="position.imageFilename"
                          label="Foto"
                        />
                      </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>
        </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 } from 'lucide-vue-next'

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

const config = ref({
  verein: { name: '', strasse: '', plz: '', ort: '', useVorsitzenderAddress: true },
  training: { ort: {}, zeiten: [] },
  trainer: [],
  mitgliedschaft: [],
  vorstand: {},
  website: {}
})

const tabs = [
  { id: 'verein', label: 'Verein', icon: Settings },
  { 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
  } catch {
    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.value
    })

    successMessage.value = 'Konfiguration erfolgreich gespeichert!'
    try { window.showSuccessModal && window.showSuccessModal('Erfolg', 'Konfiguration erfolgreich gespeichert!') } catch {
      // Modal nicht verfügbar, ignorieren
    }
    setTimeout(() => {
      successMessage.value = ''
    }, 3000)
  } catch (error) {
    errorMessage.value = error.data?.message || 'Fehler beim Speichern der Konfiguration.'
    try { window.showErrorModal && window.showErrorModal('Fehler', errorMessage.value) } catch {
      // Modal nicht verfügbar, ignorieren
    }
  } finally {
    isSaving.value = false
  }
}

const addTrainingTime = () => {
  // Finde die höchste vorhandene Gruppennummer
  let maxGruppeNummer = 0
  config.value.training.zeiten.forEach(zeit => {
    if (zeit.gruppe) {
      // Prüfe, ob das gruppe-Feld eine Nummer enthält (z.B. "Gruppe 1", "1", "Gruppe 3")
      const match = zeit.gruppe.match(/(\d+)/)
      if (match) {
        const nummer = parseInt(match[1], 10)
        if (nummer > maxGruppeNummer) {
          maxGruppeNummer = nummer
        }
      }
    }
  })
  
  // Setze die nächste Gruppennummer
  const naechsteGruppeNummer = maxGruppeNummer + 1
  
  config.value.training.zeiten.push({
    id: Date.now().toString(),
    tag: 'Montag',
    von: '19:00',
    bis: '22:00',
    gruppe: `Gruppe ${naechsteGruppeNummer}`,
    info: ''
  })
}

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

const addTrainer = () => {
  config.value.trainer.push({
    id: Date.now().toString(),
    name: '',
    lizenz: '',
    schwerpunkt: '',
    email: '',
    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)
}

const formatPositionName = (key) => {
  const names = {
    'vorsitzender': '1. Vorsitzender',
    'stellvertreter': 'Stellvertreter',
    'kassenwart': 'Kassenwart',
    'schriftfuehrer': 'Schriftführer',
    'sportwart': 'Sportwart',
    'jugendwart': 'Jugendwart'
  }
  return names[key] || key
}

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

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

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

