(function () {
    'use strict';

    let quickReturnItems = [];
    let bankAccounts = [];

    function formatMoney(amount) {
        return 'Rs ' + (parseFloat(amount) || 0).toFixed(2);
    }

    function getSelectedCustomerInfo() {
        const sel = document.getElementById('top-customer-select');
        if (!sel) {
            return { id: 0, label: 'Walk-in Customer' };
        }
        const val = sel.value;
        if (!val || val === 'walk-in' || val === 'select') {
            return { id: 0, label: 'Walk-in Customer' };
        }
        const opt = sel.options[sel.selectedIndex];
        const id = parseInt(val, 10);
        return {
            id: isNaN(id) ? 0 : id,
            label: opt ? opt.textContent.trim() : 'Customer'
        };
    }

    function collectCartForQuickReturn() {
        const items = [];
        let blockedDeal = false;

        document.querySelectorAll('.product-list').forEach(function (row) {
            if (row.getAttribute('data-is-deal') === '1') {
                blockedDeal = true;
                return;
            }

            const itemId = parseInt(row.getAttribute('data-item-id'), 10) || 0;
            const qtyInput = row.querySelector('input[name="qty"]');
            const qty = qtyInput ? parseFloat(qtyInput.value) || 0 : 0;
            if (itemId <= 0 || qty <= 0) {
                return;
            }

            let unitPrice = parseFloat(row.getAttribute('data-price')) || 0;
            if (typeof getRowDiscountInfo === 'function') {
                const discountInfo = getRowDiscountInfo(row);
                unitPrice = Math.max(0, discountInfo.price - discountInfo.perUnit);
            }

            let serialIds = [];
            const serialAttr = row.getAttribute('data-serial-ids');
            if (serialAttr) {
                try {
                    serialIds = JSON.parse(serialAttr);
                } catch (e) {
                    serialIds = [];
                }
            }

            items.push({
                item_id: itemId,
                item_name: row.getAttribute('data-item-name') || row.querySelector('h6')?.textContent || 'Item',
                quantity: qty,
                unit_price: unitPrice,
                tax_rate: parseFloat(row.getAttribute('data-tax-rate')) || 0,
                serial_ids: Array.isArray(serialIds) ? serialIds.map(function (id) { return parseInt(id, 10); }).filter(Boolean) : []
            });
        });

        return { items: items, blockedDeal: blockedDeal };
    }

    function renderQuickReturnItems() {
        const tbody = document.getElementById('quick-return-items-body');
        const totalEl = document.getElementById('quick-return-total');
        if (!tbody) {
            return;
        }

        if (!quickReturnItems.length) {
            tbody.innerHTML = '<tr><td colspan="4" class="text-center text-muted py-3">No items in cart.</td></tr>';
            if (totalEl) {
                totalEl.textContent = formatMoney(0);
            }
            return;
        }

        let total = 0;
        tbody.innerHTML = quickReturnItems.map(function (line) {
            const lineTotal = line.quantity * line.unit_price;
            total += lineTotal;
            return '<tr>' +
                '<td>' + escapeHtml(line.item_name) + '</td>' +
                '<td class="text-center">' + line.quantity + '</td>' +
                '<td class="text-end">' + line.unit_price.toFixed(2) + '</td>' +
                '<td class="text-end">' + lineTotal.toFixed(2) + '</td>' +
                '</tr>';
        }).join('');

        if (totalEl) {
            totalEl.textContent = formatMoney(total);
        }
    }

    function escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text || '';
        return div.innerHTML;
    }

    function setQuickReturnStatus(message, isError) {
        const el = document.getElementById('quick-return-status');
        if (!el) {
            return;
        }
        el.textContent = message || '';
        el.classList.toggle('text-danger', Boolean(isError));
    }

    function toggleQuickReturnBank() {
        const methodEl = document.getElementById('quick-return-payment-method');
        const wrap = document.getElementById('quick-return-bank-wrapper');
        const bankEl = document.getElementById('quick-return-bank-account');
        if (!methodEl || !wrap || !bankEl) {
            return;
        }
        const isBank = methodEl.value === 'bank';
        wrap.classList.toggle('d-none', !isBank);
        bankEl.required = isBank;
    }

    function populateQuickReturnBanks() {
        const bankEl = document.getElementById('quick-return-bank-account');
        if (!bankEl) {
            return;
        }
        while (bankEl.options.length > 1) {
            bankEl.remove(1);
        }
        bankAccounts.forEach(function (bank) {
            const opt = document.createElement('option');
            opt.value = bank.id;
            opt.textContent = bank.account_title + (bank.bank_name ? ' (' + bank.bank_name + ')' : '');
            bankEl.appendChild(opt);
        });
    }

    function fetchQuickReturnBanks() {
        return fetch('ajax/get_bank_accounts.php')
            .then(function (res) { return res.json(); })
            .then(function (data) {
                bankAccounts = (data && data.success && data.banks) ? data.banks : [];
                populateQuickReturnBanks();
            })
            .catch(function () {
                bankAccounts = [];
            });
    }

    function submitQuickReturnRequest() {
        const reasonEl = document.getElementById('quick-return-reason');
        const remarksEl = document.getElementById('quick-return-remarks');
        const methodEl = document.getElementById('quick-return-payment-method');
        const bankEl = document.getElementById('quick-return-bank-account');
        const submitBtn = document.getElementById('quick-return-submit-btn');

        const returnReason = reasonEl ? reasonEl.value.trim() : '';
        if (!returnReason) {
            setQuickReturnStatus('Please select a return reason.', true);
            return;
        }

        const paymentMethod = methodEl ? methodEl.value : 'cash';
        const bankAccountId = (paymentMethod === 'bank' && bankEl && bankEl.value) ? parseInt(bankEl.value, 10) : null;
        if (paymentMethod === 'bank' && !bankAccountId) {
            setQuickReturnStatus('Please select a bank account for bank refund.', true);
            return;
        }

        const customer = getSelectedCustomerInfo();
        const payload = {
            customer_id: customer.id,
            return_reason: returnReason,
            customer_remarks: remarksEl ? remarksEl.value.trim() : '',
            payment_method: paymentMethod,
            bank_account_id: bankAccountId,
            items: quickReturnItems
        };

        if (submitBtn) {
            submitBtn.disabled = true;
        }
        setQuickReturnStatus('Processing return...', false);

        fetch('ajax/process_quick_sale_return.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(payload)
        })
            .then(function (res) { return res.json(); })
            .then(function (data) {
                if (!data.success) {
                    throw new Error(data.message || 'Return failed.');
                }

                const modalEl = document.getElementById('quickSaleReturnModal');
                if (modalEl) {
                    bootstrap.Modal.getInstance(modalEl)?.hide();
                }

                if (typeof window.resetCart === 'function') {
                    window.resetCart(true, true);
                }

                if (typeof Swal !== 'undefined') {
                    Swal.fire({
                        icon: 'success',
                        title: 'Quick return completed',
                        html: 'Return #' + (data.sale_return_id || '') + '<br>Refund: ' + formatMoney(data.total_amount),
                        timer: 2500,
                        showConfirmButton: false
                    });
                } else {
                    alert(data.message || 'Return processed.');
                }
            })
            .catch(function (err) {
                setQuickReturnStatus(err.message || 'Return failed.', true);
            })
            .finally(function () {
                if (submitBtn) {
                    submitBtn.disabled = false;
                }
            });
    }

    function processQuickReturnWithPin() {
        if (typeof showPinVerification === 'function') {
            showPinVerification('quick_sale_return', submitQuickReturnRequest);
        } else {
            submitQuickReturnRequest();
        }
    }

    window.itrposOpenQuickReturnFromSidebar = function () {
        const sidebarEl = document.getElementById('posSettingsSidebar');
        if (sidebarEl) {
            const instance = bootstrap.Offcanvas.getInstance(sidebarEl);
            if (instance) {
                instance.hide();
            }
        }
        window.openQuickSaleReturnFromCart();
    };

    window.openQuickSaleReturnFromCart = function () {
        const modalEl = document.getElementById('quickSaleReturnModal');
        if (!modalEl) {
            return;
        }

        const collected = collectCartForQuickReturn();
        if (collected.blockedDeal) {
            if (typeof Swal !== 'undefined') {
                Swal.fire({
                    icon: 'warning',
                    title: 'Deal items',
                    text: 'Remove deal/combo lines from the cart. Use invoice-based return for deals, or return items individually.'
                });
            } else {
                alert('Deal items cannot be quick-returned. Remove them from the cart.');
            }
            return;
        }

        if (!collected.items.length) {
            if (typeof Swal !== 'undefined') {
                Swal.fire({
                    icon: 'info',
                    title: 'Empty cart',
                    text: 'Add the items to return on the POS cart first, then press Ctrl+R.'
                });
            } else {
                alert('Add items to the cart before quick return.');
            }
            return;
        }

        quickReturnItems = collected.items;
        const customer = getSelectedCustomerInfo();
        const labelEl = document.getElementById('quick-return-customer-label');
        if (labelEl) {
            labelEl.textContent = customer.label;
        }

        const reasonEl = document.getElementById('quick-return-reason');
        const remarksEl = document.getElementById('quick-return-remarks');
        if (reasonEl) {
            reasonEl.value = '';
        }
        if (remarksEl) {
            remarksEl.value = '';
        }

        renderQuickReturnItems();
        setQuickReturnStatus('', false);
        toggleQuickReturnBank();

        fetchQuickReturnBanks().finally(function () {
            bootstrap.Modal.getOrCreateInstance(modalEl).show();
        });
    };

    document.addEventListener('DOMContentLoaded', function () {
        const modalEl = document.getElementById('quickSaleReturnModal');
        if (!modalEl) {
            return;
        }

        const methodEl = document.getElementById('quick-return-payment-method');
        const submitBtn = document.getElementById('quick-return-submit-btn');
        const invoiceLink = document.getElementById('quick-return-open-invoice-link');

        if (methodEl) {
            methodEl.addEventListener('change', toggleQuickReturnBank);
        }
        if (submitBtn) {
            submitBtn.addEventListener('click', processQuickReturnWithPin);
        }
        if (invoiceLink) {
            invoiceLink.addEventListener('click', function (e) {
                e.preventDefault();
                const quickModal = bootstrap.Modal.getInstance(modalEl);
                if (quickModal) {
                    quickModal.hide();
                }
                const saleReturnModal = document.getElementById('saleReturnModal');
                if (saleReturnModal) {
                    bootstrap.Modal.getOrCreateInstance(saleReturnModal).show();
                }
            });
        }
    });
})();
