<script setup lang="ts">
import { ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { isAxiosError } from 'axios'
import { useAuthStore } from '@/stores/auth'
import PrismIcon from '@/components/PrismIcon.vue'

const { t } = useI18n()
const router = useRouter()
const auth = useAuthStore()
const password = ref('')
const loading = ref(false)

function formatRetryAfter(seconds: number) {
  if (seconds >= 60) {
    return t('common.minutes', { n: Math.ceil(seconds / 60) })
  }
  return t('common.seconds', { n: seconds })
}

function loginErrorMessage(err: unknown) {
  if (!isAxiosError(err)) return t('login.failed')
  const status = err.response?.status
  const data = err.response?.data as { retry_after?: number; remaining?: number } | undefined
  if (status === 429) {
    return t('login.tooManyAttempts', { wait: formatRetryAfter(data?.retry_after ?? 60) })
  }
  if (typeof data?.remaining === 'number' && data.remaining > 0) {
    return t('login.wrongPasswordRemaining', { n: data.remaining })
  }
  return t('login.wrongPassword')
}

async function submit() {
  loading.value = true
  try {
    await auth.login(password.value)
    router.push('/')
  } catch (err) {
    ElMessage.error(loginErrorMessage(err))
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <div class="login-page">
    <div class="login-wrap">
      <div class="login-brand-icon">
        <PrismIcon :size="24" />
      </div>
      <h1 class="page-title">Prism</h1>
      <p class="page-desc">{{ t('login.subtitle') }}</p>
      <div class="login-card">
        <h3 class="app-card__title u-mb-6">{{ t('login.title') }}</h3>
        <el-form size="large" @submit.prevent="submit">
          <el-form-item :label="t('login.password')">
            <el-input v-model="password" type="password" show-password :placeholder="t('login.passwordPlaceholder')" />
          </el-form-item>
          <el-button type="primary" native-type="submit" :loading="loading" class="w-full">
            {{ t('login.submit') }}
          </el-button>
        </el-form>
        <p class="form-hint u-mt-4 text-center">
          {{ t('login.hint') }}
        </p>
      </div>
    </div>
  </div>
</template>
