<script setup>
import { reactive, ref } from '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: '',
}

// computed properties

// watchers

// lifecycle hooks

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

function 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()
  })
}

function closeModal() {
  confirmingPassword = false
  form.password = ''
  form.error = ''
}

</script>

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

        <jet-dialog-modal :show="confirmingPassword" @close="closeModal">
            <template #title>
                {{ title }}
            </template>

            <template #content>
                {{ content }}

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

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

            <template #footer>
                <jet-secondary-button @click="closeModal">
                    Cancel
                </jet-secondary-button>

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