<script setup lang="ts">
const { signUpEmail, user, signOut } = useAuth()
const toast = useToast()
const { t } = useI18n()
const localePath = useLocalePath()
const { socialProviders } = useSocialProviders()

const email = ref('')
const password = ref('')
const name = ref('')
const loading = ref(false)
const disableForm = ref(false)
const verificationRequired = ref(false)

async function signUp() {
  if (loading.value) return
  loading.value = true

  const response = await signUpEmail({
    email: email.value,
    password: password.value,
    name: name.value
  })

  if (response.error) {
    toast.add({
      title: response.error.message,
      color: 'error'
    })
    loading.value = false
    return
  }

  // When requireEmailVerification is true, Better Auth doesn't create a session
  // until the email is verified. So if there's no error, we show the verification message.

  // If no session exists, email verification is required
  if (!user.value) {
    // Show verification message
    verificationRequired.value = true
    toast.add({
      title: t('auth.signup.verificationRequired'),
      description: t('auth.signup.checkEmail'),
      color: 'primary'
    })
  } else if (user.value?.emailVerified === false) {
    // User has a session but email is not verified - sign them out
    await signOut({ redirectTo: localePath('/auth') })

    // Show verification message
    verificationRequired.value = true
    toast.add({
      title: t('auth.signup.verificationRequired'),
      description: t('auth.signup.checkEmail'),
      color: 'primary'
    })
  } else {
    // User is verified, redirect to dashboard
    toast.add({
      title: t('auth.toastSignedUp')
    })
    navigateTo(localePath('/dashboard'))
  }

  loading.value = false
}

function signUpPending() {
  disableForm.value = true
  return true
}
</script>

<template>
  <NuxtLayout>
    <UContainer>
      <UPageBody>
        <AuthCard
          :title="t('auth.signup.title')"
          :disabled="disableForm"
        >
          <template v-if="!verificationRequired">
            <template v-if="socialProviders.length > 0">
              <AuthSocialProviders
                :available-providers="socialProviders"
                :is-register-page="true"
                @sign-in="signUpPending"
              />
              <USeparator
                :label="t('auth.or')"
                class="my-6"
              />
            </template>

            <div class="mb-6">
              <form
                class="flex flex-col gap-4 text-left"
                @submit.prevent="signUp"
              >
                <UFormField
                  :label="t('auth.name')"
                  required
                >
                  <UInput
                    v-model="name"
                    type="text"
                    :placeholder="t('auth.name')"
                    class="w-full"
                    :icon="useSolarIcon('user')"
                  />
                </UFormField>

                <UFormField
                  :label="t('auth.email')"
                  required
                >
                  <UInput
                    v-model="email"
                    type="email"
                    :placeholder="t('auth.email')"
                    class="w-full"
                    :icon="useSolarIcon('letter')"
                  />
                </UFormField>

                <UFormField
                  :label="t('auth.password')"
                  required
                >
                  <UInput
                    v-model="password"
                    type="password"
                    :placeholder="t('auth.password')"
                    class="w-full"
                    :icon="useSolarIcon('lock')"
                  />
                  <template #hint>
                    <span class="text-xs text-muted">
                      {{ t('auth.validation.passwordMinLength') }}
                    </span>
                  </template>
                </UFormField>

                <UButton
                  type="submit"
                  color="primary"
                  :loading="loading"
                  :disabled="!email || !password || !name"
                  block
                >
                  {{ t('auth.signUp') }}
                </UButton>
              </form>

              <div class="text-center mt-6">
                {{ t('auth.signup.hasAccount') }}
                <ULink
                  :to="localePath('/auth')"
                  class="text-primary hover:underline ml-1"
                >
                  {{ t('auth.signIn') }}
                </ULink>
              </div>
            </div>
          </template>

          <template v-else>
            <div class="text-center py-6">
              <UIcon
                :name="useSolarIcon('letter')"
                class="h-10 w-10 mx-auto mb-4 text-primary"
              />
              <h2 class="text-xl font-semibold mb-2">
                {{ t('auth.signup.verifyEmail') }}
              </h2>
              <p class="text-muted mb-6">
                {{ t('auth.signup.verifyEmailDescription', { email }) }}
              </p>
              <UButton
                :to="localePath('/auth')"
                color="neutral"
                variant="outline"
              >
                {{ t('auth.signup.backToLogin') }}
              </UButton>
            </div>
          </template>
        </AuthCard>
      </UPageBody>
    </UContainer>
  </NuxtLayout>
</template>
