import { Controller } from "@hotwired/stimulus";

export default class extends Controller {
    static targets = ["input", "preview", "loader"];

    connect() {
        this.element.addEventListener("dragover", this.dragOver.bind(this));
        this.element.addEventListener("dragleave", this.dragLeave.bind(this));
        this.element.addEventListener("drop", this.drop.bind(this));

        this.inputTarget.addEventListener("change", (event) => {
            this.handleFiles(this.inputTarget.files);
        });
    }

    dragOver(event) {
        event.preventDefault();
        this.element.classList.add("border-amber-600");
    }

    dragLeave(event) {
        event.preventDefault();
        this.element.classList.remove("border-amber-600");
    }

    drop(event) {
        event.preventDefault();
        this.element.classList.remove("border-amber-600");
        this.handleFiles(event.dataTransfer.files);
    }

    handleFiles(files) {
        const formData = new FormData();
        this.previewTarget.innerHTML = "";

        Array.from(files).forEach((file) => {
            formData.append("file-upload[]", file);

            const reader = new FileReader();
            reader.onload = (e) => {
                const img = document.createElement("img");
                img.src = e.target.result;
                img.className = "h-24 w-24 object-cover rounded border";
                this.previewTarget.appendChild(img);
            };
            reader.readAsDataURL(file);
        });

        this.uploadFiles(formData);
    }

    async uploadFiles(formData) {
        this.loaderTarget.style.display = "block";

        try {
            await fetch("/admin/image/upload", {
                method: "POST",
                body: formData,
            });
        } catch (err) {
            console.error("Upload error:", err);
        } finally {
            this.loaderTarget.style.display = "none";
        }
    }
}
