<template>
  <PageForm
    back-link="/login"
    :back-text="$t('to_main')"
    :title="$t('login_greeting')"
    :submit-text="$t('next')"
    :handler="onSubmit"
  >
    <UiInput
      id="email"
      class="mb-6"
      :label="$t('email')"
      rules="required|email"
    />

    <UiInput
      id="password"
      :label="$t('password')"
      native-type="password"
      rules="required"
    />

    <div class="login-form__forgot-password">
      <UiButton
        type="link"
        href="/reset-password"
      >
        {{ $t('lost_password') }}
      </UiButton>
    </div>
  </PageForm>
</template>

<script setup>
definePageMeta({
  layout: 'auth',
  pageTransition: { name: 'fade', mode: 'out-in' },
  middleware: ['guest-only'],
})

const auth = useAuth()

if (!import.meta.env.SSR) {
  const verifiedCookie = useCookie('verified')
  const { t } = useI18n()
  const notify = useNotify()

  if (verifiedCookie.value) {
    notify({
      id: 'verified',
      text: t('account_created_successfully'),
      type: 'positive',
    })
  }
  else if (verifiedCookie.value !== undefined) {
    notify({
      id: 'verified',
      title: t('account_verification_error'),
      text: t('try_again_or_contact_support'),
      type: 'negative',
    })
  }

  verifiedCookie.value = undefined
}

async function onSubmit(values) {
  try {
    await auth.login(values.email, values.password)
  }
  catch (e) {
    if (e.status === 422) {
      setStaticError({
        status: e.status,
        message: 'Incorrect email or password',
      })
    }
    else {
      setStaticError({
        status: e.status,
        message: 'Something went wrong',
      })
    }
  }
}
</script>

<style lang="scss">
.login-form {
  &__forgot-password {
    margin-top: -6px;
    text-align: right;
  }
}
</style>
