import {post} from "../utils/Request.js";
import {loading, notify} from "../utils/Notiflix.js";

const settings = () => {
    tabsLang()
    dropFiy()
    request()
}

const getIsActiveName = (isActiveName = "") => {
    if (isActiveName === "") {
        return sessionStorage.getItem("isActiveName")
    }
    sessionStorage.removeItem("isActiveName")
    sessionStorage.setItem("isActiveName", isActiveName)
    return sessionStorage.getItem("isActiveName")
}

const request = () => {
    const forms = document.querySelectorAll("form[id]");
    Array.from(forms).forEach(form => {
            form.addEventListener("submit", (evt) => {
                evt.preventDefault();
                loading(true)
                const data = new FormData(form);
                data.append("setting_lang", form.id.replace("form_", ""))
                const token = document.querySelector("meta[name='csrf-token']").content
                data.append("token", token)
                post("admin/settings", data).then(response => {
                    loading(false)
                    notify(response?.conclusion, response?.message, response?.url, response?.timeout)
                })

            })

    })

}

function tabsLang() {
    const listTabs = document.getElementById("list-tabs");
    const lis = Array.from(listTabs.children);
    lis.forEach(li => {
        liCheckedActiveControl(li)
        li.addEventListener("click", (e) => {
            const hashReplace = e.target.hash.replace("#", "")
            const isImagesCheckedControl = hashReplace.includes("images")
            if (!isImagesCheckedControl) {
                getIsActiveName(hashReplace)
                formActive(hashReplace)
            } else {
                getIsActiveName("dropzone")
                formActive("dropzone")
            }

        })
    })
}

const formActive = (active) => {
    const formUnknownBtn = document.querySelector("button[data-action='formUnknown']");
    formUnknownBtn.setAttribute("form", `form_${active}`)

}

const liCheckedActiveControl = (li, isActiveName) => {
    if (li.children[0].classList.contains("active")) {
        const hashReplace = li.children[0].hash.replace("#", "")
        const isImagesCheckedControl = hashReplace.includes("images")
        if (!isImagesCheckedControl) {
            getIsActiveName(hashReplace)
            formActive(hashReplace)
        } else {
            getIsActiveName("dropzone")
            formActive("dropzone")
        }
    }
}

const dropFiy = () => {
    function initializeDropzone(dropzone, paramName, acceptedFiles) {
        let url = "admin/setting/";
        if (dropzone.id.includes("dropzone-logo")) {
            url += "logo";
        }
        if (dropzone.id.includes("dropzone-fav")) {
            url += "favicon";
        }
        dropzoneCreatInput(dropzone);
        const dropzoneOptions = {
            url,
            paramName,
            acceptedFiles,
            maxFilesize: 10,
            maxFiles: 1,
            dictRemoveFile: "Kaldır/Sil",
            autoProcessQueue: false,
            addRemoveLinks: true,
            uploadMultiple: false,
            thumbnailWidth: null,
            thumbnailHeight: null,
            init: function () {
                const currentDropzone = this;
                const lang = document.querySelector("html").lang;
                dropzonePreviewImage(currentDropzone, dropzone.id, lang);
                const dropzoneElement = document.querySelector(`#${dropzone.id}`);
                dropzoneElement.addEventListener("click", function () {
                    removeDropzonePreviewImage(currentDropzone)
                    currentDropzone.hiddenFileInput.click();
                    return false
                });

                currentDropzone.on("drop", function () {
                    removeDropzonePreviewImage(currentDropzone)
                });

                currentDropzone.on("addedfile", function () {
                    const checkboxes = document.querySelectorAll("input[data-checked-lang]");
                    checkboxes.forEach(checkbox => {
                        if (checkbox.name === currentDropzone.element.id) {
                            checkbox.disabled = false
                        }
                    })
                    if (this.files.length > 1) {
                        this.removeFile(this.files[0]);
                    }
                });

                currentDropzone.on("success", function (file, res) {
                    const response=JSON.parse(res)
                    notify(response?.conclusion, response?.message)

                    // Yükleme başarılı olduğunda çalışacak işlemler
                });

                currentDropzone.on("error", function (file, res) {
                    const response=JSON.parse(res)
                    notify(response?.conclusion, response?.message)
                    // Yükleme hatası olduğunda çalışacak işlemler
                });

                dropzoneRequest(currentDropzone)
            },
        };
        if (dropzone.id.includes("dropzone-logo")) {
            Dropzone.options.dropzoneLogo = dropzoneOptions;
        }
        if (dropzone.id.includes("dropzone-fav")) {
            Dropzone.options.dropzoneFav = dropzoneOptions;
        }

    }

    const dropzonePreviewImage = async (currentDropzone, dropzone, lang) => {

        let placeholderImage = '';
        let imageUrl = '';
        const data = new FormData()
        data.append("lang", lang)
        data.append("op", dropzone)
        const result = await post(`api/${dropzone}`, data)
        if (result.path === null) {
            if (lang === "tr") {
                if (dropzone === "dropzone-logo") {
                    placeholderImage = "600x400@2x-logo-tr.png";
                } else if (dropzone === "dropzone-fav") {
                    placeholderImage = "600x400@2x-ico-tr.png";
                } else {
                    placeholderImage = "600x400@2x-unkunow-tr.png";
                }
            } else if (lang === "en") {
                if (dropzone === "dropzone-logo") {
                    placeholderImage = "600x400@2x-logo-en.png";
                } else if (dropzone === "dropzone-fav") {
                    placeholderImage = "600x400@2x-ico-en.png";
                } else {
                    placeholderImage = "600x400@2x-unkunow-en.png";
                }
            } else {
                placeholderImage = "600x400@2x-unkunow-en.png";
            }

            imageUrl = `assets/admin/images/dropzone-placeholder/${placeholderImage}`;
        } else {
            imageUrl = result.path;
            placeholderImage = imageUrl;
        }


        const mockFile = {name: `${placeholderImage}`, size: 1024};
        currentDropzone.emit("addedfile", mockFile);
        currentDropzone.emit("thumbnail", mockFile, imageUrl);
        currentDropzone.emit("complete", mockFile);
    }

    const removeDropzonePreviewImage = (currentDropzone) => {

        if (currentDropzone.files.length > 0) {
            currentDropzone.removeFile(currentDropzone.files[0]);
        } else {
            if (currentDropzone.element.classList.contains("dz-started") && currentDropzone.element.children.length > 2) {
                currentDropzone.element.classList.remove("dz-started");
                if (currentDropzone.previewsContainer.children.length <= 3) {
                    currentDropzone.previewsContainer.lastChild.remove()
                } else {
                    [...currentDropzone.previewsContainer.children].forEach(prev => {
                        if (prev.classList.length > 1 && prev.classList.contains("dz-image-preview")) {
                            prev.remove()
                        }
                    })
                }
            }
        }
    };

    const dropzoneCreatInput = (dropzone) => {
        const submitButton = document.querySelector("button[form]");
        submitButton.addEventListener("mouseenter", (event) => {
            if (event.target.attributes.form.value === "form_dropzone") {
                const inputs = document.querySelectorAll(`input[name='${dropzone.id}[]']`)
                if (inputs.length > 0) {
                    inputs.forEach(input => {
                        input.remove()
                    })
                }
                langCheckList().find(list => {
                    if (list.name === dropzone.id) {
                        const langInput = document.createElement("input");
                        langInput.type = "hidden";
                        langInput.name = `${list.name}[]`;
                        langInput.value = list.dataset.checkedLang;
                        dropzone.append(langInput);

                    }
                })
            }

        });
        const tokenInput = document.createElement("input");
        tokenInput.type = "hidden";
        tokenInput.name = "token";
        tokenInput.value = document.querySelector("meta[name='csrf-token']").content;
        dropzone.append(tokenInput);
    }
    const dropzoneRequest = (currentDropzone) => {
        const submitButton = document.querySelector("button[form]");
        submitButton.addEventListener("mouseenter", (event) => {
            if (event.target.attributes.form.value === "form_dropzone") {
                const buttonForm = document.querySelector("button[type='submit']");
                buttonForm.addEventListener('click', function (event) {
                    event.preventDefault();
                    if (getIsActiveName() === "dropzone" && currentDropzone.files.length > 0) {
                        if (dropzoneRequestButtonMessage(langCheckList(), currentDropzone)) {
                            currentDropzone.processQueue();
                        }
                    }
                });
            }

        });
    }

    function langCheckList() {
        const checkboxes = document.querySelectorAll("input[data-checked-lang]");
        const checkedList = [];
        checkboxes.forEach((checkbox, i) => {
            if (checkbox.checked) {
                checkedList.push(checkbox)
                return checkedList
            }
        })
        return checkedList;
    }

    const dropzoneRequestButtonMessage = (langCheckList, dropzone) => {
        let conclusion = true;
        let conclusionWarn = false;
        if (dropzone.files.length > 0) {
            if (langCheckList.length <= 0) {
                conclusion = false;
                conclusionWarn = true;
            } else {

                let hasLanguage = langCheckList.some(langCheck => langCheck.name === dropzone.element.id);

                if (!hasLanguage) {
                    conclusion = false;
                    conclusionWarn = true;
                }
            }
        } else {
            conclusion = false;
        }

        if (conclusionWarn) {
            let position = "top center";

            $("button[type='submit']").notify(`Lütfen ${dropzone.previewsContainer.dataset.process} için en az 1 dili seçiniz`, {
                position,
                className: "warn"
            });
        }

        return conclusion;
    };

    const dropzoneLogo = document.getElementById('dropzone-logo');
    const dropzoneFav = document.getElementById('dropzone-fav');
    if (dropzoneLogo !== null) {
        initializeDropzone(dropzoneLogo, "logo", ".jpeg,.jpg,.png,.webp,.svg");
    }

    if (dropzoneFav !== null) {
        initializeDropzone(dropzoneFav, "favicon", ".ico,.jpeg,.jpg,.png,.webp,.svg");
    }
}


export default settings
