<template>
  <form @submit.prevent="newPasswordFunc" class="relative px-6 py-11">
    <div class="flex flex-col gap-5 p-2 mb-8 relative">
      <div class="w-full grid gap-3 relative">
        <input class="input-field xs:min-w-[350px] min-w-64" id="password-register" v-model="password" :type="showPassword ? 'text' : 'password'" name="password" placeholder="Password" required />
        <button type="button" @click.prevent="showPassword = !showPassword" :class="{ 'eye-open': showPassword }" class="bg-[url('/assets/icons/eye.svg')] p-0 absolute right-3 w-4 h-3 top-1/2 -translate-y-1/2 bg-no-repeat"></button>
        <span v-if="newPasswordError" class="text-red-200 text-xs absolute top-full mt-1">{{ newPasswordError }}</span>
      </div>
      <button class="btn-cyan xs:w-full" type="submit">Change password</button>

      <!-- Divider shape -->
      <div class="absolute w-40 h-0.5 -bottom-8 left-1/2 -translate-x-1/2 flex justify-between">
        <div class="w-0.5 h-full bg-gray-300"></div>
        <div class="w-36 h-full bg-gray-300"></div>
        <div class="w-0.5 h-full bg-gray-300"></div>
      </div>
    </div>
    <div class="pt-8">
      <p class="m-0 text-center"><button class="text-cyan-300 text-base p-0" @click.prevent="cancelNewPassword">Back to login</button></p>
    </div>
  </form>
</template>

<script setup lang="ts">
import { newPassword } from '@/services/authenticationService'
import { useGameStore } from '@/stores/gameStore'
import { useCookies } from '@vueuse/integrations/useCookies'
import { onMounted, ref } from 'vue'

const emit = defineEmits(['switchToLogin'])

const gameStore = useGameStore()
const password = ref('')
const newPasswordError = ref('')
const showPassword = ref(false)

// automatic login because of development
onMounted(async () => {
  const token = useCookies().get('token')
  if (token) {
    gameStore.setToken(token)
    gameStore.initConnection()
  }
})

async function newPasswordFunc() {
  // check if username and password are valid
  if (password.value === '') {
    newPasswordError.value = 'Please enter a password'
    return
  }

  const urlToken = window.location.hash.split('#')[1]

  // send new password event to server along with the token
  const response = await newPassword(urlToken, password.value)

  if (response.success === undefined) {
    newPasswordError.value = response.error
    return
  }

  gameStore.addNotification({
    title: 'Success',
    message: 'Password changed successfully'
  })

  window.history.replaceState(null, '', window.location.pathname)
  emit('switchToLogin')
}

function cancelNewPassword() {
  window.history.replaceState(null, '', windowlocation.pathname)
  emit('switchToLogin')
}
</script>
