<template>
  <div class="oauth-callback-container">
    <n-spin :show="loading" size="large">
      <div class="callback-content">
        <n-result
          v-if="!loading && success"
          status="success"
          title="授权成功"
          description="正在跳转..."
        />
        <n-result
          v-else-if="!loading && error"
          status="error"
          title="授权失败"
          :description="error"
        >
          <template #footer>
            <n-button type="primary" @click="goToLogin">返回登录</n-button>
          </template>
        </n-result>
        <div v-else class="loading-text">
          <n-icon size="48" :depth="3">
            <Icon icon="tabler:loader-2" />
          </n-icon>
          <p>正在处理授权...</p>
        </div>
      </div>
    </n-spin>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { NSpin, NResult, NButton, NIcon, useMessage } from 'naive-ui'
import { Icon } from '@iconify/vue'
import { useAuthStore } from '../shared/stores/auth'

const router = useRouter()
const message = useMessage()
const authStore = useAuthStore()

const loading = ref(true)
const success = ref(false)
const error = ref<string | null>(null)

const goToLogin = () => {
  router.push('/login')
}

onMounted(async () => {
  try {
    const result = await authStore.handleOAuthCallback()
    
    if (result.success) {
      success.value = true
      message.success('登录成功')
      
      // 延迟跳转，让用户看到成功提示
      setTimeout(() => {
        router.push('/')
      }, 1000)
    } else {
      error.value = result.error || '授权失败'
      loading.value = false
    }
  } catch (err: any) {
    console.error('OAuth 回调处理错误:', err)
    error.value = err.message || '处理授权回调时发生错误'
    loading.value = false
  }
})
</script>

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

.callback-content {
  width: 100%;
  max-width: 500px;
  padding: 24px;
}

.loading-text {
  text-align: center;
  padding: 48px;
}

.loading-text p {
  margin-top: 16px;
  font-size: 16px;
  color: #666;
}
</style>
