<template>
    <div v-if="files">
        <label
            :for="name"
            v-if="label"
            class="block mb-1 font-semibold text-xs text-gray-300 peer-required:after:content-['*']"
            >{{ label }}</label
        >
        <transition
            class="flex flex-wrap items-center flex-1 gap-3"
            enter-active-class="transition duration-200 ease-in-out"
            enter-class="translate-y-1 opacity-0"
            enter-to-class="translate-y-0 opacity-100"
            leave-active-class="transition duration-200 ease-in-out"
            leave-class="translate-y-0 opacity-100"
            leave-to-class="translate-y-1 opacity-0"
            mode="out-in"
        >
            <ul
                :key="`${name}_file_preview`"
                class="w-full flex flex-wrap items-start justify-start gap-2.5"
            >
                <swiper
                    :slides-per-view="slidesPerView"
                    :space-between="10"
                    class="w-full flex items-start justify-start gap-2.5 overflow-hidden select-none"
                >
                    <SwiperSlide
                        v-if="files.length < maxFiles && uploadInSlider"
                        key="file-upload"
                    >
                        <li
                            :key="`${name}_file_upload`"
                            @dragover.prevent="dragOver = true"
                            @dragleave.prevent="dragOver = false"
                            @drop.prevent="dragOver = false"
                        >
                            <label
                                :class="dragOver ? 'brightness-95' : ''"
                                :for="name"
                                @drop="dragFile"
                            >
                                <slot name="upload"></slot>
                            </label>
                            <input
                                :id="name"
                                ref="file"
                                :accept="accept"
                                :multiple="maxFiles > 1"
                                :name="name"
                                class="hidden"
                                type="file"
                                @change="upload"
                            />
                            <FormKit
                                v-model="files"
                                :accept="accept"
                                :classes="{
                                    inner: 'hidden',
                                }"
                                :multiple="maxFiles > 1"
                                :name="name"
                                :validation="required ? 'required' : ''"
                                type="file"
                            />
                        </li>
                    </SwiperSlide>
                    <SwiperSlide
                        v-for="(file, index) in files"
                        :key="'portfolio_projects_file_upload_' + index"
                    >
                        <li :title="file.name">
                            <slot name="preview">
                                <button
                                    type="button"
                                    class="relative w-[132px] h-[100px]"
                                >
                                    <img
                                        class="w-full h-full object-cover rounded-[10px]"
                                        :src="getPreviewFromFile(file)"
                                        :alt="file.name"
                                    />
                                    <button
                                        class="absolute top-0 right-0 p-1 m-2 rounded-full bg-gray-200/50"
                                        type="button"
                                        @click="remove(index)"
                                    >
                                        <svg
                                            width="16"
                                            height="16"
                                            viewBox="0 0 16 16"
                                            fill="none"
                                            xmlns="http://www.w3.org/2000/svg"
                                        >
                                            <g
                                                clip-path="url(#clip0_919_50247)"
                                            >
                                                <path
                                                    d="M12 4L4 12"
                                                    stroke="white"
                                                    stroke-width="1.5"
                                                    stroke-linecap="round"
                                                    stroke-linejoin="round"
                                                />
                                                <path
                                                    d="M4 4L12 12"
                                                    stroke="white"
                                                    stroke-width="1.5"
                                                    stroke-linecap="round"
                                                    stroke-linejoin="round"
                                                />
                                            </g>
                                            <defs>
                                                <clipPath id="clip0_919_50247">
                                                    <rect
                                                        width="16"
                                                        height="16"
                                                        fill="white"
                                                    />
                                                </clipPath>
                                            </defs>
                                        </svg>
                                    </button>
                                    <!-- <Lightbox>
                                        <img
                                            class="object-cover w-full h-full"
                                            :src="getPreviewFromFile(file)"
                                            :alt="file.name"
                                        />
                                    </Lightbox> -->
                                </button>
                            </slot>
                        </li>
                    </SwiperSlide>
                </swiper>
                <li
                    :key="`${name}_file_upload`"
                    @dragover.prevent="dragOver = true"
                    @dragleave.prevent="dragOver = false"
                    @drop.prevent="dragOver = false"
                    v-if="files.length < maxFiles && !uploadInSlider"
                    class="w-full"
                >
                    <label
                        :class="dragOver ? 'brightness-95' : ''"
                        :for="name"
                        @drop="dragFile"
                    >
                        <slot name="upload"></slot>
                    </label>
                    <input
                        :id="name"
                        ref="file"
                        :accept="accept"
                        :multiple="maxFiles > 1"
                        :name="name"
                        class="hidden"
                        type="file"
                        @change="upload"
                    />
                    <FormKit
                        v-model="files"
                        :accept="accept"
                        :classes="{
                            inner: 'hidden',
                        }"
                        :multiple="maxFiles > 1"
                        :name="name"
                        :validation="required ? 'required' : ''"
                        type="file"
                    />
                </li>
            </ul>
        </transition>
    </div>
</template>

<script>
import { Swiper, SwiperSlide } from "swiper/vue";

import "swiper/css";
import Lightbox from "@/components/General/Lightbox.vue";

export default {
    props: {
        maxFiles: { type: Number, default: 5 },
        initSelected: { type: Number, default: 0 },
        value: { type: Array, default: () => [] },
        name: String,
        avatar: { type: Boolean, default: false },
        accept: { type: String, default: "*" },
        required: { type: Boolean, default: false },
        label: { type: String, default: null },
        uploadInSlider: { type: Boolean, default: true },
        slidesPerView: { type: Number, default: 3.5 },
    },
    data() {
        return {
            files: [],
            selected: this.initSelected,
            dragOver: false,
            enable: false,
        };
    },
    methods: {
        //Upload by clicking the box
        upload() {
            let fileArray = Array.from(this.$refs.file.files);
            this.files = [...this.files, ...fileArray].slice(0, this.maxFiles);
            this.update();
        },
        //Get blob or url to preview
        getPreviewFromFile(file) {
            return file.url ? file.url : URL.createObjectURL(file);
        },
        //Change the selected main image
        updateSwitch(newVal) {
            if (newVal.checked) this.selected = newVal.value.split("-")[1];
            else this.selected = 0;
            this.update();
        },
        //Upload by dragging and dropping
        dragFile(e) {
            //MIME type
            let fileArray = Array.from(e.dataTransfer.files);
            const acceptedTypes = this.accept;
            fileArray = fileArray.filter(function (el) {
                // return acceptedTypes.includes(el.type);
                // return el.type.match(acceptedTypes) !== null;
                return true;
            });

            this.files = [...this.files, ...fileArray].slice(0, this.maxFiles);
            this.update();
        },
        //After each update set default image and emit to parent component.
        update() {
            this.$emit(
                "update:value",
                this.maxFiles > 1 ? this.files : this.files[0]
            );
        },
        remove(index) {
            this.files.splice(index, 1);
            if (this.files.length <= this.selected) this.selected = 0;
        },
        openLightbox(i) {
            this.$refs["lightbox_slider_" + i].open();
        },
    },
    mounted() {
        this.files = this.value || [];
    },
    updated() {
        if (this.files != this.value) this.files = this.value || [];
    },
    components: {
        Swiper,
        SwiperSlide,
        Lightbox,
    },
};
</script>
