/**
 * Admin Collections Page Script
 * ----------------------------
 * Handles fetching, displaying, and filtering collections via API.
 */

document.addEventListener('DOMContentLoaded', function () {
    // DOM Elements
    const collectionsTableBody = document.getElementById('collectionsTableBody');
    const searchInput = document.getElementById('searchInput');
    const statusFilter = document.getElementById('statusFilter');
    const paginationContainer = document.getElementById('pagination');
    const paginationInfo = document.getElementById('paginationInfo');

    // Modal Elements
    const deleteModalEl = document.getElementById('deleteConfirmationModal');
    const confirmDeleteBtn = document.getElementById('confirmDeleteBtn');
    let deleteModal = null;
    let collectionToDeleteId = null;

    if (deleteModalEl) {
        deleteModal = new bootstrap.Modal(deleteModalEl);

        // Bind Modal Events
        deleteModalEl.addEventListener('show.bs.modal', function (event) {
            const button = event.relatedTarget;
            const id = button.getAttribute('data-id');
            const name = button.getAttribute('data-name');

            collectionToDeleteId = id;
            document.getElementById('deleteCollectionName').textContent = name || `Collection #${id}`;
        });

        // Bind Confirm Button
        if (confirmDeleteBtn) {
            confirmDeleteBtn.addEventListener('click', function () {
                if (!collectionToDeleteId) return;

                const btn = this;
                const originalText = btn.innerHTML;
                btn.disabled = true;
                btn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Deleting...';

                // Simple URL-encoded data for max compatibility
                const params = new URLSearchParams();
                params.append('action', 'delete');
                params.append('id', collectionToDeleteId);

                fetch('api/collections.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: params
                })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            deleteModal.hide();
                            loadCollections(); // Reload list
                        } else {
                            alert(data.message || 'Failed to delete collection');
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        alert('An error occurred while deleting.');
                    })
                    .finally(() => {
                        btn.disabled = false;
                        btn.innerHTML = originalText;
                    });
            });
        }
    }

    // State
    let currentPage = 1;
    let limit = 10;

    // Initial Load
    loadCollections();

    // Event Listeners
    if (searchInput) {
        searchInput.addEventListener('input', debounce(function () {
            currentPage = 1;
            loadCollections();
        }, 500));
    }

    if (statusFilter) {
        statusFilter.addEventListener('change', function () {
            currentPage = 1;
            loadCollections();
        });
    }

    /**
     * Load collections from API
     */
    function loadCollections() {
        const query = searchInput.value;
        const status = statusFilter.value;

        let url = `api/collections.php?page=${currentPage}&limit=${limit}`;
        if (query) url += `&search=${encodeURIComponent(query)}`;
        if (status) url += `&status=${status}`;

        // Show loading state (optional, can handle minimal UI updates)
        collectionsTableBody.innerHTML = '<tr><td colspan="7" class="text-center py-4">Loading...</td></tr>';

        fetch(url)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    renderCollections(data.data);
                    renderPagination(data.pagination);
                } else {
                    showError(data.message || 'Failed to load collections');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showError('An error occurred while loading collections');
            });
    }

    /**
     * Render collections table rows
     */
    function renderCollections(collections) {
        if (!collections || collections.length === 0) {
            collectionsTableBody.innerHTML = '<tr><td colspan="7" class="text-center py-4">No collections found.</td></tr>';
            return;
        }

        collectionsTableBody.innerHTML = collections.map(collection => `
            <tr>
                <td>#${collection.id}</td>
                <td>
                    <img src="${collection.image || 'assets/images/placeholder.png'}" alt="${collection.name}" class="rounded" style="width: 40px; height: 40px; object-fit: cover;">
                </td>
                <td>
                    <h6 class="mb-0 text-truncate" style="max-width: 250px;">${escapeHtml(collection.name)}</h6>
                </td>
                <td>
                    <span class="text-muted small">${collection.slug}</span>
                </td>
                <td>
                    <span class="badge bg-soft-info text-info rounded-pill px-2">
                        ${collection.product_count || 0} products
                    </span>
                </td>
                <td>
                    ${getStatusBadge(collection.is_active)}
                </td>
                <td>
                    <div class="d-flex gap-2">
                        <a href="edit-collection.php?id=${collection.id}" class="btn btn-sm btn-outline-secondary">
                            <i class="iconoir-edit-pencil"></i>
                        </a>
                        <!-- Update Delete Button to Trigger Modal -->
                        <button type="button" class="btn btn-sm btn-outline-danger" 
                                data-bs-toggle="modal" 
                                data-bs-target="#deleteConfirmationModal"
                                data-id="${collection.id}"
                                data-name="${escapeHtml(collection.name)}">
                            <i class="iconoir-trash"></i>
                        </button>
                    </div>
                </td>
            </tr>
        `).join('');
    }

    /**
     * Render pagination controls
     */
    function renderPagination(pagination) {
        if (pagination.total_pages <= 1) {
            paginationContainer.innerHTML = '';
            paginationInfo.innerHTML = `Showing ${pagination.total_items} collections`;
            return;
        }

        let html = '';

        // Previous
        html += `<li class="page-item ${!pagination.has_prev ? 'disabled' : ''}">
            <a class="page-link" href="#" data-page="${pagination.current_page - 1}">Previous</a>
        </li>`;

        // Pages
        for (let i = 1; i <= pagination.total_pages; i++) {
            if (
                i === 1 ||
                i === pagination.total_pages ||
                (i >= pagination.current_page - 1 && i <= pagination.current_page + 1)
            ) {
                html += `<li class="page-item ${i === pagination.current_page ? 'active' : ''}">
                    <a class="page-link" href="#" data-page="${i}">${i}</a>
                </li>`;
            } else if (
                i === pagination.current_page - 2 ||
                i === pagination.current_page + 2
            ) {
                html += `<li class="page-item disabled"><span class="page-link">...</span></li>`;
            }
        }

        // Next
        html += `<li class="page-item ${!pagination.has_next ? 'disabled' : ''}">
            <a class="page-link" href="#" data-page="${pagination.current_page + 1}">Next</a>
        </li>`;

        paginationContainer.innerHTML = html;
        paginationInfo.innerHTML = `Showing page ${pagination.current_page} of ${pagination.total_pages} (${pagination.total_items} total)`;

        // Add event listeners to pagination links
        paginationContainer.querySelectorAll('.page-link').forEach(link => {
            link.addEventListener('click', function (e) {
                e.preventDefault();
                const page = parseInt(this.dataset.page);
                if (page && page !== currentPage) {
                    currentPage = page;
                    loadCollections();
                }
            });
        });
    }

    // Utility: Debounce
    function debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    }

    // Utility: Escape HTML
    function escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    // Utility: Get Status Badge
    // API returns '0' or '1' string or int
    function getStatusBadge(status) {
        // Normalize status
        const isActive = (status === 1 || status === '1' || status === 'active');
        if (isActive) {
            return '<span class="badge bg-success">Active</span>';
        } else {
            return '<span class="badge bg-secondary">Inactive</span>';
        }
    }

    // Utility: Show Error
    function showError(message) {
        collectionsTableBody.innerHTML = `<tr><td colspan="7" class="text-center text-danger py-4">${message}</td></tr>`;
    }
});
