<template>
  <div class="settings-management">
    <div class="card">
      <div class="flex justify-between items-center mb-4">
        <div class="font-semibold text-xl">Systemeinstellungen</div>
      </div>
      
      <Card class="mb-4">
        <template #title>
          <div class="flex items-center gap-2">
            <i class="pi pi-shield text-primary"></i>
            <span>Sicherheitseinstellungen</span>
          </div>
        </template>
        
        <template #content>
          <form @submit.prevent="saveSettings" v-if="!loading">
            <!-- Password Minimum Length -->
            <div class="flex flex-col gap-4 mb-4">
              <div class="flex flex-col gap-2">
                <label for="passwordMinLength" class="font-medium">
                  <i class="pi pi-lock mr-2"></i>
                  Mindestlänge für Passwörter
                </label>
                <InputNumber
                  id="passwordMinLength"
                  v-model="settings.passwordMinLength"
                  :min="4"
                  :max="128"
                  :showButtons="true"
                  suffix=" Zeichen"
                  class="w-full md:w-1/2"
                />
                <small class="text-500">
                  Legt die Mindestanzahl an Zeichen fest, die ein Passwort haben muss (4-128 Zeichen).
                </small>
              </div>

              <!-- Allow Password Login -->
              <div class="flex flex-col gap-2">
                <div class="flex items-center gap-2">
                  <Checkbox
                    id="allowPasswordLogin"
                    v-model="settings.allowPasswordLogin"
                    :binary="true"
                  />
                  <label for="allowPasswordLogin" class="cursor-pointer font-medium">
                    <i class="pi pi-sign-in mr-2"></i>
                    Login mit E-Mail und Passwort erlauben
                  </label>
                </div>
                <small class="text-500">
                  Wenn deaktiviert, können sich Benutzer nur über alternative Methoden (z.B. OIDC) anmelden.
                </small>
                
                <Message v-if="!settings.allowPasswordLogin" severity="warn" class="mt-2" :closable="false">
                  <strong>Achtung:</strong> Stellen Sie sicher, dass mindestens eine alternative Login-Methode (z.B. OIDC) 
                  konfiguriert ist, bevor Sie den Passwort-Login deaktivieren.
                </Message>
              </div>
            </div>

            <!-- Action Buttons -->
            <div class="flex gap-2 mt-4">
              <Button
                type="submit"
                label="Einstellungen speichern"
                icon="pi pi-check"
                :loading="saving"
                severity="success"
              />
              <Button
                type="button"
                label="Zurücksetzen"
                icon="pi pi-refresh"
                @click="loadSettings"
                :disabled="saving"
                outlined
              />
            </div>
          </form>

          <div v-else class="text-center py-4">
            <ProgressSpinner />
          </div>
        </template>
      </Card>
    </div>

    <!-- Success Toast -->
    <Toast />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useToast } from 'primevue/usetoast'
import Card from 'primevue/card'
import InputNumber from 'primevue/inputnumber'
import Checkbox from 'primevue/checkbox'
import Button from 'primevue/button'
import Message from 'primevue/message'
import Toast from 'primevue/toast'
import ProgressSpinner from 'primevue/progressspinner'

const toast = useToast()
const loading = ref(false)
const saving = ref(false)

const settings = ref({
  passwordMinLength: 8,
  allowPasswordLogin: true
})

const loadSettings = async () => {
  loading.value = true
  try {
    const response = await fetch('/api/settings', {
      credentials: 'include'
    })
    
    if (!response.ok) {
      throw new Error('Failed to load settings')
    }
    
    const data = await response.json()
    settings.value = { ...data.settings }
  } catch (error) {
    console.error('Error loading settings:', error)
    toast.add({
      severity: 'error',
      summary: 'Fehler',
      detail: 'Einstellungen konnten nicht geladen werden',
      life: 3000
    })
  } finally {
    loading.value = false
  }
}

const saveSettings = async () => {
  // Validation
  if (settings.value.passwordMinLength < 4 || settings.value.passwordMinLength > 128) {
    toast.add({
      severity: 'error',
      summary: 'Validierungsfehler',
      detail: 'Passwort-Mindestlänge muss zwischen 4 und 128 Zeichen liegen',
      life: 3000
    })
    return
  }

  saving.value = true
  try {
    const response = await fetch('/api/settings', {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json'
      },
      credentials: 'include',
      body: JSON.stringify({
        settings: settings.value
      })
    })

    if (!response.ok) {
      const errorData = await response.json()
      throw new Error(errorData.error || 'Failed to save settings')
    }

    const data = await response.json()
    settings.value = { ...data.settings }

    toast.add({
      severity: 'success',
      summary: 'Erfolg',
      detail: 'Einstellungen wurden erfolgreich gespeichert',
      life: 3000
    })
  } catch (error) {
    console.error('Error saving settings:', error)
    toast.add({
      severity: 'error',
      summary: 'Fehler',
      detail: error.message || 'Einstellungen konnten nicht gespeichert werden',
      life: 3000
    })
  } finally {
    saving.value = false
  }
}

onMounted(() => {
  loadSettings()
})
</script>
