<template>
  <div class="settings-management">
    <h1>Systemeinstellungen</h1>
    
    <div class="card">
      <div class="card-header">
        <h2>Sicherheitseinstellungen</h2>
      </div>
      
      <div class="card-body">
        <form @submit.prevent="saveSettings" v-if="!loading">
          <!-- Password Minimum Length -->
          <div class="form-group">
            <label for="passwordMinLength">
              <i class="pi pi-lock"></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"
            />
            <small class="form-text">
              Legt die Mindestanzahl an Zeichen fest, die ein Passwort haben muss (4-128 Zeichen).
            </small>
          </div>

          <!-- Allow Password Login -->
          <div class="form-group">
            <div class="flex align-items-center">
              <Checkbox
                id="allowPasswordLogin"
                v-model="settings.allowPasswordLogin"
                :binary="true"
              />
              <label for="allowPasswordLogin" class="ml-2 cursor-pointer">
                <i class="pi pi-sign-in"></i>
                Login mit E-Mail und Passwort erlauben
              </label>
            </div>
            <small class="form-text">
              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>

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

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

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

<script setup>
import { ref, onMounted } from 'vue'
import { useToast } from 'primevue/usetoast'
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>

<style scoped>
.settings-management {
  max-width: 900px;
  margin: 0 auto;
  padding: 2rem;
}

h1 {
  color: #333;
  margin-bottom: 2rem;
  font-size: 2rem;
}

.card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.card-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 1.5rem;
}

.card-header h2 {
  margin: 0;
  font-size: 1.5rem;
  font-weight: 500;
}

.card-body {
  padding: 2rem;
}

.form-group {
  margin-bottom: 1.5rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: 500;
  color: #333;
}

.form-group label i {
  margin-right: 0.5rem;
  color: #667eea;
}

.form-text {
  display: block;
  margin-top: 0.5rem;
  color: #6c757d;
  font-size: 0.875rem;
}

.cursor-pointer {
  cursor: pointer;
}

@media (max-width: 768px) {
  .settings-management {
    padding: 1rem;
  }
  
  h1 {
    font-size: 1.5rem;
  }
  
  .card-body {
    padding: 1rem;
  }
}
</style>
