<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";

const page = usePage();

// define props - drilled from ShareButton
const props = defineProps({
    shareall: {
        type: Boolean,
        default: false,
        required: false,
    },
    selected: {
        type: Array,
        required: false,
    },
    modelValue: Boolean,
});

// define refs
const emailInput = 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 form
const form = useForm({
    email: null,
    all: false,
    Ids: [],
    parent_id: null,
});

// share function
const share = () => {
    // define form fields
    form.all = props.shareall;
    form.Ids = props.selected;
    form.parent_id = page.props.folder.id;

    // post to file.share
    form.post(route("file.share"), {
        preserveScroll: true,
        onSuccess: () => {
            // close window when successful
            close();
        },
        // otherwise focus on email input field
        onError: () => emailInput.value.focus,
    });
};

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

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