<script setup>
import { reactive, ref } from 'vue'
import DialogModal from './DialogModal.vue'
import InputElm from '@/Components/Input.vue'
import InputError from '@/Components/Input.vue'

const emit = defineEmits(['confirmed'])

const props = defineProps({
  title: {
    default: 'Confirm Password',
  },
  content: {
    default: 'For your security, please confirm your password to continue.',
  },
  button: {
    default: 'Confirm',
  },
})

let confirmingPassword = false
let form = {
  password: '',
  error: '',
}

// methods
const startConfirmingPassword = (() {
  axios.get(route('password.confirmation')).then(resp => {
    if (resp.data.confirmed) {
      emit('confirmed')
    } else {
      confirmingPassword = true
      setTimeout(() => $refs.password.focus(), 250)
    }
  })
})

const confirmPassword = (() => {
  form.processing = true

  axios.post(route('password.confirm'), {
    password: form.password,
  }).then(() => {
    form.processing = false
    closeModal()
    $nextTick(() => emit('confirmed'))
  }).catch(erro => {
    form.processing = false;
    form.error = erro.response.data.errors.password[0]
    $refs.password.focus()
  })
})

const closeModal = (() => {
  confirmingPassword = false
  form.password = ''
  form.error = ''
})
</script>

<template>
    <div>
        <span @click="startConfirmingPassword">
            <slot></slot>
        </span>

        <DialogModal :show="confirmingPassword" @close="closeModal">
            <template #title>{{ title }}</template>

            <template #content>
                {{ content }}

                <div class="mt-4">
                    <InputElm type="password" class="mt-1 block w-3/4" placeholder="Password"
                                ref="password"
                                v-model="form.password"
                                @keyup.enter="confirmPassword"></InputElm>

                    <InputError :message="form.error" class="mt-2"></InputError>
                </div>
            </template>

            <template #footer>
                <button type="button" class="button button-gradient-secondary" @click="closeModal">Cancel</button>

                <button class="button button-gradient-primary ml-3" @click="confirmPassword" :class="{ 'opacity-25': form.processing }" :disabled="form.processing">
                    {{ button }}
                </button>
            </template>
        </DialogModal>
    </div>
</template>
