/**
 * Blogibot Manage Feeds JavaScript
 * Handles dynamic loading and management of feed sources
 */
(function ($) {
    'use strict';

    let allFeeds = [];
    let feedStats = {};

    // Initialize on document ready
    $(document).ready(function () {
        loadFeeds();
        initializeEventHandlers();
    });

    /**
     * Load all feeds from server
     */
    function loadFeeds() {
        $.ajax({
            url: blogibotFeed.ajax_url,
            type: 'POST',
            data: {
                action: 'blogibot_get_feed_sources',
                nonce: blogibotFeed.nonce
            },
            success: function (response) {
                if (response.success) {
                    allFeeds = response.data.feeds;
                    feedStats = response.data.stats;
                    renderFeeds(allFeeds);
                    updateStats();
                } else {
                    showError('Failed to load feeds: ' + (response.data.message || 'Unknown error'));
                }
            },
            error: function (xhr, status, error) {
                showError('Error loading feeds: ' + error);
            }
        });
    }

    /**
     * Render feeds in table
     */
    function renderFeeds(feeds) {
        const tbody = $('.blog82ai-feeds-table tbody');
        tbody.empty();

        if (feeds.length === 0) {
            tbody.append('<tr><td colspan="8" style="text-align:center;">No feed sources found. <a href="' + getAddFeedUrl() + '">Add your first feed</a></td></tr>');
            return;
        }

        feeds.forEach(function (feed) {
            const row = createFeedRow(feed);
            tbody.append(row);
        });

        // Update count
        $('.blog82ai-items-count').text(feeds.length + ' feeds total');
    }

    /**
     * Create a table row for a feed
     */
    function createFeedRow(feed) {
        const statusBadge = getStatusBadge(feed.status);
        const fetchStatus = getFetchStatus(feed);
        const actionButtons = getActionButtons(feed);
        const lastFetch = feed.last_fetch_time ? formatDateTime(feed.last_fetch_time) : 'Never';

        return $('<tr>')
            .attr('data-status', feed.status)
            .attr('data-category', feed.category || '')
            .attr('data-frequency', feed.fetch_frequency)
            .html(`
                <td><input type="checkbox" class="feed-checkbox" value="${feed.id}"></td>
                <td>
                    <strong><a href="#edit-feed-${feed.id}">${escapeHtml(feed.feed_name)}</a></strong>
                    <div class="row-actions">
                        <span class="edit"><a href="#" onclick="editFeed(${feed.id}); return false;">Edit</a> | </span>
                        <span class="view"><a href="${escapeHtml(feed.feed_url)}" target="_blank">View Feed</a> | </span>
                        <span class="fetch"><a href="#" onclick="fetchFeed(${feed.id}); return false;">Fetch Now</a></span>
                    </div>
                    <div class="blog82ai-feed-url">${escapeHtml(feed.feed_url)}</div>
                </td>
                <td>${feed.category_name ? escapeHtml(feed.category_name) : '-'}</td>
                <td>${formatFrequency(feed.fetch_frequency)}</td>
                <td>
                    <span class="blog82ai-fetch-time">${lastFetch}</span>
                    ${fetchStatus}
                </td>
                <td>
                    <span class="blog82ai-import-count">${feed.posts_imported_total || 0} total</span>
                    <div class="blog82ai-recent-imports">${feed.posts_imported_today || 0} today</div>
                </td>
                <td>${statusBadge}</td>
                <td>${actionButtons}</td>
            `);
    }

    /**
     * Get status badge HTML
     */
    function getStatusBadge(status) {
        const statusClass = 'blog82ai-status-badge status-' + status;
        return `<span class="${statusClass}">${capitalizeFirst(status)}</span>`;
    }

    /**
     * Get fetch status HTML
     */
    function getFetchStatus(feed) {
        if (!feed.last_fetch_status) {
            return '';
        }

        const statusIcons = {
            'success': '✅',
            'error': '❌',
            'partial': '⚠️',
            'paused': '⏸️'
        };

        const icon = statusIcons[feed.last_fetch_status] || '';
        const statusClass = 'blog82ai-fetch-status ' + feed.last_fetch_status;
        const message = feed.last_fetch_message || capitalizeFirst(feed.last_fetch_status);

        return `<div class="${statusClass}">${icon} ${escapeHtml(message)}</div>`;
    }

    /**
     * Get action buttons HTML
     */
    function getActionButtons(feed) {
        const toggleButton = feed.status === 'active' || feed.status === 'error'
            ? `<button class="button button-small" onclick="toggleFeed(${feed.id}, 'paused')" title="Pause Feed">⏸️</button>`
            : `<button class="button button-small" onclick="toggleFeed(${feed.id}, 'active')" title="Activate Feed">▶️</button>`;

        return `
            <div class="blog82ai-action-buttons">
                ${toggleButton}
                <button class="button button-small" onclick="fetchFeed(${feed.id})" title="Fetch Now">🔄</button>
                <button class="button button-small" onclick="editFeed(${feed.id})" title="Edit Feed">✏️</button>
                <button class="button button-small button-danger" onclick="deleteFeed(${feed.id})" title="Delete Feed">🗑️</button>
            </div>
        `;
    }

    /**
     * Update statistics display
     */
    function updateStats() {
        $('.blog82ai-stats-cards').html(`
            <div class="blog82ai-stat-card">
                <div class="blog82ai-stat-number">${feedStats.total || 0}</div>
                <div class="blog82ai-stat-label">Total Feeds</div>
            </div>
            <div class="blog82ai-stat-card">
                <div class="blog82ai-stat-number">${feedStats.active || 0}</div>
                <div class="blog82ai-stat-label">Active</div>
            </div>
            <div class="blog82ai-stat-card">
                <div class="blog82ai-stat-number">${feedStats.error || 0}</div>
                <div class="blog82ai-stat-label">Errors</div>
            </div>
            <div class="blog82ai-stat-card">
                <div class="blog82ai-stat-number">${feedStats.total_posts || 0}</div>
                <div class="blog82ai-stat-label">Total Posts</div>
            </div>
        `);
    }

    /**
     * Initialize event handlers
     */
    function initializeEventHandlers() {
        // Filter handlers
        $('#filter-status, #filter-category, #filter-frequency').on('change', applyFilters);
        $('#search-feeds').on('input', applyFilters);

        // Select all checkbox
        $('#select-all-feeds').on('change', function () {
            $('.feed-checkbox:visible').prop('checked', $(this).prop('checked'));
            updateSelectionCount();
        });

        // Individual checkboxes
        $(document).on('change', '.feed-checkbox', updateSelectionCount);

        // Bulk actions
        $(document).on('click', '.blog82ai-bulk-actions button', applyBulkAction);
    }

    /**
     * Apply filters
     */
    function applyFilters() {
        const statusFilter = $('#filter-status').val();
        const categoryFilter = $('#filter-category').val();
        const frequencyFilter = $('#filter-frequency').val();
        const searchTerm = $('#search-feeds').val().toLowerCase();

        const filtered = allFeeds.filter(function (feed) {
            if (statusFilter && feed.status !== statusFilter) return false;
            if (categoryFilter && feed.category !== categoryFilter) return false;
            if (frequencyFilter && feed.fetch_frequency !== frequencyFilter) return false;
            if (searchTerm) {
                const nameMatch = feed.feed_name.toLowerCase().includes(searchTerm);
                const urlMatch = feed.feed_url.toLowerCase().includes(searchTerm);
                if (!nameMatch && !urlMatch) return false;
            }
            return true;
        });

        renderFeeds(filtered);
    }

    /**
     * Update selection count
     */
    function updateSelectionCount() {
        const selected = $('.feed-checkbox:checked').length;
        const countSpan = $('.blog82ai-selection-count');

        if (selected > 0) {
            countSpan.text(selected + ' selected').show();
        } else {
            countSpan.hide();
        }
    }

    /**
     * Apply bulk action
     */
    function applyBulkAction() {
        const action = $('#bulk-action-selector').val();
        const selectedIds = $('.feed-checkbox:checked').map(function () {
            return $(this).val();
        }).get();

        if (!action) {
            Blog82AI_Modal.showError('Error', 'Please select a bulk action.');
            return;
        }

        if (selectedIds.length === 0) {
            Blog82AI_Modal.showError('Error', 'Please select at least one feed.');
            return;
        }

        const actionText = action.replace('_', ' ');
        Blog82AI_Modal.showConfirm(
            'wptestings.test says',
            `Are you sure you want to ${actionText} ${selectedIds.length} selected feed(s)?`,
            function () {
                // User confirmed - proceed with bulk action
                performBulkAction(selectedIds, action);
            }
        );
    }

    function performBulkAction(selectedIds, action) {

        $.ajax({
            url: blogibotFeed.ajax_url,
            type: 'POST',
            data: {
                action: 'blogibot_bulk_feed_action',
                nonce: blogibotFeed.nonce,
                feed_ids: selectedIds,
                action_type: action
            },
            success: function (response) {
                if (response.success) {
                    Blog82AI_Modal.showSuccess('Success', response.data.message, true);
                    setTimeout(function () {
                        loadFeeds(); // Reload feeds
                    }, 1500);
                } else {
                    Blog82AI_Modal.showError('Error', response.data.message || 'Bulk action failed');
                }
            },
            error: function (xhr, status, error) {
                Blog82AI_Modal.showError('Error', error);
            }
        });
    }

    /**
     * Helper functions
     */
    function formatDateTime(datetime) {
        const date = new Date(datetime);
        const now = new Date();
        const diff = Math.floor((now - date) / 1000); // seconds

        if (diff < 60) return 'Just now';
        if (diff < 3600) return Math.floor(diff / 60) + ' minutes ago';
        if (diff < 86400) return Math.floor(diff / 3600) + ' hours ago';
        if (diff < 604800) return Math.floor(diff / 86400) + ' days ago';

        return date.toLocaleDateString();
    }

    function formatFrequency(freq) {
        const map = {
            'hourly': 'Every Hour',
            '6hours': 'Every 6 Hours',
            'daily': 'Daily',
            'weekly': 'Weekly',
            'manual': 'Manual'
        };
        return map[freq] || capitalizeFirst(freq);
    }

    function capitalizeFirst(str) {
        if (!str) return '';
        return str.charAt(0).toUpperCase() + str.slice(1);
    }

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

    function getAddFeedUrl() {
        return window.location.href.replace('manage_feeds', 'add_feed_source');
    }

    function showError(message) {
        Blog82AI_Modal.showError('Error', message);
    }

    // Make functions globally accessible
    window.toggleFeed = function (feedId, newStatus) {
        Blog82AI_Modal.showConfirm(
            'wptestings.test says',
            `Are you sure you want to ${newStatus === 'paused' ? 'pause' : 'activate'} this feed?`,
            function () {
                // User confirmed - proceed with toggle
                $.ajax({
                    url: blogibotFeed.ajax_url,
                    type: 'POST',
                    data: {
                        action: 'blogibot_toggle_feed_status',
                        nonce: blogibotFeed.nonce,
                        feed_id: feedId,
                        status: newStatus
                    },
                    success: function (response) {
                        if (response.success) {
                            Blog82AI_Modal.showSuccess('Success', 'Feed status updated successfully!', true);
                            setTimeout(function () {
                                loadFeeds();
                            }, 1500);
                        } else {
                            Blog82AI_Modal.showError('Error', response.data.message || 'Failed to update status');
                        }
                    },
                    error: function (xhr, status, error) {
                        Blog82AI_Modal.showError('Error', error);
                    }
                });
            }
        );
    };

    window.fetchFeed = function (feedId) {
        Blog82AI_Modal.showConfirm(
            'wptestings.test says',
            'Fetch new posts from this feed now?',
            function () {
                // User confirmed - proceed with fetch
                Blog82AI_Modal.showLoading('Fetching feed posts...');

                $.ajax({
                    url: blogibotFeed.ajax_url,
                    type: 'POST',
                    data: {
                        action: 'blogibot_fetch_feed',
                        nonce: blogibotFeed.nonce,
                        feed_id: feedId
                    },
                    success: function (response) {
                        Blog82AI_Modal.closeLoading();
                        if (response.success) {
                            Blog82AI_Modal.showSuccess(
                                'Success',
                                response.data.message + '\nPosts imported: ' + (response.data.posts_imported || 0),
                                true
                            );
                            setTimeout(function () {
                                loadFeeds();
                            }, 2000);
                        } else {
                            Blog82AI_Modal.showError('Error', response.data.message || 'Failed to fetch feed');
                        }
                    },
                    error: function (xhr, status, error) {
                        Blog82AI_Modal.closeLoading();
                        Blog82AI_Modal.showError('Error', error);
                    }
                });
            }
        );
    };

    window.editFeed = function (feedId) {
        // Redirect to Add Feed Source page with edit parameter
        window.location.href = 'admin.php?page=blogibot&tab=feed&subtab=add_feed_source&edit_feed_id=' + feedId;
    };

    window.deleteFeed = function (feedId) {
        Blog82AI_Modal.showConfirm(
            'wptestings.test says',
            'Are you sure you want to delete this feed? This action cannot be undone.',
            function () {
                // User confirmed - proceed with deletion
                $.ajax({
                    url: blogibotFeed.ajax_url,
                    type: 'POST',
                    data: {
                        action: 'blogibot_delete_feed_source',
                        nonce: blogibotFeed.nonce,
                        feed_id: feedId
                    },
                    success: function (response) {
                        if (response.success) {
                            Blog82AI_Modal.showSuccess(
                                'wptestings.test says',
                                'Feed deleted successfully!',
                                true
                            );
                            setTimeout(function () {
                                loadFeeds();
                            }, 1500);
                        } else {
                            Blog82AI_Modal.showError(
                                'Error',
                                response.data.message || 'Failed to delete feed'
                            );
                        }
                    },
                    error: function (xhr, status, error) {
                        Blog82AI_Modal.showError('Error', error);
                    }
                });
            }
        );
    };

    window.bulkFetchAll = function () {
        const activeIds = allFeeds
            .filter(f => f.status === 'active')
            .map(f => f.id);

        if (activeIds.length === 0) {
            Blog82AI_Modal.showError('Error', 'No active feeds found.');
            return;
        }

        Blog82AI_Modal.showConfirm(
            'wptestings.test says',
            'Fetch new posts from all active feeds now?',
            function () {
                // User confirmed - proceed with bulk fetch
                Blog82AI_Modal.showLoading('Fetching all active feeds...');

                $.ajax({
                    url: blogibotFeed.ajax_url,
                    type: 'POST',
                    data: {
                        action: 'blogibot_bulk_feed_action',
                        nonce: blogibotFeed.nonce,
                        feed_ids: activeIds,
                        action_type: 'fetch'
                    },
                    success: function (response) {
                        Blog82AI_Modal.closeLoading();
                        if (response.success) {
                            Blog82AI_Modal.showSuccess('Success', response.data.message, true);
                            setTimeout(function () {
                                loadFeeds();
                            }, 2000);
                        } else {
                            Blog82AI_Modal.showError('Error', response.data.message || 'Bulk fetch failed');
                        }
                    },
                    error: function (xhr, status, error) {
                        Blog82AI_Modal.closeLoading();
                        Blog82AI_Modal.showError('Error', error);
                    }
                });
            }
        );
    };

})(jQuery);
