<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useAuthStore } from '@/stores/auth'
import { api } from '@/api'
import SecuritySettings from '@/components/SecuritySettings.vue'

const authStore = useAuthStore()

const currentPassword = ref('')
const newPassword = ref('')
const confirmPassword = ref('')
const loading = ref(false)
const message = ref('')
const error = ref('')
const showSecuritySettings = ref(false)

// App lock status
const lockMethod = ref<string | null>(null)

onMounted(() => {
  lockMethod.value = localStorage.getItem('lockMethod')
  // Store email for biometric setup
  if (authStore.user?.email) {
    localStorage.setItem('userEmail', authStore.user.email)
  }
})

const lockStatusText = computed(() => {
  if (!lockMethod.value || lockMethod.value === 'none') return 'Deaktiviert'
  if (lockMethod.value === 'biometric') return 'Fingerabdruck / Face ID'
  if (lockMethod.value === 'pin') return 'PIN-Code'
  return 'Unbekannt'
})

const lockStatusClass = computed(() => {
  if (!lockMethod.value || lockMethod.value === 'none') {
    return 'bg-red-100 text-red-700'
  }
  return 'bg-green-100 text-green-700'
})

async function changePassword() {
  if (newPassword.value !== confirmPassword.value) {
    error.value = 'Passwörter stimmen nicht überein'
    return
  }
  
  if (newPassword.value.length < 8) {
    error.value = 'Passwort muss mindestens 8 Zeichen haben'
    return
  }

  loading.value = true
  error.value = ''
  message.value = ''

  try {
    await api.post('/auth/change-password', {
      currentPassword: currentPassword.value,
      newPassword: newPassword.value
    })
    message.value = 'Passwort erfolgreich geändert'
    currentPassword.value = ''
    newPassword.value = ''
    confirmPassword.value = ''
  } catch (e) {
    error.value = e instanceof Error ? e.message : 'Fehler beim Ändern'
  } finally {
    loading.value = false
  }
}

function handleSecurityClose() {
  showSecuritySettings.value = false
  lockMethod.value = localStorage.getItem('lockMethod')
}
</script>

<template>
  <div class="space-y-6">
    <h1 class="text-2xl font-bold text-gray-900 dark:text-white">🔧 Einstellungen</h1>

    <!-- Profile -->
    <div class="card">
      <h2 class="text-lg font-semibold mb-4">👤 Profil</h2>
      <div class="grid grid-cols-2 gap-4">
        <div>
          <label class="block text-sm text-gray-500">Name</label>
          <p class="font-medium">{{ authStore.fullName }}</p>
        </div>
        <div>
          <label class="block text-sm text-gray-500">E-Mail</label>
          <p class="font-medium">{{ authStore.user?.email }}</p>
        </div>
        <div>
          <label class="block text-sm text-gray-500">Rolle</label>
          <p class="font-medium capitalize">{{ authStore.user?.role }}</p>
        </div>
      </div>
    </div>

    <!-- App Security -->
    <div class="card">
      <h2 class="text-lg font-semibold mb-4">🔐 App-Sicherheit</h2>
      <p class="text-gray-600 text-sm mb-4">
        Schütze deine App mit Fingerabdruck, Face ID oder PIN. 
        Bei jedem Öffnen der App musst du dich verifizieren.
      </p>
      
      <div class="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
        <div>
          <div class="font-medium">App-Sperre</div>
          <div :class="['inline-block px-2 py-1 rounded text-sm mt-1', lockStatusClass]">
            {{ lockStatusText }}
          </div>
        </div>
        <button 
          @click="showSecuritySettings = true"
          class="btn btn-primary"
        >
          Konfigurieren
        </button>
      </div>
    </div>

    <!-- Change Password -->
    <div class="card">
      <h2 class="text-lg font-semibold mb-4">🔑 Passwort ändern</h2>
      <form @submit.prevent="changePassword" class="space-y-4 max-w-md">
        <div>
          <label class="block text-sm font-medium mb-1">Aktuelles Passwort</label>
          <input v-model="currentPassword" type="password" required class="input" />
        </div>
        <div>
          <label class="block text-sm font-medium mb-1">Neues Passwort</label>
          <input v-model="newPassword" type="password" required class="input" />
        </div>
        <div>
          <label class="block text-sm font-medium mb-1">Passwort bestätigen</label>
          <input v-model="confirmPassword" type="password" required class="input" />
        </div>

        <div v-if="error" class="text-red-600 text-sm">{{ error }}</div>
        <div v-if="message" class="text-green-600 text-sm">{{ message }}</div>

        <button type="submit" :disabled="loading" class="btn btn-primary">
          {{ loading ? 'Speichern...' : 'Passwort ändern' }}
        </button>
      </form>
    </div>

    <!-- Security Settings Modal -->
    <SecuritySettings 
      v-if="showSecuritySettings" 
      @close="handleSecurityClose" 
    />
  </div>
</template>
