<template>
  <div class="oauth-callback">
    <div v-if="pendingToken" class="link-container">
      <h2>Google-Konto verknüpfen</h2>
      <p>
        Für {{ googleEmail }} existiert bereits ein Account. Melden Sie sich mit dem bestehenden Account an,
        um ihn mit Google zu verknüpfen.
      </p>
      <form @submit.prevent="linkExistingAccount" class="link-form">
        <label>E-Mail-Adresse</label>
        <input v-model="email" type="email" required>
        <label>Passwort</label>
        <input v-model="password" type="password" required>
        <button class="btn btn-primary" :disabled="linking">
          {{ linking ? 'Wird verknüpft...' : 'Bestehenden Account verknüpfen' }}
        </button>
        <button type="button" class="btn" @click="router.push('/login')">Abbrechen</button>
      </form>
      <p v-if="errorMessage" class="error">{{ errorMessage }}</p>
    </div>
    <div v-else class="loading-container">
      <h2>{{ status }}</h2>
      <div class="spinner"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useAuthStore } from '../stores/authStore'
import { API_BASE_URL } from '@/config/api'

const route = useRoute()
const router = useRouter()
const authStore = useAuthStore()
const API_URL = API_BASE_URL

const status = ref('Authentifizierung läuft...')
const pendingToken = ref('')
const googleEmail = ref('')
const email = ref('')
const password = ref('')
const linking = ref(false)
const errorMessage = ref('')

async function finishLogin(token) {
  authStore.saveToken(token)
  await authStore.fetchCurrentUser()
  status.value = 'Login erfolgreich! Sie werden weitergeleitet...'
  setTimeout(() => {
    router.push('/')
  }, 1000)
}

async function linkExistingAccount() {
  try {
    linking.value = true
    errorMessage.value = ''
    const response = await fetch(`${API_URL}/auth/oauth/link-existing`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        pendingToken: pendingToken.value,
        email: email.value,
        password: password.value
      })
    })
    const result = await response.json()
    if (!response.ok || !result.success || !result.token) {
      throw new Error(result.error || 'Verknüpfung fehlgeschlagen')
    }
    pendingToken.value = ''
    await finishLogin(result.token)
  } catch (error) {
    errorMessage.value = error.message || 'Verknüpfung fehlgeschlagen'
  } finally {
    linking.value = false
  }
}

onMounted(async () => {
  const token = route.query.token
  const error = route.query.error
  const pending = route.query.pending

  if (error) {
    status.value = 'OAuth-Login fehlgeschlagen'
    setTimeout(() => {
      router.push('/login')
    }, 2000)
    return
  }

  if (pending) {
    pendingToken.value = pending
    googleEmail.value = route.query.email || ''
    email.value = route.query.email || ''
    return
  }

  if (token) {
    try {
      await finishLogin(token)
    } catch (err) {
      status.value = 'Fehler beim Login'
      setTimeout(() => {
        router.push('/login')
      }, 2000)
    }
  } else {
    status.value = 'Kein Token erhalten'
    setTimeout(() => {
      router.push('/login')
    }, 2000)
  }
})
</script>

<style scoped>
.oauth-callback {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #ffffff;
}

.loading-container {
  text-align: center;
}

.link-container {
  background: #fafafa;
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  padding: 24px;
  width: min(460px, calc(100vw - 32px));
}

.link-container h2 {
  margin-top: 0;
}

.link-form {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.link-form input {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.error {
  color: #d9534f;
}

.loading-container h2 {
  color: #333;
  font-weight: 500;
  margin-bottom: 2rem;
}

.spinner {
  border: 4px solid #f3f3f3;
  border-top: 4px solid #5bc0de;
  border-radius: 50%;
  width: 50px;
  height: 50px;
  animation: spin 1s linear infinite;
  margin: 0 auto;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style>


