import Ajax from "./ajax.js"
import Modal from "./modal.js"
import ClassSelect from "./select2.js"

const getInitials = (name) => name.split(" ").map(e => e.charAt(0)).join("")
const hebraList = (message) => `
<div class="list-group-item list-group-item-action d-flex align-items-center cursor-pointer">
    <div class="avatar avatar-md px-2 py-2">
        <img src="https://gravatar.com/avatar/${message.user?.avatar}?s=40" class="rounded-circle"></img>
    </div>
    <div class="w-100 px-4">
        <div class="d-flex flex-column">
            <div class="d-flex align-items-center">
            <p class="px-1">
            <span class="ti ti-xs ti-clock"></span>
            </p>
            <p class="px-1">
            ${message.created_at}
            </p>    
                <h6>
                    ${message.user.first_name} ${message.user.last_name} (${message.user.username})
                </h6>
            </div>
            <p class="text-start">${message.message}</p>
        </div>
    </div>
</div>
`
const hebraUsersList = (user) => `
    <div class="avatar avatar-md px-2 py-2" title="${user.first_name + " " + user.last_name}">
        <img src="https://gravatar.com/avatar/${user.avatar}?s=40" class="rounded-circle"></img>
    </div>`

class InternalMessages {
    constructor(domItem) {
        this.item = domItem
        this.containerMessages = this.item.find("#container-internal-messages")
        this.btnNewHebra = this.item.find(".btn-new-hebra")
        this.btnNewHebraMessage = this.item.find(".btn-new-hebra-message")
        this.modalNewMessage = new Modal($("#modalNewInternalMessage"))
        this.selectUsers = this.item.find("#selectUsersHebra")
        this.btnNewHebraSubmit = this.item.find("#submit_new_hebra")
        this.textAreaMessage = this.item.find("#new-internal-message-text")
        this.hebraTitle = this.item.find("#new-internal-message-title")
        this.btnUpdateHebraSubmit = this.item.find("#submit_update_hebra")
        this.message = ""
        this.formNewValues = ""
        this.formUpdateValues = ""
        this.subjectHebra = ""
        this.modelId = this.item.data("id")
        this.type = this.item.data("type")
        this.chatId = null

        this.selectMessageUsers = new ClassSelect(this.selectUsers, '/chat/users/internal', "Seleccione un usuario", true)
    }
    init() {
        this.selectMessageUsers.init()
        this.item.on("click", ".btn-new-hebra", this.handleBtnNewHebra.bind(this))
        this.item.on("click", ".btn-new-hebra-message", this.handleBtnUpdateHebra.bind(this))
        this.modalNewMessage.item.on("click", "#submit_new_hebra", this.handlePostNewHebra.bind(this))
        this.modalNewMessage.item.on("click", "#submit_update_hebra", this.handleUpdateHebra.bind(this))
        this.handleGetInternalMessages()

    }
    handleGetInternalMessages() {
        this.containerMessages.empty()
        let ajax = new Ajax(
            `/chat/hebra/${this.type}/${this.modelId}`,
            null,
            null,
            this._handleGetInternalMessagesSuccess.bind(this),
            this._handleGetInternalMessagesError.bind(this)
        )
        ajax.get()
    }
    handlePostNewHebra() {
        this._handleUpdateFormNewHebraValues()
        let ajax = new Ajax(
            `/chat/hebra/${this.type}`,
            this.formNewValues,
            null,
            this.handlePostNewHebraSuccess.bind(this),
            this.handlePostNewHebraError.bind(this),
        )
        ajax.post()

    }
    handlePostNewHebraSuccess(data) {
        this.modalNewMessage.toggle()
        this.handleGetInternalMessages()
    }
    handlePostNewHebraError(err) { }
    handleUpdateHebra() {
        this._handleUpdateFormUpdateHebraValues()
        let ajax = new Ajax(
            `/chat/hebra/${this.chatId}`,
            this.formUpdateValues,
            null,
            this.handleUpdateNewHebraSuccess.bind(this),
            this.handleUpdateNewHebraError.bind(this),
        )
        ajax.post()
    }
    handleUpdateNewHebraSuccess(data) {
        this.modalNewMessage.toggle()
        this.handleGetInternalMessages()
    }
    handleUpdateNewHebraError(err) { }
    handleBtnNewHebra(e) {
        e.preventDefault()
        this.chatId = null
        this.modalNewMessage.item.find(".modal-title").text("Nuevo hilo")
        this.selectMessageUsers.reset()
        this.textAreaMessage.val("")
        this.hebraTitle.val("")
        this.hebraTitle.parent().removeClass("d-none")
        this.btnNewHebraSubmit.removeClass("d-none")
        this.btnUpdateHebraSubmit.addClass("d-none")
        this.modalNewMessage.show()
        this._handleUpdateFormNewHebraValues()
    }
    handleBtnUpdateHebra(e) {
        e.preventDefault()
        this.chatId = $(e.currentTarget).data("id")
        this.selectMessageUsers.reset()
        this.textAreaMessage.val("")
        this.hebraTitle.val("")
        this.hebraTitle.parent().addClass("d-none")
        this.modalNewMessage.item.find(".modal-title").text("Nuevo mensaje")
        this.btnUpdateHebraSubmit.removeClass("d-none")
        this.btnNewHebraSubmit.addClass("d-none")
        this.modalNewMessage.show()
        this._handleUpdateFormUpdateHebraValues()

    }
    _handleUpdateFormNewHebraValues() {
        this.formNewValues = {
            title: this.hebraTitle.val(),
            users: this.selectMessageUsers.getVal(),
            message: this.textAreaMessage.val(),
            modelId: this.modelId
        }
    }
    _handleUpdateFormUpdateHebraValues() {
        this.formUpdateValues = {
            users: this.selectMessageUsers.getVal(),
            message: this.textAreaMessage.val(),
            modelId: this.modelId
        }
    }
    _handleGetInternalMessagesSuccess(data) {
        Object.values(data).map((k) => {
            this._addHebraDOM(k.id, k.title, k.messages, k.internalUsers)
        })
    }
    _handleGetInternalMessagesError(err) { }

    _addHebraDOM(key, chatTitle, messages, users) {
        const itemHebra = $(`<div id="hebra-item-${key}"></div>`).addClass("border border-container flex-grow-0 container-p-y mt-4 p-5")
        const headerHebra = $("<div></div>").addClass("d-flex justify-content-between align-items-center")
        const contentHeaderHebra = $("<h4></h4>").text(`${chatTitle}`)
        const btnNewHebra = $("<button></button>").attr("type", "button").addClass("btn btn-danger btn-sm btn-new-hebra")
        btnNewHebra.append('<span class="ti-xs ti ti-git-branch"></span>')
        btnNewHebra.append("Nuevo hilo")
        headerHebra.append(contentHeaderHebra, btnNewHebra)
        itemHebra.append(headerHebra)
        let itemMessagesHebraRow = $("<div></div>").addClass("row")
        let itemMessagesHebraCol = $("<div></div>").addClass("col")
        let itemMessagesListGroup = $("<div></div>").addClass("list-group")
        itemMessagesHebraRow.append(itemMessagesHebraCol)
        itemMessagesHebraCol.append(itemMessagesListGroup)
        let itemFooterHebra = $("<div></div>").addClass("d-flex justify-content-between align-items-center")
        let itemFooterUserFlex = $("<div></div>").addClass("d-flex justify-content-start ")
        let itemFooterHebraUserFlexChildren = $("<div></div>").addClass("d-flex align-items-center avatar-group mb-4 mt-4")
        itemFooterUserFlex.append(itemFooterHebraUserFlexChildren)
        itemFooterHebra.append(itemFooterUserFlex)
        users.map((user) => {
            let avatarUsers = hebraUsersList(user)
            itemFooterHebraUserFlexChildren.append(avatarUsers)
        })
        itemFooterHebra.append(`
            <button class="btn btn-primary btn-md waves-effect waves-light btn-new-hebra-message" data-id="${key}">
                <span class="ti-xs ti ti-message-2 me-1"></span>
                Nuevo mensaje
            </button>
            `)
        messages.map((message) => {
            let messageContent = hebraList(message)
            itemMessagesListGroup.append(messageContent)
        })
        itemHebra.append(itemMessagesListGroup)
        itemHebra.append(itemFooterHebra)
        this.containerMessages.append(itemHebra)
    }
}

export default InternalMessages;