<script lang="ts" setup>
import { computed, onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Box } from '@/components/ui/box'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { AlertRoot, AlertTitle, AlertDescription } from '@/components/ui/alert'
import {
  getVerifyEmailErrorMessage,
  resendVerificationEmail,
  resolvePostAuthRoute,
  verifyEmail,
} from '@/modules/auth'
import { useAuthStore } from '@/stores/auth'
import logoUrl from '@/assets/images/logo-kopkb.svg'
import illustrationUrl from '@/assets/images/logo-kopkb.svg'

const route = useRoute()
const router = useRouter()
const authStore = useAuthStore()

const email = ref('')
const otp = ref('')
const loading = ref(false)
const resendLoading = ref(false)
const errorMessage = ref('')
const resendMessage = ref('')

const canSubmit = computed(() => email.value.length > 0 && otp.value.length === 6)

onMounted(() => {
  const queryEmail = route.query.email
  if (typeof queryEmail === 'string' && queryEmail) {
    email.value = queryEmail
  }
})

const handleVerify = async () => {
  errorMessage.value = ''
  loading.value = true

  try {
    const response = await verifyEmail({
      email: email.value,
      otp: otp.value,
    })

    authStore.setSession(response.data.user, response.active_role, response.can_switch_role)
    await router.push(resolvePostAuthRoute(response.data.user))
  } catch (error) {
    errorMessage.value = getVerifyEmailErrorMessage(error)
  } finally {
    loading.value = false
  }
}

const handleResend = async () => {
  if (!email.value) {
    errorMessage.value = 'Sila masukkan alamat e-mel.'
    return
  }

  errorMessage.value = ''
  resendMessage.value = ''
  resendLoading.value = true

  try {
    const response = await resendVerificationEmail(email.value)
    resendMessage.value = response.message
  } catch (error) {
    errorMessage.value = getVerifyEmailErrorMessage(error)
  } finally {
    resendLoading.value = false
  }
}

const onOtpInput = (event: Event) => {
  const target = event.target as HTMLInputElement
  otp.value = target.value.replace(/\D/g, '').slice(0, 6)
}

const appName = import.meta.env.VITE_APP_NAME
const appVersion = import.meta.env.VITE_APP_VERSION
</script>

<template>
  <div :class="[
    'relative h-screen lg:overflow-hidden bg-primary bg-noise xl:bg-background xl:bg-none',
    'before:hidden before:xl:block before:content-[\'\'] before:w-[57%] before:mt-[-28%] before:mb-[-16%] before:ml-[-12%] before:absolute before:inset-y-0 before:left-0 before:transform before:rotate-6 before:bg-primary/95 before:bg-noise before:rounded-[35%]',
    'after:hidden after:xl:block after:content-[\'\'] after:w-[57%] after:mt-[-28%] after:mb-[-16%] after:ml-[-12%] after:absolute after:inset-y-0 after:left-0 after:transform after:rotate-6 after:border after:bg-accent after:bg-cover after:blur-xl after:rounded-[35%] after:border-primary',
  ]">
    <div :class="[
      'p-3 sm:px-8 relative h-full',
      'before:hidden before:xl:block before:w-[57%] before:mt-[-20%] before:mb-[-13%] before:ml-[-12%] before:absolute before:inset-y-0 before:left-0 before:transform before:-rotate-6 before:bg-primary/40 before:bg-noise before:border before:border-primary/50 before:opacity-60 before:rounded-[20%]',
    ]">
      <div class="container relative z-10 mx-auto sm:px-20">
        <div class="block grid-cols-2 gap-4 xl:grid">
          <div class="hidden min-h-screen flex-col xl:flex">
            <a class="flex items-center pt-10" href="">
              <img class="w-6" :src="logoUrl" alt="logo-RAJD" />
              <span class="ml-3 text-xl font-medium text-white">
                {{ appName }} {{ appVersion }}
              </span>
            </a>
            <div class="my-auto">
              <img class="-mt-16 w-1/2" :src="illustrationUrl" alt="logo-RAJD" />
              <div class="mt-10 text-4xl font-medium leading-tight text-white">
                Sahkan E-mel
              </div>
              <div class="mt-5 text-lg text-white opacity-60">
                Masukkan kod 6 digit yang dihantar ke e-mel anda.
              </div>
            </div>
          </div>

          <div class="my-10 flex h-screen py-5 xl:my-0 xl:h-auto xl:py-0">
            <Box raised="double"
              class="mx-auto my-auto w-full px-5 py-8 sm:w-3/4 sm:px-8 lg:w-2/4 xl:ml-24 xl:w-auto xl:p-0 xl:before:hidden xl:after:hidden xl:shadow-none xl:border-none xl:bg-none">
              <h2 class="text-center text-2xl font-semibold xl:text-left xl:text-3xl">
                Verify Email
              </h2>
              <p class="mt-2 text-center text-sm opacity-70 xl:text-left">
                Kod OTP 6 digit telah dihantar ke e-mel anda.
              </p>

              <AlertRoot v-if="errorMessage" class="mt-6" variant="danger">
                <AlertTitle>Verification failed</AlertTitle>
                <AlertDescription>{{ errorMessage }}</AlertDescription>
              </AlertRoot>

              <AlertRoot v-if="resendMessage" class="mt-6" variant="primary">
                <AlertDescription>{{ resendMessage }}</AlertDescription>
              </AlertRoot>

              <form class="mt-8 flex flex-col gap-5" @submit.prevent="handleVerify">
                <Input v-model="email" class="box block min-w-full px-5 py-6 xl:min-w-md" type="email"
                  placeholder="Email" autocomplete="email" required />
                <Input :model-value="otp"
                  class="box block min-w-full px-5 py-6 xl:min-w-md text-center tracking-[0.5em] text-lg" type="text"
                  inputmode="numeric" pattern="[0-9]*" maxlength="6" placeholder="000000" autocomplete="one-time-code"
                  required @input="onOtpInput" />

                <div class="mt-5 text-center xl:mt-10 xl:text-left">
                  <Button class="box w-full px-4 py-5" variant="primary" type="submit"
                    :disabled="loading || !canSubmit">
                    {{ loading ? 'Verifying...' : 'Verify Email' }}
                  </Button>
                  <Button class="box mt-4 w-full px-4 py-5" look="outline" type="button"
                    :disabled="resendLoading || !email" @click="handleResend">
                    {{ resendLoading ? 'Sending...' : 'Resend Code' }}
                  </Button>
                  <Button class="box mt-4 w-full px-4 py-5" look="outline" type="button"
                    @click="router.push({ name: 'login' })">
                    Back to Login
                  </Button>
                </div>
              </form>
            </Box>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
