<script setup lang="ts">
import Modal from "ChillMainAssets/vuejs/_components/Modal.vue";
import { StoredObject, StoredObjectVersion } from "../../types";
import DropFileWidget from "ChillDocStoreAssets/vuejs/DropFileWidget/DropFileWidget.vue";
import { computed, reactive } from "vue";
import { useToast } from "vue-toast-notification";

interface DropFileConfig {
    allowRemove: boolean;
    existingDoc?: StoredObject;
}

const props = withDefaults(defineProps<DropFileConfig>(), {
    allowRemove: false,
});

const emit = defineEmits<{
    (
        e: "addDocument",
        {
            stored_object: StoredObject,
            stored_object_version: StoredObjectVersion,
            file_name: string,
        },
    ): void;
    (e: "removeDocument"): void;
}>();

const $toast = useToast();

const state = reactive({ showModal: false });

const modalClasses = { "modal-dialog-centered": true, "modal-md": true };

const buttonState = computed<"add" | "replace">(() => {
    if (props.existingDoc === undefined || props.existingDoc === null) {
        return "add";
    }

    return "replace";
});

function onAddDocument({
    stored_object,
    stored_object_version,
    file_name,
}: {
    stored_object: StoredObject;
    stored_object_version: StoredObjectVersion;
    file_name: string;
}): void {
    const message =
        buttonState.value === "add" ? "Document ajouté" : "Document remplacé";
    $toast.success(message);
    emit("addDocument", { stored_object_version, stored_object, file_name });
    state.showModal = false;
}

function onRemoveDocument(): void {
    emit("removeDocument");
}

function openModal(): void {
    state.showModal = true;
}

function closeModal(): void {
    state.showModal = false;
}
</script>

<template>
    <button
        v-if="buttonState === 'add'"
        @click="openModal"
        class="btn btn-create"
    >
        Ajouter un document
    </button>
    <button v-else @click="openModal" class="btn btn-edit">
        Remplacer le document
    </button>
    <modal
        v-if="state.showModal"
        :modal-dialog-class="modalClasses"
        @close="closeModal"
    >
        <template v-slot:body>
            <drop-file-widget
                :existing-doc="existingDoc"
                :allow-remove="allowRemove"
                @add-document="onAddDocument"
                @remove-document="onRemoveDocument"
            ></drop-file-widget>
        </template>
    </modal>
</template>

<style scoped lang="scss"></style>
