<template>
  <div
    class="relative grid min-h-screen place-items-center overflow-hidden bg-[#f5f5f5] px-4 py-12 font-sans text-[#0c0a09] md:py-24">
    <div
      class="pointer-events-none absolute left-1/2 top-10 h-[420px] w-[min(92vw,760px)] -translate-x-1/2 rounded-[48px] bg-[radial-gradient(circle_at_20%_30%,rgba(232,184,196,0.58),transparent_28%),radial-gradient(circle_at_72%_24%,rgba(167,229,211,0.56),transparent_30%),radial-gradient(circle_at_52%_78%,rgba(244,197,168,0.5),transparent_34%)] blur-2xl"
      aria-hidden="true"></div>
    <NuxtLink to="/"
      class="absolute left-4 top-4 z-10 inline-flex h-10 items-center justify-center gap-2 rounded-full border border-[#d6d3d1] bg-white/80 px-4 text-[14px] font-medium leading-none text-[#0c0a09] shadow-[0_4px_16px_rgba(0,0,0,0.04)] backdrop-blur transition hover:border-[#0c0a09] md:left-8 md:top-8">
      <Icon name="mdi:arrow-left" class="text-base" />
      Início
    </NuxtLink>

    <main
      class="relative grid w-full max-w-[1120px] grid-cols-1 items-center gap-8 md:grid-cols-[minmax(0,1fr)_minmax(340px,440px)] md:gap-16"
      aria-labelledby="reset-password-title">
      <section class="relative pt-2 md:py-8">
        <p
          class="m-0 inline-flex rounded-full bg-[rgba(232,184,196,0.58)] px-3 py-1 text-xs font-semibold uppercase leading-[1.4] tracking-[0.96px] text-[#0c0a09]">
          Nova senha
        </p>
        <h1 id="reset-password-title"
          class="my-5 max-w-[640px] font-serif text-[40px] font-light leading-[1.05] tracking-[-1.2px] text-[#0c0a09] md:text-[64px] md:tracking-[-1.92px]">
          Redefina sua senha
        </h1>
        <p class="m-0 max-w-[520px] text-base font-normal leading-6 tracking-[0.16px] text-[#4e4e4e]">
          Use o token gerado na recuperação para definir uma nova senha de acesso.
        </p>
      </section>

      <section
        class="grid gap-5 rounded-2xl border border-[#e7e5e4] bg-white p-6 shadow-[0_4px_16px_rgba(0,0,0,0.04)] md:p-8"
        aria-label="Formulario de redefinicao de senha">
        <div class="mb-1">
          <span
            class="inline-flex min-h-6 items-center rounded-full bg-[rgba(232,184,196,0.58)] px-2.5 py-1 text-xs font-semibold uppercase leading-none tracking-[0.96px] text-[#0c0a09]">
            Reset
          </span>
          <h2 class="mt-4 font-serif text-3xl font-light leading-[1.13] tracking-[-0.32px] text-[#0c0a09]">
            Dados da nova senha
          </h2>
        </div>

        <Form :validation-schema="schema" :initial-values="initialValues" @submit="redefinirSenha" class="grid gap-5">
          <div class="grid gap-2">
            <label class="m-0 text-xs font-semibold uppercase leading-[1.4] tracking-[0.96px] text-[#777169]"
              for="new-password">
              Nova senha
            </label>
            <Field name="newPassword" v-slot="{ field, meta }">
              <input v-bind="field" :disabled="isLoading"
                class="h-11 w-full rounded-lg border bg-white px-4 py-3 text-base leading-6 tracking-[0.16px] text-[#0c0a09] outline-none transition focus:border-2 focus:border-[#0c0a09] disabled:cursor-not-allowed disabled:opacity-50"
                :class="meta.touched && !meta.valid ? 'border-red-400' : 'border-[#d6d3d1]'" type="password"
                id="new-password" />
            </Field>
            <ErrorMessage name="newPassword" class="text-xs text-red-500" />
          </div>

          <div class="grid gap-2">
            <label class="m-0 text-xs font-semibold uppercase leading-[1.4] tracking-[0.96px] text-[#777169]"
              for="confirm-password">
              Confirmar senha
            </label>
            <Field name="confirmPassword" v-slot="{ field, meta }">
              <input v-bind="field" :disabled="isLoading"
                class="h-11 w-full rounded-lg border bg-white px-4 py-3 text-base leading-6 tracking-[0.16px] text-[#0c0a09] outline-none transition focus:border-2 focus:border-[#0c0a09] disabled:cursor-not-allowed disabled:opacity-50"
                :class="meta.touched && !meta.valid ? 'border-red-400' : 'border-[#d6d3d1]'" type="password"
                id="confirm-password" />
            </Field>
            <ErrorMessage name="confirmPassword" class="text-xs text-red-500" />
          </div>

          <p v-if="!resetToken"
            class="rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm leading-[1.47] text-red-600">
            Link de recuperação inválido. Gere uma nova recuperação de senha.
          </p>

          <button type="submit" :disabled="isLoading || !resetToken"
            class="mt-1 inline-flex h-10 items-center justify-center gap-2 rounded-full bg-[#292524] px-5 text-[15px] font-medium leading-none text-white transition hover:bg-[#0c0a09] active:bg-[#0c0a09] disabled:cursor-not-allowed disabled:opacity-70">
            <Icon v-if="isLoading" name="mdi:loading" class="animate-spin text-base" />
            <span v-else>Redefinir senha</span>
          </button>

          <p class="text-center text-[15px] leading-[1.47] tracking-[0.15px] text-[#777169]">
            Lembrou a sua senha?
            <NuxtLink to="/login" class="font-medium text-[#0c0a09] underline-offset-2 hover:underline">
              Entrar agora
            </NuxtLink>
          </p>
        </Form>
      </section>
    </main>
  </div>
</template>

<script setup>
import { toTypedSchema } from '@vee-validate/zod'
import { z } from 'zod'

definePageMeta({ middleware: 'guest' })

useHead({
  title: 'Redefinir senha | GameVerse',
  meta: [
    {
      name: 'description',
      content: 'Defina uma nova senha de acesso usando o token de recuperação da conta GameVerse.'
    }
  ]
})

const route = useRoute()
const { $toast } = useNuxtApp()

const isLoading = ref(false)

const toStr = (val) => (val == null ? '' : String(val))
const resetToken = computed(() => (typeof route.query.token === 'string' ? route.query.token : ''))

const initialValues = {
  newPassword: '',
  confirmPassword: ''
}

const schema = toTypedSchema(
  z
    .object({
      newPassword: z.preprocess(
        toStr,
        z.string().min(8, 'A senha deve ter no mínimo 8 caracteres')
      ),
      confirmPassword: z.preprocess(toStr, z.string().min(1, 'Confirme a nova senha'))
    })
    .refine((data) => data.newPassword === data.confirmPassword, {
      message: 'As senhas não conferem',
      path: ['confirmPassword']
    })
)

async function redefinirSenha({ newPassword }) {
  isLoading.value = true
  try {
    await $fetch('/auth/reset-password', {
      method: 'POST',
      body: {
        token: resetToken.value,
        new_password: newPassword
      }
    })

    $toast.success('Senha redefinida com sucesso!', { duration: 8000 })
    await navigateTo('/login')
  } catch (error) {
    const message = error?.data?.statusMessage
    $toast.error(message ?? 'Erro ao redefinir senha. Gere um novo token e tente novamente.', {
      duration: 8000
    })
  } finally {
    isLoading.value = false
  }
}
</script>
