<!-- src/pages/auth/register.vue -->

<template>
  <div class="WrapperPlain">
    <div class="container mx-auto max-w-lg text-white">
      <div class="mx-auto flex items-center justify-center ">
        <form class="bg-neutral rounded-md  px-8 pt-6 pb-8 mb-4 mt-4 w-full" method="POST" @submit.prevent="onSubmit">
          <div class="mb-4 text-center text-[28px] ">Register</div>
          <div class="mb-4">
            <label class="block text-white text-sm font-bold mb-2" for="username">Username</label>
            <input v-model="form.username" class="rounded w-full py-2 px-3 input-primary text-black" id="username"
              type="text" placeholder="Login Username" :class="{ 'input-error': v$.form.username.$error }" />
            <span v-if="v$.form.username.$error" class="text-red-600 text-center">
              {{ v$.form.username.$errors[0].$message }}
            </span>
          </div>

          <div class="mb-4">
            <label class="block text-white text-sm font-bold mb-2" for="email">Email</label>
            <input v-model="form.email" class="rounded w-full py-2 px-3 input-primary text-black" id="email" type="text"
              placeholder="Email" :class="{ 'input-error': v$.form.email.$error }" />
            <span v-if="v$.form.email.$error" class="text-red-600 text-center">
              {{ v$.form.email.$errors[0].$message }}
            </span>
          </div>
          <div class="mb-4">
            <label class="block text-white text-sm font-bold mb-2" for="password">Password</label>
            <input v-model="form.password" class="rounded w-full py-2 px-3 input-primary text-black" id="password"
              type="password" autocomplete="off" placeholder="Password"
              :class="{ 'input-error': v$.form.password.$error }" />
            <span v-if="v$.form.password.$error" class="text-red-600 text-center">
              {{ v$.form.password.$errors[0].$message }}
            </span>
          </div>
          <div class="mb-4">
            <label class="block text-white text-sm font-bold mb-2" for="password_confirm">Confirm Password</label>
            <input v-model="form.password_confirm" class="rounded w-full py-2 px-3 input-primary text-black"
              id="password_confirm" type="password" autocomplete="off" placeholder="Confirm Password"
              :class="{ 'input-error': v$.form.password_confirm.$error }" />
            <span v-if="v$.form.password_confirm.$error" class="text-red-600 text-center">
              {{ v$.form.password_confirm.$errors[0].$message }}
            </span>
          </div>

          <div class="flex items-center justify-center mb-6">
            <button
              class="bg-primary hover:bg-zinc-400 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline"
              type="submit">
              Register
            </button>
          </div>
          <div class="flex flex-col justify-center">
            <router-link :to="{ name: 'lostPassword' }"
              class="text-center font-bold text-sm text-blue-500 hover:text-blue-800">Forgot Password?</router-link>
          </div>
          <div class="flex flex-col justify-center mt-5">
            <router-link :to="{ name: 'login' }"
              class="text-center font-bold text-sm text-blue-500 hover:text-blue-800">Login Here</router-link>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { notify } from "@kyvg/vue3-notification"
import { useVuelidate } from '@vuelidate/core'
import { required, email, minLength, sameAs } from "@vuelidate/validators"
import { authService } from '../../services/authService'

const router = useRouter()

// Form state
const form = reactive({
  username: '',
  email: '',
  password: '',
  password_confirm: '',
})

// Validation rules
const rules = computed(() => ({
  form: {
    username: { required, minLength: minLength(6) },
    email: { email, required },
    password: { required, minLength: minLength(6) },
    password_confirm: {
      required,
      minLength: minLength(6),
      sameAs: sameAs(form.password),
    },
  },
}))

const v$ = useVuelidate(rules, { form })

// Methods
async function onSubmit() {
  const isValid = await v$.value.$validate()

  if (!isValid) {
    notify({
      title: "Authorization",
      text: "Form Failure; Fields must be filled out correctly.",
      type: "error",
    })
    return
  }

  try {
    const response = await authService.register({
      username: form.username,
      password: form.password,
      email: form.email,
    })

    const data = response.data as any

    if (data.error) {
      notify({
        title: "Authorization",
        text: data.error,
        type: "error",
      })
      return
    }

    if (data.ok) {
      localStorage.setItem("auth_user", data.user)
      localStorage.setItem("auth_token", data.token)
      router.push({ name: "home" })
      notify({
        title: "Authorization",
        text: "Success",
        type: "success",
      })
    }
  } catch (error) {
    notify({
      title: "Authorization",
      text: "Registration failed. Please try again.",
      type: "error",
    })
  }
}
</script>

<style scoped></style>