<script setup>
import { ref, nextTick } from "vue";
import InputError from "../InputError.vue";
import InputLabel from "../InputLabel.vue";
import TextInput from "../TextInput.vue";
import Modal from "../Modal.vue";
import { useForm, usePage } from "@inertiajs/vue3";

// define Inertia page to pull props from
const page = usePage();

// define active prop - passed from parent
const { modelValue } = defineProps({
    modelValue: Boolean,
});

// define ref
const nameInput = ref(null);

// pass "close" emit up towards NewDropdown.vue
// also clear form
const emit = defineEmits(["close"]);
const close = () => {
    emit("close");
    form.clearErrors();
    form.reset();
};

// create folder function
const create = () => {
    // get parent_id from page props
    form.parent_id = page.props.folder.id;
    // post to folder.new
    form.post(route("folder.new"), {
        preserveScroll: true,
        onSuccess: () => {
            // close window when successful
            close();
            // show success notifiation
        },
        // otherwise focus on name input field
        onError: () => nameInput.value.focus,
    });
};

// create form
const form = useForm({
    name: "",
    parent_id: null,
});

const focusInput = () => {
    nextTick(() => {
        nameInput.value.focus();
    });
};
</script>

<template>
    <Modal :show="modelValue" @close="close" @active="focusInput">
        <div class="flex flex-col justify-center items-center">
            <h2 class="text-2xl">New Folder</h2>
            <div class="mt-10">
                <InputLabel
                    class="mb-2 text-lg"
                    for="name"
                    value="Folder Name:"
                />
                <TextInput
                    type="text"
                    id="name"
                    v-model="form.name"
                    class="block w-full mb-2"
                    :class="
                        form.errors.name
                            ? 'border-red-800 focus:border-red-800 focus:ring-red-800'
                            : ''
                    "
                    @keyup.enter="create()"
                    ref="nameInput"
                />
                <InputError :message="form.errors.name" />
            </div>
            <div class="justify-center mt-5">
                <button
                    @click="create()"
                    :disable="form.processing"
                    :class="{ 'opacity-25': form.processing }"
                    class="border border-sky-600 px-5 py-3 rounded hover:bg-green-700"
                >
                    Create
                </button>
            </div>
        </div>
    </Modal>
</template>
