<template>
  <UCard class="max-w-md mx-auto">
    <template #header>
      <h2 class="text-2xl font-bold text-center text-gray-900 dark:text-white">
        登录
      </h2>
    </template>

    <UAlert
      v-if="error"
      :title="error"
      color="red"
      variant="subtle"
      class="mb-4"
      @close="error = null"
    />

    <UForm :state="form" :validate="validate" @submit="onSubmit" class="space-y-4">
      <UFormField label="邮箱/用户名" name="emailOrUsername" required>
        <UInput
          v-model="form.emailOrUsername"
          placeholder="请输入邮箱或用户名"
          autocomplete="username"
        />
      </UFormField>

      <UFormField label="密码" name="password" required>
        <UInput
          v-model="form.password"
          type="password"
          placeholder="请输入密码"
          autocomplete="current-password"
        />
      </UFormField>

      <div class="flex items-center justify-between">
        <UCheckbox v-model="form.remember" label="记住我" />
      </div>

      <UButton
        type="submit"
        color="indigo"
        class="w-full"
        :loading="isLoading"
        :disabled="isLoading"
      >
        登录
      </UButton>
    </UForm>

    <template #footer>
      <p class="text-center text-sm text-gray-600 dark:text-gray-400">
        还没有账号？请联系管理员
      </p>
    </template>
  </UCard>
</template>

<script setup lang="ts">
import type { FormSubmitEvent } from '#ui/types'

definePageMeta({
  layout: 'default',
  middleware: (to) => {
    const { isAuthenticated } = useAuth()
    if (isAuthenticated.value) {
      return navigateTo('/')
    }
  },
})

useSeoMeta({
  title: '登录 - LinkShare Blog',
  description: '登录到您的 LinkShare Blog 账号',
})

const { login, isLoading } = useAuth()
const error = ref<string | null>(null)

const form = ref({
  emailOrUsername: '',
  password: '',
  remember: false,
})

const validate = (state: any) => {
  const errors = []
  if (!state.emailOrUsername) {
    errors.push({ path: 'emailOrUsername', message: '请输入邮箱或用户名' })
  }
  if (!state.password) {
    errors.push({ path: 'password', message: '请输入密码' })
  } else if (state.password.length < 6) {
    errors.push({ path: 'password', message: '密码至少需要 6 位' })
  }
  return errors
}

const onSubmit = async (event: FormSubmitEvent<any>) => {
  try {
    error.value = null
    await login(form.value)
  } catch (err: any) {
    error.value = err.data?.message || '登录失败，请检查账号密码'
  }
}
</script>
