{% load static %}
{% load i18n %}
{% load bloomerp %}

<!--Workspace-->
<div class="row" id="contentLayoutContainer">
    {% for item in workspace.content.content %}
        {% workspace_item item %}
    {% endfor %}
</div>
<!--End workspace-->

{% if perms.bloomerp.change_workspace %}
<!--Update workspace-->
<div class="d-flex justify-content-end gap-2">
    <button href="#" class="btn btn-sm btn-outline-primary" onclick="changeLayout()">
        Change layout
    </button>
</div>
<!--End update workspace-->



<!--Save layout div-->
<div class="d-none save-layout-div d-flex gap-2">
    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addItemModal">Add items</button>
    <button class="btn btn-primary" onclick="saveLayout('{{ workspace.pk }}')">Save layout</button>
    <button class="btn btn-danger" data-bs-toggle="modal" data-bs-target="#resetLayoutModal">Reset layout</button>
    <button class="btn btn-secondary" onclick="changeLayout()">Cancel</button>
</div>
<!--End save layout div-->

<!--Add item modal-->
<div
    class="modal fade"
    id="addItemModal"
    tabindex="-1"
    data-bs-backdrop="static"
    data-bs-keyboard="false"
    role="dialog"
    aria-labelledby="addItemModalTitle"
    aria-hidden="true"
>
    <div
        class="modal-dialog modal-dialog-scrollable modal-dialog-centered modal-lg"
        role="document"
    >
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="addItemModalTitle">
                    Dashboard item
                </h5>
                <button
                    type="button"
                    class="btn-close"
                    data-bs-dismiss="modal"
                    aria-label="Close"
                ></button>
            </div>
            <form 
                hx-get="{% url 'components_create_workspace_item' %}?action=get_snippet"
                hx-target=".new-workspace-item"
                hx-swap="outerHTML"
            >
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="" class="form-label">Dashboard item type</label>
                        <select
                            class="form-select"
                            name="item_type"
                            hx-get="{% url 'components_create_workspace_item' %}?action=get_input_field"
                            hx-target="#workspaceItemInput"
                            hx-swap="innerHTML"
                            id="dashboardItemType"
                        >
                            <option selected>Select one</option>
                            <option value="text">Text</option>
                            <option value="header">Header</option>
                            <option value="link">Link</option>
                            <option value="link_list">Link list</option>
                            <option value="widget">Widget</option>
                            <option value="sql_query_filter">SQL Query Filters</option>
                        </select>
                    </div>
                    
                    <!--Input size-->
                    <div class="mb-3">
                        <label for="" class="form-label">Size</label>
                        <input
                            type="number"
                            class="form-control"
                            name="size"
                            placeholder="Size"
                            max="12"
                            min="1"
                            value="12"
                            >
                    </div>
                    <!--End input size-->

                    <!-- Input fields changing based on input -->
                    <div id="workspaceItemInput">

                    </div>
                    <!-- End input fields changing based on input -->
                </div>
                <div class="modal-footer">
                    <button
                        type="button"
                        class="btn btn-secondary"
                        data-bs-dismiss="modal"
                    >
                        Close
                    </button>
                    <button type="submit" class="btn btn-primary">Insert</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!--Reset layout modal-->
<div
    class="modal fade"
    id="resetLayoutModal"
    tabindex="-1"
    data-bs-backdrop="static"
    data-bs-keyboard="false"
    role="dialog"
    aria-labelledby="resetLayoutModalTitle"
    aria-hidden="true"
>
    <div
        class="modal-dialog modal-dialog-scrollable modal-dialog-centered"
        role="document"
    >
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="resetLayoutModalTitle">
                    Reset layout
                </h5>
                <button
                    type="button"
                    class="btn-close"
                    data-bs-dismiss="modal"
                    aria-label="Close"
                ></button>
            </div>
            <div class="modal-body">
                <p>
                    Are you sure you want to reset the layout?
                </p>
            </div>
            <div class="modal-footer">
                <button
                    type="button"
                    class="btn btn-secondary"
                    data-bs-dismiss="modal"
                >
                    Close
                </button>
                <button
                    type="button"
                    class="btn btn-danger"
                    hx-post="{% url 'components_reset_workspace' %}"
                    hx-vals='{"workspace_id": "{{ workspace.pk }}"}'
                    hx-headers='{"X-CSRFToken": "{{ csrf_token }}"}'
                    hx-on:htmx:after-request="document.location.reload()"
                >
                    Reset layout
                </button>
            </div>
        </div>
    </div>
</div>
<!--End reset layout modal-->

<script>
    function changeLayout() {
        document.querySelectorAll('.workspace-item').forEach(element => {
            element.classList.toggle('border');
            element.classList.toggle('rounded');
        });

        document.querySelectorAll('.item-settings-div').forEach(element => {
            element.classList.toggle('d-none');
        });

        document.querySelector('.save-layout-div').classList.toggle('d-none');

        createNewItemDiv();
    }
    
    function resizeItem(id, type, customSize) {
        if (type == 'custom' && !customSize) {
            return
        }


        // Get the parent row
        let col = document.getElementById(id);

        // Parse the col class from the element that starts with 'col-'
        let colClass = col.className.match(/col-md-\d+/)[0];
        
        // Get the number of the col
        let colNumber = parseInt(colClass.split('-')[1]);
        

        // Check if the type is shrink or expand
        if (type == 'shrink') {
            // Check if the col number is greater than 1
            if (colNumber > 1) {
                // Decrease the col number by 1
                colNumber -= 1;
            }
        } else if (type == 'expand') {
            // Check if the col number is less than 12
            if (colNumber < 12) {
                // Increase the col number by 1
                colNumber += 1;
            }
        } else if (type == 'custom') {
            // Check if the custom size is between 1 and 12
            if (customSize >= 1 && customSize <= 12) {
                // Set the col number to the custom size
                colNumber = customSize;
            }
        }

        // Remove the old col class
        col.classList.remove(colClass);

        // Add the new col class
        col.classList.add(`col-md-${colNumber}`);

    }

    function deleteItem(element) {
        element.closest('.workspace-item').remove();
    }

    function moveItem(element, direction) {
        const item = element.closest('.workspace-item');

        if (direction === 'up' && item.previousElementSibling) {
            item.parentNode.insertBefore(item, item.previousElementSibling);
        } else if (direction === 'down' && item.nextElementSibling) {
            item.parentNode.insertBefore(item.nextElementSibling, item);
        }
    }

    function getItemSize(element) {
        let col = element.closest('.workspace-item');
        let colClass = col.className.match(/col-md-\d+/)[0];
        let colNumber = parseInt(colClass.split('-')[2]);

        if (!colNumber) {
            return 12
        }

        return colNumber;
    }

    function saveLayout(workspaceId) {
        let layout = [];

        // Get all the workspace items
        document.querySelectorAll('.workspace-item').forEach(item => {
            // Get the size
            let size = getItemSize(item);
            

            // Get the type
            let type = item.getAttribute('type');

            // Get the data based on the type
            let data = {};
            
            switch(type) {
                case 'text':
                    data = {
                        type: type,
                        size: size,
                        data: {
                            text: item.querySelector('.col-content').textContent
                        }
                    }
                    break;
                case 'header':
                    data = {
                        type: type,
                        size: size,
                        data: {
                            text: item.querySelector('.card-title').textContent
                        }
                    }
                    break;
                case 'link':
                    // Get the link id from the link element
                    let link = item.querySelector('.link-item')

                    if (link) {
                        linkId = linkId.getAttribute('link-id');

                        data = {
                            type: type,
                            size: size,
                            data: {
                                link_id: linkId
                            }
                        }
                    }

                    break;
                case 'link_list':
                    // Get all the link ids from the link elements
                    let links = [];
                    item.querySelectorAll('.link-item').forEach(link => {
                        link_id = link.getAttribute('link-id');
                        if (link_id) {
                            links.push(link_id);
                        }
                    });

                    data = {
                        type: type,
                        size: size,
                        data: {
                            links: links
                        }
                    }
                    break;
                case 'widget':
                    // Get the widget id from the widget element
                    let widgetId = item.querySelector('.card').getAttribute('widget-id');

                    data = {
                        type: type,
                        size: size,
                        data: {
                            widget_id: widgetId
                        }
                    }
                    break;
                case 'spacer':
                    data = {
                        type: type,
                        size: size,
                        data: {}
                    }
                    break;
            }
            // Only push the data if it is not empty
            if (Object.keys(data).length !== 0) {
                layout.push(data);
            }
        });



        // Send the layout to the server
        let url = '{% url "workspaces-detail" workspace.pk %}'


        fetch(url, {
            method: 'PATCH',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': '{{ csrf_token }}'},
            body: JSON.stringify({content: {content: layout}})
        }).then(response => {
            if (response.ok) {
                showMessage('Layout saved successfully', 'success');
                changeLayout();

            } else {
                showMessage('Error saving layout','danger');
            }
        });
    }
    
    function createNewItemDiv() {
        // Check if the new item div already exists
        if (document.querySelector('.new-workspace-item')) {
            return;
        }
        let newItemDiv = document.createElement('div');
        newItemDiv.setAttribute('id', 'newItemDiv');
        newItemDiv.classList.add('new-workspace-item');
        // Append the new item div to the content layout container
        document.getElementById('contentLayoutContainer').appendChild(newItemDiv);
    }

    addItemModal = document.getElementById('addItemModal');
    addItemModal.addEventListener('show.bs.modal', function (event) {
        // Button that triggered the modal
        let button = event.relatedTarget;

        // Create the new item div
        createNewItemDiv();
    });

    // HTMX after request
    document.addEventListener('htmx:afterRequest', function(event) {
        if (event.detail.target.id == 'newItemDiv') {
            // Make it so that the new item div is edited
            document.querySelectorAll('.workspace-item').forEach(item => {
                item.classList.add('border');
                item.classList.add('rounded');
            });

            document.querySelectorAll('.item-settings-div').forEach(item => {
                item.classList.remove('d-none');
            });

            // Show message
            showMessage('Item added successfully', 'success');

            // Create the new item div
            createNewItemDiv();
        }
    });

</script>
{% endif %}