import {customLang, dataTables, dataTablesReload} from "../utils/AdminConfigure.js";
import {loading, notify} from "../utils/Notiflix.js";
import {postJson} from "../utils/Request.js";

const table = () => {
    const serverRequest = {
        "serverSide": true,
        "responsive": true,
        "ajax": {
            "url": "api/References",
            "type": "POST",
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        },
        "columns": [
            {"data": "ref_file_path"},
            {"data": "title"},
            {"data": "description"},
            {"data": "ref_action"}
        ]
    };

    dataTables(serverRequest);
}

const modal = () => {
    const buttons = document.querySelectorAll(".modal-open-ref");
    // let buttonsUpdate = [];
    let creatButton
    buttons.forEach((button, index) => {
        if (button.dataset.op === "createReference") {
            creatButton = button
        } else {
            // buttonsUpdate.push(button)
        }
    })

    creatModal(creatButton)
    // updateModal(buttonsUpdate)
}
const creatModal =  (button) => {
    button.addEventListener("click", async () => {
        const langGet = await customLang("admin", "references");
        let lang = langGet.modal.create
        let form;
        let label;
        let buttonTextOkay;
        let buttonTextCanceled;
        let buttonColorOkay;
        let buttonColorCanceled;
        let footer;
        const token = document.querySelector("meta[name='csrf-token']").content
        label = `${lang?.textLabel}`
        form = `
            <div class="container">
                <div class="row">
                    <div class="col-xl-12 col-xs-12 col-sm-12 col-md-12 col-lg-12">
                        <div class="row">
                            <div class="col-xl-12 col-xs-12 col-sm-12 col-md-12 col-lg-12">
                                <form id="formatter" class="dropzone" method="post">
                                    <div class="dz-message">
                                    ${lang?.dzMessage}
                                    </div>
                                    <div id="inputus"></div>
                                </form>
                            </div>
                            <div class="col-xl-12 col-xs-12 col-sm-12 col-md-12 col-lg-12 mt-4">
                                <!-- Nav tabs -->
                                <ul class="nav nav-tabs p-0 mb-3">
                                    <li class="nav-item"><a class="nav-link active" data-toggle="tab" href="#tr">TR</a></li>
                                    <li class="nav-item"><a class="nav-link" data-toggle="tab" href="#en">EN</a></li>
                                </ul>
                                <!-- Tab panes -->
                                <div class="tab-content">
                                    <div role="tabpanel" class="tab-pane in active" id="tr">
                                        <div class="form-group">
                                            <label for="brandName_tr">
                                                ${lang?.labels?.brand_name_text_tr}
                                            </label>
                                            <input type="text" id="brandName_tr" name="brandName_tr" class="form-control">
                                        </div>
                                        <div class="form-group">
                                            <label for="brandDescription_tr">
                                                ${lang?.labels?.brand_description_text_tr}
                                            </label>
                                            <div class="form-line">
                                                <textarea name="brandDescription_tr" rows="4" class="form-control no-resize" id="brandDescription_tr"></textarea>
                                            </div>
                                        </div>
                                    </div>
                                    <div role="tabpanel" class="tab-pane" id="en">
                                        <div class="form-group">
                                            <label for="brandName_en">
                                                ${lang?.labels?.brand_name_text_en}
                                            </label>
                                            <input type="text" id="brandName_en" name="brandName_en" class="form-control">
                                        </div>
                                        <div class="form-group">
                                            <label for="brandDescription_en">
                                                ${lang?.labels?.brand_description_text_en}
                                            </label>
                                            <div class="form-line">
                                                <textarea name="brandDescription_en" rows="4" class="form-control no-resize" id="brandDescription_en"></textarea>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <input type="hidden" name="token" class="form-control" value="${token}">
                    </div>
                </div>
            </div>
            
        `;
        buttonTextOkay = `${lang?.buttonTextOkay}`
        buttonTextCanceled = `${lang?.buttonTextCanceled}`
        buttonColorOkay = 'green'
        buttonColorCanceled = 'red'
        footer = `${lang?.footerText}`;
        Swal.fire({
            title: label,
            html: form,
            footer: footer,
            confirmButtonText: buttonTextOkay,
            confirmButtonColor: buttonColorOkay,
            cancelButtonText: buttonTextCanceled,
            cancelButtonColor: buttonColorCanceled,
            showCancelButton: true,
            didOpen: (ev) => {
                const childrenList = ev.children;
                let confirmElement;
                childrenList.forEach(children => {
                    if (children.classList.value.includes("swal2-actions")) {
                        children.children.forEach(confirmBtn => {
                            if (confirmBtn.classList.contains("swal2-confirm")) {
                                confirmElement = confirmBtn;
                            }
                        })
                    }
                })
                dropzoneFunc(confirmElement)
                refTranslateControl(lang)
            }
        })

    });
}
const dropzoneFunc = (confirmBtn) => {
    function initializeDropzone(dropzone, confirmBtn, paramName, acceptedFiles) {
        let url = "admin/reference";
        dropzoneCreatInput(dropzone, confirmBtn);
        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 () {

                    if (this.files.length > 1) {
                        this.removeFile(this.files[0]);
                    }
                    updateConfirmButtonStatus(confirmBtn, currentDropzone.files.length > 0);
                });

                currentDropzone.on("removedfile", function () {
                    updateConfirmButtonStatus(confirmBtn, currentDropzone.files.length > 0);
                });

                currentDropzone.on("success", function (file, res) {
                    const response = JSON.parse(res)
                    loading(false)
                    dataTablesReload()
                     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)
                    loading(false)
                    notify(response?.conclusion, response?.message)
                    // Yükleme hatası olduğunda çalışacak işlemler
                });

                dropzoneRequest(currentDropzone, confirmBtn)
            },
        };
        if (dropzone.id.includes("formatter")) {
            new Dropzone("#formatter", dropzoneOptions);
        }
    }

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

            // 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 placeholderImage = "600x400@2x-logo-tr.png";

            const imageUrl = `assets/admin/images/dropzone-placeholder/${placeholderImage}`;

            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 updateConfirmButtonStatus = (confirmBtn, isEnabled) => {
        confirmBtn.disabled = !isEnabled;
    }

    const dropzoneCreatInput = (dropzone, confirmBtn) => {
        confirmBtn.addEventListener("mouseenter", () => {
            const InputsContent = dropzone.children.inputus;
            InputsContent.innerHTML = "";
            const brandNameTr = document.getElementById("brandName_tr");
            const brandDescriptionTr = document.getElementById("brandDescription_tr");
            const brandNameEn = document.getElementById("brandName_en");
            const brandDescriptionEn = document.getElementById("brandDescription_en");
            const elements = [brandNameTr, brandDescriptionTr, brandNameEn, brandDescriptionEn];
            elements.map(element => {
                if (element.value.trim().length > 0) {
                    const createInput = document.createElement("input");
                    createInput.type = 'hidden'
                    createInput.name = element.name;
                    createInput.value = element.value;
                    InputsContent.append(createInput)
                }
            });
            const tokenInput = document.createElement("input");
            tokenInput.type = "hidden";
            tokenInput.name = "token";
            tokenInput.value = document.querySelector("meta[name='csrf-token']").content;
            InputsContent.append(tokenInput)
        });
    }

    const dropzoneRequest = (currentDropzone, confirmBtn) => {
        confirmBtn.addEventListener('click', function (event) {
            event.preventDefault();
            loading(true)
            currentDropzone.processQueue();
        });
    }

    const dropzoneFormatter = document.getElementById('formatter');
    if (dropzoneFormatter !== null) {
        initializeDropzone(dropzoneFormatter, confirmBtn, "referenceLogo", ".jpeg,.jpg,.png,.webp,.svg");
        updateConfirmButtonStatus(confirmBtn, dropzoneFormatter.dropzone.files.length > 0);
    }
}

const refTranslateControl = (lang) => {
    const langText=lang
    const brandNameTr = document.getElementById("brandName_tr");
    const brandDescriptionTr = document.getElementById("brandDescription_tr");
    const brandNameEn = document.getElementById("brandName_en");
    const brandDescriptionEn = document.getElementById("brandDescription_en");
    const elements = [brandNameTr, brandDescriptionTr, brandNameEn, brandDescriptionEn];
    const createdButtons = [];
    elements.map(element => {
        element.addEventListener("input", (ev) => {
            const elementLang = ev.target.name.split("_")[1];
            elements.map(el => {
                if (el.name.split("_")[1] !== elementLang) {
                    const langId = el.name.split("_")[1] === "tr" ? "tr" : "en";
                    if (el.value.trim().length <= 0) {
                        if (!createdButtons.includes(langId)) {
                            const contentTab = document.getElementById(langId);
                            const createTranslateButton = document.createElement("button");
                            createTranslateButton.type = "button";
                            createTranslateButton.classList.add("btn", "btn-success", "col-4", "m-2");
                            createTranslateButton.setAttribute("data-lang", langId);
                            createTranslateButton.innerText = langText?.createTranslateButtonText ;
                            createTranslateButton.addEventListener("click", () => {
                                let lang;
                                if (langId === "en") {
                                    lang = "tr";
                                } else {
                                    lang = "en"
                                }
                                refRequestTranslate(langText,lang, langId, elements, createdButtons)
                            });
                            contentTab.prepend(createTranslateButton);
                            createdButtons.push(langId);
                        }
                    } else {
                        if (createdButtons.includes(langId)) {
                            const contentTab = document.getElementById(langId);
                            const existingButtons = contentTab.getElementsByClassName("btn-success");
                            for (let i = 0; i < existingButtons.length; i++) {
                                existingButtons[i].remove();
                            }
                            const index = createdButtons.indexOf(langId);
                            createdButtons.splice(index, 1);
                        }
                    }
                }
            });
        });
    });

    const refRequestTranslate = (langText,lang, toLang, elements, createdButtons) => {
        loading(true)
        const beforeElements = [];
        const afterElements = [];

        elements.forEach(element => {
            if (element.name.split("_")[1].includes(lang) && element.value.trim().length > 0) {
                beforeElements.push(element)
                const elementName = element.name.split("_")[0]
                elements.forEach(element => {
                    if (element.name.split("_")[0].includes(elementName) && element.name.split("_")[1].includes(toLang) && element.value.trim().length <= 0) {
                        afterElements.push(element)
                    }
                })
            }
        })

        if (afterElements.length <= 0) {
            if (createdButtons.includes(toLang)) {
                const contentTab = document.getElementById(toLang);
                const existingButtons = contentTab.getElementsByClassName("btn-success");
                for (let i = 0; i < existingButtons.length; i++) {
                    existingButtons[i].remove();
                }
                const index = createdButtons.indexOf(toLang);
                createdButtons.splice(index, 1);
                notify("info", `${langText?.messageInfo}`)
                loading(false)

            }
        } else {
            beforeElements.map(async (before, index) => {
                loading(true);

                const translateText = before.value;

                const dataJson = {translateText, toLang};

                const translate = await postJson("api/ReferenceTranslate", dataJson);

                if (translate?.boolean) {
                    afterElements[index].value = translate?.data?.data?.translations[0]?.translatedText;
                    loading(false);
                    notify("success", `${langText.messageInfo_2}`);
                } else {
                    loading(false)
                    notify("info", `${langText.messageInfo_3}`)
                }
            })
        }
    }
}

export default function references() {
    table();
    modal()


}