"use strict";

function formatRepoSelection(repo) {
    return repo.id || repo.text;
}

function formatRepo(repo) {
    if (repo.loading) {
        return repo.text;
    }
    return repo.text;
}

// Class definition
const products = function () {
    let datatable;
    let table;
    let modal;
    let oldValue;
    let oldHtml;
    let searchModalEl = document.getElementById("modal_search_product");
    let searchModal = new bootstrap.Modal(searchModalEl);
    let searchHandlerEl;
    let suggestionsElement;
    let resultsElement;
    let wrapperElement;
    let emptyElement;
    let searchObject;
    let ajaxRequest;
    let initDatatable = () => {
        datatable = $(table).DataTable({
            language: {
                url: '/media/fa.json'
            },
            ajax: {
                url: "?handler=GetData",
                type: "POST",
                datatype: "json",
                headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
                data: function (outData) {
                    // what is being sent to the server
                    // console.log(outData);
                    return outData;
                },
                dataFilter: function (inData) {
                    // what is being sent back from the server (if no error)
                    // console.log(JSON.parse(inData));
                    return inData;
                },
                error: function (err, status) {
                    // what error is seen(it could be either server side or client side.
                    console.log(err);
                },
            },
            pageLength: 50,
            stateSave: true,
            autoWidth: true,
            processing: true,
            serverSide: true,
            scrollY: "50vh",
            scrollX: true,
            scrollCollapse: true,
            fixedHeader: true,
            filter: true,
            order: [],
            columns: [
                { data: "id", name: "Id", autoWidth: true },
                { data: "nam", name: "Nam", autoWidth: false },
                { data: "groupOne", name: "GroupOne", autoWidth: false },
                { data: "groupTwo", name: "GroupTwo", autoWidth: false },
                // {data: "service", name: "Service", autoWidth: false,visible:false},
                { data: "barcode", name: "Barcode", autoWidth: true },
                { data: "active", name: "Active", autoWidth: false, visible: false },
                {
                    data: 'isDifferent',
                    render: function (data) {
                        if (data == 1) {
                            return '<span class="badge badge-danger"><i class="fas fa-times-circle text-white"></i>&nbsp;&nbsp;بله</span>';
                        } else if (data == 0) {
                            return '<span class="badge badge-success"><i class="fas fa-check-circle text-white"></i>&nbsp;&nbsp;خیر</span>';
                        } else {
                            return '<span class="badge badge-warning"><i class="fas fa-times-circle text-white"></i>&nbsp;&nbsp;نامشخص</span>';
                        }
                    }
                },
                {
                    data: "taxId", name: "TaxId", autoWidth: true, contenteditable: true, 'sortable': false,
                    "render": function (data, type, row) {
                        if (!data) {
                            return '<i class="fa fa-search"></i>'; // Replace with your search icon HTML
                        } else {
                            return data;
                        }
                    },
                },


            ],
        }).search('').state.clear();
        // datatable.state.clear();
        datatable.search('');
        $('#products_table td[contenteditable=true]').blur(function () {
            let row = $(this).parents('tr')[0];
            // let row = $((this).closest('tbody tr'));
            let rowData = datatable.row(row).data();
            let data = {
                id: rowData['id'],
                taxId: rowData['taxId'],
                service: rowData['service'],
            };
            $.ajax({
                type: 'POST',
                url: '?handler=UpdatePost',
                headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
                data: data,
                success: function (res) {
                    if (res == true)
                        toastr.success('تغییرات اعمال شد');
                    else
                        toastr.error('عدم ثبت تغییرات');
                },
                error: function (err) {
                    console.log(err);
                }
            });
        });

        $(document).on('dblclick', 'table tr ', function () {
            let row = $(this).closest('tr')[0];
            let rowData = datatable.row(row).data();
            if (!rowData)
                return;
            searchModalEl.querySelector('#idkala').value = rowData.id;
            searchModalEl.querySelector('#service').value = rowData.service;
            searchModalEl.querySelector('[name=product_code_manual]').value = rowData.taxId;
            searchModal.show();
            return;
        });

        // $(document).on('focus', '.select2.select2-container', function (e) {
        //
        //     var isOriginalEvent = e.originalEvent // don't re-open on closing focus event
        //     var isSingleSelect = $(this).find(".select2-selection--single").length > 0 // multi-select will pass focus to input
        //
        //     if (isOriginalEvent && isSingleSelect) {
        //         $(this).siblings('select:enabled').select2('open');
        //     }
        //     console.log('focus select2')
        // });
        // logging info
        //         $(document).on('focus', '.select2.select2-container', function (e) {
        //             if ($("#showFocus").is(":checked")) toastr.success("Focus Event")
        //             console.log("%c Focus Event ", "background:green; color:white")
        //         });
        // Listen for focusout event on the input field within the second column
        //         $(document).on('focusout', 'table tr td:nth-child(4)', function () {
        //             // Get the new value from the input field
        //             if (!$(this).val())
        //                 return;
        //             let newValue = $(this).val();
        //             if (!newValue)
        //                 newValue = oldValue;
        //             // Get the ID of the corresponding row
        //             var rowId = $(this).closest('tr').attr('data-id');
        //             var row = $(this).closest('tr')[0];
        //             if (!newValue) {
        //                 $(row).find('td:nth-child(4)').html(newValue);
        //                 return;
        //             }
        //
        //             var data = {
        //                 id: row.cells[0].innerText,
        //                 taxId: row.cells[3].innerText,
        //             };
        //             // Submit the new value to the server using AJAX
        //             $.ajax({
        //                 type: 'POST',
        //                 url: '?handler=UpdateProduct',
        //                 headers: {"RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val()},
        //                 data: {id: row.cells[0].innerText, value: newValue},
        //                 success: function (data) {
        //                     // Replace the input field with the new value
        //                     // $('table tr[data-id="' + rowId + '"] td:nth-child(4)').text(newValue);
        //                     $(row).find('td:nth-child(4)').html(newValue);
        //                     if (data == true)
        //                         toastr.success('.تغییرات اعمال شد')
        //                     else
        //                         toastr.error('.تغییرات ثبت نشد')
        //                 },
        //                 error: function (jqXHR, textStatus, errorThrown) {
        //                     console.log('Error: ' + textStatus + ' - ' + errorThrown);
        //                 }
        //             });
        //         });
        // datatable.buttons(0, null).container().insertAfter($('#button_container'));
        datatable.columns().every(function () {
            let that = this;
            $('[data-product-table-filter="search"] input').on('keyup change', function () {
                if (that.search() == this.value) {
                    that.search(this.value).draw();
                }
            });

        });

    };
    const handleStatusFilter = () => {
        const filterStatus = document.querySelector('[data-filter="active_good"]');
        $(filterStatus).on('change', e => {
            let value = e.target.checked;
            datatable.column(6).search(value).draw();
        });
        const withoutIdentifier = document.querySelector('[data-filter="without_identifier"]');
        $(withoutIdentifier).on('change', e => {
            let value = e.target.checked;
            datatable.column(7).search(value).draw();
        });
    }
    const handlers = () => {
        document.querySelector('[name="search"]').addEventListener('keydown', function (event) {
            if (event.key === 'Enter') {
                event.preventDefault();
                const spinner = $('[data-kt-search-element="spinner"]');
                spinner.addClass('d-none');
                searchProcess(searchObject);
                spinner.removeClass('d-none');
            }
        });
        const filterSearch = document.querySelector('[data-product-table-filter="search"]');
        filterSearch.addEventListener('keyup', function (e) {
            datatable.search(e.target.value).draw();
        });
        let submitButton = document.getElementById('upload-excel-modal-submit');
        $('#upload-excel-modal-form').on('submit', function (event) {
            event.preventDefault();
            submitButton.setAttribute('data-kt-indicator', 'on');
            submitButton.disabled = true;
            let formData = new FormData($('#upload-excel-modal-form')[0]);
            ajaxRequest = $.ajax({
                url: '?handler=MyUpload',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function (result) {
                    submitButton.removeAttribute('data-kt-indicator');
                    submitButton.disabled = false;

                    Swal.fire({
                        text: "فایل با موفقیت بارگذاری شد",
                        icon: "success",
                        buttonsStyling: false,
                        confirmButtonText: "باشه",
                        customClass: {
                            confirmButton: "btn btn-success"
                        }
                    });
                    modal.hide();
                },
                error: function (xhr, status, error) {
                    console.log(error);
                    submitButton.removeAttribute('data-kt-indicator');
                    submitButton.disabled = false;

                    if (error === 'abort') {
                        toastr.info('بارگذاری لغو شد');
                        return;
                    }
                    Swal.fire({
                        text: xhr.responseText,
                        icon: "error",
                        buttonsStyling: false,
                        confirmButtonText: "باشه",
                        customClass: {
                            confirmButton: "btn btn-danger"
                        }
                    });
                    modal.hide();
                }
            });
        });

        let cancelButton = document.querySelector('#upload-excel-modal-cancel');
        cancelButton.addEventListener('click', function (event) {
            modal.hide();
            if (!ajaxRequest)
                return;

            ajaxRequest.abort();
        });

        $(document.getElementById("modal_search_product").querySelector('[name="type"]')).on('change', function (event) {
            const spinner = $('[data-kt-search-element="spinner"]');
            spinner.addClass('d-none');
            searchProcess(searchObject);
            spinner.removeClass('d-none');
        });

        const select_manual_btn = document.getElementById('select_manual_btn');
        select_manual_btn.addEventListener('click', function () {
            //check is it valid number with 13 length and all be number

            let product_code = document.querySelector('[name=product_code_manual]').value;
            if (product_code && product_code !== "") {
                if (product_code.length !== 13 || !product_code.match(/^[0-9]*$/)) {
                    toastr.error('کد محصول وارد شده معتبر نمی باشد');
                }
            } else { product_code = ""; }

            const idkala = searchModalEl.querySelector('#idkala').value
            const data = datatable.rows().data();
            let rowTemp;
            let rowTable;
            for (let i = 0; i < data.length; i++) {
                let row = data[i];
                if (row['id'] === parseInt(idkala)) {
                    rowTemp = row;
                    rowTable = $(`#products_table tr`).eq(i + 1);
                    break;
                }
            }
            $.ajax({
                type: 'POST',
                url: '?handler=UpdateProduct',
                headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
                data: { id: rowTemp['id'], value: product_code, service: rowTemp['service'] },
                success: function (data) {
                    if (data === true) {
                        if (product_code && product_code !== "")
                            toastr.success('تغییرات اعمال شد');
                        else
                            toastr.success('شناسه ای برای کالا انتخاب نشده است');
                        $(rowTable).find('td:nth-child(7)').html(product_code);
                    } else {
                        toastr.error('عدم ثبت تغییرات');
                    }
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    console.log('Error: ' + textStatus + ' - ' + errorThrown);
                }
            });
        });
    };

    const searchProcess = function (search) {
        // debounce(performSearch,search ,300)
        let timeoutId;
        clearTimeout(timeoutId);
        timeoutId = setTimeout(async () => {
            await performSearch(search);
        }, 2000);

        // const timeout = setTimeout(function () {
        //     const number = KTUtil.getRandomInt(1, 3);
        //     suggestionsElement.classList.add('d-none');
        //     if (number === 3) {
        //         resultsElement.classList.add('d-none');
        //         emptyElement.classList.remove('d-none');
        //     } else {
        //         resultsElement.classList.remove('d-none');
        //         emptyElement.classList.add('d-none');
        //     }
        //     search.complete();
        // }, 1500);
    }

    async function performSearch(search) {
        const searchQuery = search['inputElement'].value.trim();
        if (!searchQuery) {
            clearResults();
            return;
        }
        const type = $(document.getElementById("modal_search_product").querySelector('[name="type"]')).select2('data')[0].id;
        try {
            if (useOnlineSearch_chk.checked) {
                // const response = await fetch(`https://stuffid.myzarin.com/api/search/${encodeURIComponent(searchQuery)}?type=${encodeURIComponent(type)}`);
                // const data = await response.json();

                // perform post request to server

                const data = await $.ajax({
                    type: 'POST',
                    url: 'https://stuffid.myzarin.com/api/search',
                    // url: 'http://localhost/taxstuffsite/api/search',
                    header: {

                        "Content-Type": "application/json",
                        "Access-Control-Allow-Origin": "*",
                        // "Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept",
                        // "Access-Control-Allow-Methods": "POST"

                    },
                    data: JSON.stringify({
                        searchInput: searchQuery,
                        typeSelect: type,
                        extraInput: '',
                    }),
                    success: function (data) {
                        renderResults(data["data"], search);
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        console.log('Error: ' + textStatus + ' - ' + errorThrown);
                    }
                });

                // fetch( 'http://localhost/taxstuffsite/api/search',{
                //     method: 'POST',
                //mode: 'no-cores'
                //     headers: {
                //         'Content-Type': 'application/json',
                //         "Access-Control-Allow-Origin": "*",
                //     },
                //     body: JSON.stringify({
                //         searchInput: searchQuery,
                //         typeSelect: '',
                //         extraInput: '',
                //     })
                // })
                // .then(response => response.json())
                // .then(data => {
                //     renderResults(data["data"],search);
                //  })
            } else {
                const response = await fetch(`?handler=stuffId&search=${encodeURIComponent(searchQuery)}&type=${encodeURIComponent(type)}`);
                const data = await response.json();
                renderResults(data, search);
            }
        } catch (error) {
            console.error('Error fetching search results:', error);
            showErrorMessage('An error occurred while searching. Please try again later.');
            search.complete();
        }
    }

    function debounce(func, search, delay) {
        let timeoutId;
        return (...args) => {
            clearTimeout(timeoutId);
            timeoutId = setTimeout(() => {
                func.apply(this, search, args);
            }, delay);
        };
    }

    function clearResults() {
        resultsElement.innerHTML = '';
    }

    function renderResults(data, search) {
        clearResults();
        console.log(data);
        const itemElement = (item) => {
            return `
            <div class="border border-hover-primary rounded d-flex flex-stack bg-active-lighten p-4" data-product-id="${item.stuffId ?? item.StuffId ?? item.Id ?? item.id ?? item.stuffID ?? item.StuffID}">
                                    <div class="d-flex align-items-center">
                                        <div class="ms-5">
                                            <a href="#" class="fs-5 fw-bold text-gray-900 text-hover-primary mb-2">${item.descript ?? item.Descript}</a>
                                            <div class="fw-semibold text-muted">${item.stuffId ?? item.StuffId ?? item.Id ?? item.id ?? item.stuffID ?? item.StuffID}</div>
                                        </div>
                                    </div>
                                    <div class="ms-2 w-100px">
                                        <button type="button" data-product-selection="${item.stuffId ?? item.StuffId ?? item.Id ?? item.id ?? item.stuffID ?? item.StuffID}" data-bs-dismiss="modal" class="btn btn-light me-3">انتخاب</button>
                                    </div>
                                </div>
                                `;
            // <div class="border-bottom border-gray-300 border-bottom-dashed"></div>
        }
        if (data.length === 0) {
            // const noResultsMessage = document.createElement('p');
            // noResultsMessage.textContent = 'No results found.';
            // resultsElement.appendChild(noResultsMessage);
            resultsElement.innerHTML = "";
            resultsElement.classList.add('d-none');
            emptyElement.classList.remove('d-none');
        } else {
            resultsElement.classList.remove('d-none');
            emptyElement.classList.add('d-none');
            const resultsList = document.createElement('ul');
            data.forEach((item) => {
                // const listItem = document.createElement('li');
                // listItem.textContent = item.name; // Assuming the data has a 'name' property
                const itemHtml = itemElement(item);
                resultsElement.insertAdjacentHTML("beforeend", itemHtml);
            });
            const btns = resultsElement.querySelectorAll('[data-product-selection]');
            btns.forEach((element) => {
                element.addEventListener('click', function (event) {
                    const selectedProduct = element.getAttribute('data-product-selection');
                    const selectedProductElement = document.querySelector(`[data-product-id="${selectedProduct}"]`);
                    const idkala = searchModalEl.querySelector('#idkala').value
                    const data = datatable.rows().data();
                    let rowTemp;
                    let rowTable;
                    for (let i = 0; i < data.length; i++) {
                        let row = data[i];
                        if (row['id'] === parseInt(idkala)) {
                            rowTemp = row;
                            rowTable = $(`#products_table tr`).eq(i + 1);
                            break;
                        }
                    }
                    $.ajax({
                        type: 'POST',
                        url: '?handler=UpdateProduct',
                        headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
                        data: { id: rowTemp['id'], value: selectedProduct, service: rowTemp['service'] },
                        success: function (data) {
                            if (data === true) {
                                toastr.success('تغییرات اعمال شد');
                                $(rowTable).find('td:nth-child(7)').html(selectedProduct);
                            } else {
                                toastr.error('عدم ثبت تغییرات');
                            }
                        },
                        error: function (jqXHR, textStatus, errorThrown) {
                            console.log('Error: ' + textStatus + ' - ' + errorThrown);
                        }
                    });

                });
            });
            // resultsElement.appendChild(resultsList);
        }
        search.complete();
    }

    function showErrorMessage(message) {
        const errorMessage = document.createElement('p');
        errorMessage.textContent = message;
        errorMessage.classList.add('error-message');
        resultsElement.appendChild(errorMessage);
    }

    const clear = function (search) {
        // Show recently viewed
        suggestionsElement.classList.remove('d-none');
        // Hide results
        resultsElement.classList.add('d-none');
        // Hide empty message 
        emptyElement.classList.add('d-none');
    };
    return {
        init: function () {
            table = document.querySelector('#products_table');
            if (!table) return;

            const element = document.getElementById('upload-excel-modal');
            modal = new bootstrap.Modal(element);

            searchHandlerEl = document.querySelector('#kt_modal_users_search_handler');
            wrapperElement = searchHandlerEl.querySelector('[data-kt-search-element="wrapper"]');
            suggestionsElement = searchHandlerEl.querySelector('[data-kt-search-element="suggestions"]');
            resultsElement = searchHandlerEl.querySelector('[data-kt-search-element="results"]');
            emptyElement = searchHandlerEl.querySelector('[data-kt-search-element="empty"]');

            searchObject = new KTSearch(searchHandlerEl);
            searchObject.on('kt.search.process', searchProcess);
            searchObject.on('kt.search.clear', clear);

            initDatatable();
            handlers();
            handleStatusFilter();

        }
    };
}();

// On document ready
KTUtil.onDOMContentLoaded(function () {
    products.init();
});
