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

const serverRequest = {
    "serverSide": true,
    "responsive": true,
    "ajax": {
        "url": "api/Users",
        "type": "POST",
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    },
    "columns": [
        {"data": "username"},
        {"data": "user_date"},
        {"data": "user_action"}
    ]
}

export default function users(table) {
    if (table) {
        tables(serverRequest)
        createUser()
    } else {
        profile()
    }
}

const tables = (serverRequest) => {
    dataTables(serverRequest)
}

const profile = () => {
    if (setupPasswordConfirmationEventListeners()) {
        request()
    }
}

const setupPasswordConfirmationEventListeners = () => {
    const passwordBefore = document.querySelector("input[name='password_before']");
    const passwordAfter = document.querySelector("input[name='password_after']");
    const userCode = document.querySelector("input[name='userCode']").value;
    const btn = document.getElementById("profileBtn");
    const confirmMessage = document.getElementById("confirm_message");
    const removeMessageClassesAndText = () => {
        confirmMessage.classList.remove("d-inline-block", "border-danger", "text-danger");
        confirmMessage.classList.add("d-none");
        confirmMessage.innerText = "";
    };
    const handlePasswordBeforeInput = (evt) => {
        if (evt.target.value.trim().length > 0) {
            const password = evt.target.value;
            postJson("api/PasswordConfirm", { userCode, password }).then((result) => {
                if (result?.profileConfirm) {
                    removeMessageClassesAndText();
                    passwordAfter.disabled = false;
                    btn.disabled = false;
                } else {
                    confirmMessage.classList.remove("d-none");
                    confirmMessage.classList.add("d-inline-block", "border-danger", "text-danger");
                    confirmMessage.innerText = "Girmiş olduğunuz şifre eşleşmior mevcut şifre ile";
                    passwordAfter.disabled = true;
                    btn.disabled = true;
                }
            });
            return true;
        }
        removeMessageClassesAndText();
        btn.disabled = false;
        return true;
    };
    passwordBefore.addEventListener("blur", handlePasswordBeforeInput);
    passwordBefore.addEventListener("input", handlePasswordBeforeInput);
    passwordBefore.addEventListener("click", handlePasswordBeforeInput);
    return true
};
const request = () => {
    const form = document.getElementById("profile");
    const btn = document.getElementById("profileBtn");
    btn.addEventListener("click", (evt) => {
        evt.preventDefault();
        loading(true)
        const data = new FormData(form)
        const token = document.querySelector("meta[name='csrf-token']").content
        data.append("token", token)
        post("admin/profile", data).then(response => {
            loading(false)
            notify(response?.conclusion, response?.message, response?.url, response?.timeout)
        })
    })
}


const createUser = () => {
    const btnCreateUser = document.getElementById("createUser");
    btnCreateUser.addEventListener("click", async () => {
        const langGet = await customLang("admin", "users");
        const lang = langGet.modal;
        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">
                       <form class="col-xl-12 col-xs-12 col-sm-12 col-md-12 col-lg-12" id="formatter" method="post">
                            <div class="row">
                                <div class="col-xl-12 col-xs-12 col-sm-12 col-md-12 col-lg-12">
                                    <div class="form-group">
                                        <label for="username">
                                            ${lang?.username_text}
                                        </label>
                                        <input type="text" id="username" name="username" class="form-control" value="">
                                    </div>
                                    <div class="form-group">
                                        <label for="password">
                                            ${lang?.user_password_text}
                                        </label>
                                        <input type="password" id="password" name="password" class="form-control" value="">
                                    </div>
                                </div>
                                
                           </div>
                           <input type="hidden" name="token" class="form-control" value="${token}">
                        </form>
                    </div>
                </div>`;
        buttonTextOkay = `${lang?.buttonTextOkay}`
        buttonTextCanceled = `${lang?.buttonTextCanceled}`
        buttonColorOkay = 'green'
        buttonColorCanceled = 'red'
        footer = `${lang?.footerText}`;
        await sweetModal(label, form, buttonTextOkay, buttonTextCanceled, buttonColorOkay, buttonColorCanceled, footer,  "api/UserCreate")

    })
}