<template>
  <Modal :isModalOpen="true" :modal-width="400" :modal-height="300" :is-resizable="false" @modal:close="() => emit('close')">
    <template #modalHeader>
      <h3 class="m-0 font-medium shrink-0 text-white">Reset Password</h3>
    </template>

    <template #modalBody>
      <div class="h-[calc(100%_-_32px)] p-4">
        <form class="h-full flex flex-col justify-between" @submit.prevent="resetPasswordFunc">
          <div class="flex flex-col relative">
            <p>Fill in your email to receive a password reset request.</p>
            <input type="email" name="email" class="input-field" v-model="email" placeholder="E-mail" />
            <span v-if="resetPasswordError" class="text-red-200 text-xs absolute top-full mt-1">{{ resetPasswordError }}</span>
          </div>
          <div class="grid grid-flow-col justify-stretch gap-4">
            <button class="btn-empty py-1.5 px-4 min-w-24 inline-block" @click.stop="() => emit('close')">Cancel</button>
            <button class="btn-cyan py-1.5 px-4 min-w-24 inline-flex items-center justify-center" type="submit">
              <svg v-if="isLoading" xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 animate-spin mr-2" fill="none" viewBox="0 0 24 24">
                <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
              </svg>
              Send mail
            </button>
          </div>
        </form>
      </div>
    </template>
  </Modal>
</template>

<script setup lang="ts">
import Modal from '@/components/utilities/Modal.vue'
import { resetPassword } from '@/services/authenticationService'
import { useGameStore } from '@/stores/gameStore'
import { ref } from 'vue'

const emit = defineEmits(['close'])

const gameStore = useGameStore()
const isLoading = ref(false)
const email = ref('')
const resetPasswordError = ref('')

async function resetPasswordFunc() {
  // check if email is valid
  if (email.value === '') {
    resetPasswordError.value = 'Please enter an email'
    return
  }

  isLoading.value = true

  // send reset password event to server
  const response = await resetPassword(email.value)

  if (response.success === undefined) {
    resetPasswordError.value = response.error
    isLoading.value = false
    return
  }

  gameStore.addNotification({
    title: 'Success',
    message: 'Password reset email sent'
  })

  isLoading.value = false

  emit('close')
}
</script>
