//Alpine
document.addEventListener('alpine:init', () => {

    Alpine.data("sortGateways", ()=>({
        pageLoaderIsActive: false,

        //table data
        tableData: [],
        tableLoaderIsActive: false,

        //modals
        modals: {
            delete: {
                active: false,
                gateway: null
            },
        },

        //page data
        gatewaysTableEl: null,

        async init(){
            await this.getPageData();
            this.gatewaysTableEl = document.getElementById("gatewaysTable");

            let htmlTemp = "";
            for (const item of this.tableData) {
                htmlTemp += await this.generateGatewayRow(item);
            }

            this.gatewaysTableEl.innerHTML = htmlTemp;

            const sortable = new Draggable.Sortable(this.gatewaysTableEl, {
                draggable: '.gateway-row',
                handle: '.btn-handle',
                mirror: {
                    constrainDimensions: true,
                },
            });

            const submitFunction = ()=>{
                this.submit();
            }
            sortable.on('drag:stop', () => {
                setTimeout(()=>{
                    submitFunction()
                }, 100)
            });

        },

        //request functions
        async getPageData(){
            this.tableLoaderIsActive = true;

            try{

                const result = await apiRequest('gateland/gateway/index', {
                    method: 'POST',
                })

                if(result.success){
                    const data = result.data;
                    this.tableData = data.gateways;
                }else{
                    notyf.error(result.message ? result.message : 'حطایی رخ داده است!');
                    this.pageLoaderIsActive = false;
                }

                this.tableLoaderIsActive = false;

            }catch (error){
                console.error('Error fetching posts:', error);
                this.tableLoaderIsActive = false;
            }

        },

        async changeSortGateways(data){
            this.tableLoaderIsActive = true;

            try{

                const result = await apiRequest('gateland/gateway/sort', {
                    method: 'POST',
                    data:{
                        gateway_ids: data
                    }
                })

                if(result.success){
                    await this.init();
                    notyf.success(result.message ? result.message : 'درخواست با موفقیت انجام شد.');
                }else{
                    notyf.error(result.message ? result.message : 'حطایی رخ داده است!');
                }

                this.tableLoaderIsActive = false;

            }catch (error){
                console.error('Error fetching posts:', error);
                this.tableLoaderIsActive = false;
            }

        },

        async generateGatewayRow(data){
            return `
                <div id="${data.id}" class="gateway-row text-sm grid grid-cols-12 bg-white border-b border-gray-200">
                    <div class="md:col-span-7 col-span-8 flex items-center py-4 md:px-5 px-3">
                        <div class="flex items-center gap-3">
                            <button class="btn-handle size-5 min-w-5 opacity-80 hover:opacity-100">
                                <img class="w-full" src="${assetsBaseUrl}/image/icons/dragable.svg">
                            </button>
                            <div class="flex gap-3">
                                <div class="size-10 min-w-10 flex items-center justify-center">
                                    <img class="max-w-full" src="${data.icon}">
                                </div>
                                <div class="text-sm">
                                    <div class="font-semibold text-gray-900 mb-0.5">${data.name}</div>
                                    <div class="text-gray-600">${data.description}</div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="md:col-span-2 col-span-4 flex items-center py-4 md:px-5 px-3">
                        <div class="${ data.status === 'active' ? 'bg-success-50 text-success-700' : 'bg-error-50 text-error-700'} inline-block rounded-full text-center text-nowrap text-xs 0 px-2 py-1">
                            ${ data.status === 'active' ? 'فعال' : 'غیرفعال'}
                        </div>
                    </div>
                    <div class="md:col-span-3 col-span-full flex items-center md:justify-start justify-end py-4 md:px-5 px-3">
                         <div class="flex items-center sm:gap-2 gap-1">
                            <a
                                    href="?page=gateland-gateways-edit&gateway_id=${data.id}\"
                                    class="size-7 flex items-center justify-center rounded hover:shadow hover:bg-primary-100"
                            >
                                <img src="${assetsBaseUrl}/image/icons/settings.svg">
                            </a>
                            <a
                                    href="?page=gateland-gateway&gateway_id=${data.id}"
                                    class="size-7 flex items-center justify-center rounded hover:shadow hover:bg-success-100"
                            >
                                <img src="${assetsBaseUrl}/image/icons/eye.svg">
                            </a>
                            <button
                                    onclick="deleteGateway(${data.id}, '${data.name}')"
                                    class="size-7 flex items-center justify-center rounded hover:shadow hover:bg-error-100"
                            >
                                <img src="${assetsBaseUrl}/image/icons/trash.svg">
                            </button>
                        </div>
                    </div>
                </div>
            `
        },

        async deleteGateway(){
            this.modals.delete.active = false;
            this.tableLoaderIsActive = true;

            try{

                const result = await apiRequest('gateland/gateway/delete', {
                    method: 'POST',
                    data:{
                        gateway_id: this.modals.delete.gateway.id,
                    }
                })

                if(result.success){
                    notyf.success(result.message ? result.message : 'درخواست با موفقیت انجام شد.');
                    await this.init();
                }else{
                    notyf.error(result.message ? result.message : 'حطایی رخ داده است!');
                    this.tableLoaderIsActive = false;
                }

            }catch (error){
                console.error('Error fetching posts:', error);
                this.tableLoaderIsActive = false;
            }

        },

        submit(){
            const gatewayRowElements  = document.querySelectorAll(".gateway-row");
            const dataIdes = {};
            gatewayRowElements.forEach((el, index)=>{
                const id = el.getAttribute('id').toString();
                dataIdes[index] = id;
            })

            this.changeSortGateways(dataIdes);
        },

        openDeleteModal(data){
            this.modals.delete.active = true;
            this.modals.delete.gateway = data;
        }

    }))

})

function deleteGateway(id, name){
    const el = document.querySelector('#sortGateways');
    const component = Alpine.$data(el); // Get the Alpine component's data
    component.openDeleteModal({
        id,
        name
    })
}