// Groups JavaScript functionality
let currentPage = 1;
let searchQuery = '';
let filters = {
    privacy: [],
    memberCount: [],
    activityLevel: [],
    location: [],
    categories: []
};


// Render group card
function renderGroupCard(group) {
    const privacyBadge = group.privacy === 'private' ? 
        '<span class="badge bg-warning text-dark"><i class="fas fa-lock me-1"></i>Private</span>' : 
        '<span class="badge bg-success"><i class="fas fa-globe me-1"></i>Public</span>';
    
    const featuredBadge = group.is_featured ? 
        '<span class="badge bg-primary"><i class="fas fa-star me-1"></i>Featured</span>' : '';
    
    const joinButton = group.already_member ? 
        `<button class="btn btn-secondary" disabled>
            <i class="fas fa-check me-2"></i>Already Joined
        </button>` :
        `<button class="btn btn-primary join-group-btn" data-group-id="${group.id}">
            <i class="fas fa-user-plus me-2"></i>Join Group
        </button>`;
    
    const leaveButton = group.already_member ? 
        `<button class="btn btn-outline-danger leave-group-btn" data-group-id="${group.id}">
            <i class="fas fa-user-minus me-2"></i>Leave Group
        </button>` : '';

    return `
        <div class="col-md-6 col-lg-4 mb-4">
            <div class="card h-100 border-0 shadow-sm hover-shadow-md transition-hover">
                <div class="position-relative">
                    <img src="${group.cover_image || base_url + '/assets/images/default-group-cover.jpg'}" 
                         class="card-img-top" alt="Group Cover" style="height: 140px; object-fit: cover;">
                    <div class="position-absolute top-0 end-0 p-2">
                        ${privacyBadge}
                        ${featuredBadge}
                    </div>
                </div>
                <div class="card-body mt-2">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <h5 class="card-title mb-0">
                            <a href="${base_url}/group/${group.slug}" class="text-decoration-none">
                                ${group.name}
                            </a>
                        </h5>
                        <div class="dropdown">
                            <button class="btn btn-icon btn-sm btn-light rounded-circle" data-bs-toggle="dropdown">
                                <i class="fas fa-ellipsis-h"></i>
                            </button>
                            <ul class="dropdown-menu">
                                <li><a class="dropdown-item" href="#"><i class="fas fa-bookmark me-2"></i>Save Group</a></li>
                                <li><a class="dropdown-item" href="#"><i class="fas fa-flag me-2"></i>Report</a></li>
                                <li><a class="dropdown-item" href="#"><i class="fas fa-share me-2"></i>Share</a></li>
                            </ul>
                        </div>
                    </div>
                    <div class="d-flex flex-wrap gap-2 mb-3">
                        <span class="badge bg-light text-dark">
                            <i class="fas fa-users me-1"></i>${group.members_count} members
                        </span>
                        <span class="badge bg-light text-dark">
                            <i class="fas fa-calendar me-1"></i>${new Date(group.created_at).toLocaleDateString()}
                        </span>
                    </div>
                    <p class="card-text small text-muted mb-3">${group.description}</p>
                </div>
                <div class="card-footer bg-white border-0 pt-0">
                    <div class="d-grid gap-2">
                        ${joinButton}
                        ${leaveButton}
                    </div>
                </div>
            </div>
        </div>
    `;
}

// Get all groups
function get_all_groups(page = 1, isMe = false, additionalFilters = {}) {
    const searchInput = $('.search-group').val() || '';
    const categoryFilter = $('.category-filter').val() || '';
    
    // Show loading state
    showLoadingState();
    
    const params = {
        page: page,
        search: searchInput,
        isMe: isMe,
        categories: categoryFilter, // Backend expects 'categories' not 'category'
        ...additionalFilters
    };

    // Handle filters object - convert arrays to single values where needed
    if (filters.privacy && filters.privacy.length > 0) {
        // Backend expects single privacy value, take first one
        params.privacy = filters.privacy[0];
    }
    
    if (filters.memberCount && filters.memberCount.length > 0) {
        params.member_count = filters.memberCount[0];
    }
    
    if (filters.activityLevel && filters.activityLevel.length > 0) {
        params.activity_level = filters.activityLevel[0];
    }
    
    if (filters.location && filters.location.length > 0) {
        params.location = filters.location[0];
    }
    
    if (filters.categories && filters.categories.length > 0) {
        // Merge with categoryFilter if both exist
        params.categories = categoryFilter ? 
            [categoryFilter, ...filters.categories].join(',') : 
            filters.categories.join(',');
    }

    // Remove empty filters
    Object.keys(params).forEach(key => {
        if (params[key] === '' || (Array.isArray(params[key]) && params[key].length === 0)) {
            delete params[key];
        }
    });

    axios.get(`${base_url}/webapi/groups/all`, { params })
        .then(response => {
            if (response.status === 200) {
                const groups = response.data.data || [];
                const pagination = response.data.pagination;
                
                // Update pagination UI
                if (pagination) {
                    updatePagination(pagination);
                }
                
                // Update groups grid
                updateGroupsGrid(groups);
                
                // Hide loading state
                hideLoadingState();
            }
        })
        .catch(error => {
            console.error('Error fetching groups:', error);
            console.error('Error response:', error.response);
            console.error('Error status:', error.response?.status);
            console.error('Error data:', error.response?.data);
            
            hideLoadingState();
            
            let errorMessage = 'Failed to load groups. Please try again.';
            
            if (error.response) {
                // Server responded with error status
                if (error.response.status === 401) {
                    errorMessage = 'Please log in to view groups.';
                } else if (error.response.status === 403) {
                    errorMessage = 'You do not have permission to view groups.';
                } else if (error.response.status === 500) {
                    errorMessage = 'Server error. Please try again later.';
                } else if (error.response.data?.message) {
                    errorMessage = error.response.data.message;
                }
            } else if (error.request) {
                // Request was made but no response received
                errorMessage = 'Network error. Please check your connection.';
            }
            
            showErrorState(errorMessage);
        });
}

// Get liked groups (groups user has joined)
function get_liked_groups(page = 1) {
    showLoadingState();
    
    const searchInput = $('.search-group').val() || '';
    const categoryFilter = $('.category-filter').val() || '';
    
    const params = {
        page: page,
        following: true,
        search: searchInput,
        categories: categoryFilter, // Backend expects 'categories' not 'category'
    };

    // Handle filters object - convert arrays to single values where needed
    if (filters.privacy && filters.privacy.length > 0) {
        // Backend expects single privacy value, take first one
        params.privacy = filters.privacy[0];
    }
    
    if (filters.memberCount && filters.memberCount.length > 0) {
        params.member_count = filters.memberCount[0];
    }
    
    if (filters.activityLevel && filters.activityLevel.length > 0) {
        params.activity_level = filters.activityLevel[0];
    }
    
    if (filters.location && filters.location.length > 0) {
        params.location = filters.location[0];
    }
    
    if (filters.categories && filters.categories.length > 0) {
        // Merge with categoryFilter if both exist
        params.categories = categoryFilter ? 
            [categoryFilter, ...filters.categories].join(',') : 
            filters.categories.join(',');
    }

    // Remove empty filters
    Object.keys(params).forEach(key => {
        if (params[key] === '' || (Array.isArray(params[key]) && params[key].length === 0)) {
            delete params[key];
        }
    });

    axios.get(`${base_url}/webapi/groups/all`, { params })
        .then(response => {
            if (response.status === 200) {
                const groups = response.data.data || [];
                const pagination = response.data.pagination;
                
                // Update pagination UI
                if (pagination) {
                    updatePagination(pagination);
                }
                
                // Update groups grid
                updateGroupsGrid(groups, 'liked');
                
                // Hide loading state
                hideLoadingState();
            }
        })
        .catch(error => {
            console.error('Error fetching liked groups:', error);
            console.error('Error response:', error.response);
            console.error('Error status:', error.response?.status);
            console.error('Error data:', error.response?.data);
            
            hideLoadingState();
            
            let errorMessage = 'Failed to load liked groups. Please try again.';
            
            if (error.response) {
                // Server responded with error status
                if (error.response.status === 401) {
                    errorMessage = 'Please log in to view groups.';
                } else if (error.response.status === 403) {
                    errorMessage = 'You do not have permission to view groups.';
                } else if (error.response.status === 500) {
                    errorMessage = 'Server error. Please try again later.';
                } else if (error.response.data?.message) {
                    errorMessage = error.response.data.message;
                }
            } else if (error.request) {
                // Request was made but no response received
                errorMessage = 'Network error. Please check your connection.';
            }
            
            showErrorState(errorMessage);
        });
}

// Show loading state
function showLoadingState() {
    const groupsContainer = $('.groups-grid');
    groupsContainer.html(`
        <div class="col-12">
            <div class="text-center py-5">
                <div class="spinner-border text-primary mb-3" role="status">
                    <span class="visually-hidden">Loading...</span>
                </div>
                <p class="text-muted">Loading groups...</p>
            </div>
        </div>
    `);
}

// Hide loading state
function hideLoadingState() {
    // Loading state will be replaced by actual content
}

// Show error state
function showErrorState(message) {
    const groupsContainer = $('.groups-grid');
    groupsContainer.html(`
        <div class="col-12">
            <div class="text-center py-5">
                <i class="fas fa-exclamation-triangle fa-3x text-warning mb-3"></i>
                <h5 class="text-muted">${message}</h5>
                <button class="btn btn-primary" onclick="location.reload()">
                    <i class="fas fa-refresh me-2"></i>Try Again
                </button>
            </div>
        </div>
    `);
}

// Update groups grid
function updateGroupsGrid(groups, type = 'all') {
    const groupsContainer = $('.groups-grid');
    groupsContainer.empty();

    if (groups.length === 0) {
        let emptyMessage = 'No groups found';
        let emptyDescription = 'Try adjusting your search or filters';
        
        if (type === 'liked') {
            emptyMessage = 'No liked groups found';
            emptyDescription = 'You haven\'t joined any groups yet';
        } else if (type === 'my') {
            emptyMessage = 'No groups created yet';
            emptyDescription = 'Create your first group to get started';
        }
        
        groupsContainer.html(`
            <div class="col-12">
                <div class="text-center py-5">
                    <i class="fas fa-users fa-3x text-muted mb-3"></i>
                    <h5 class="text-muted">${emptyMessage}</h5>
                    <p class="text-muted">${emptyDescription}</p>
                    ${type === 'my' ? '<a href="' + base_url + '/group/create" class="btn btn-primary"><i class="fas fa-plus me-2"></i>Create Group</a>' : ''}
                </div>
            </div>
        `);
        return;
    }

    groups.forEach(group => {
        groupsContainer.append(renderGroupCard(group));
    });
}

// Update pagination
function updatePagination(pagination) {
    const paginationContainer = $('#pagination');
    paginationContainer.empty();
    
    if (pagination.total_pages > 1) {
        // Previous button
        paginationContainer.append(`
            <li class="page-item ${pagination.current_page === 1 ? 'disabled' : ''}">
                <a class="page-link" href="#" data-page="${pagination.current_page - 1}" aria-label="Previous">
                    <span aria-hidden="true">&laquo;</span>
                </a>
            </li>
        `);

        // Page numbers
        for (let i = 1; i <= pagination.total_pages; i++) {
            paginationContainer.append(`
                <li class="page-item ${pagination.current_page === i ? 'active' : ''}">
                    <a class="page-link" href="#" data-page="${i}">${i}</a>
                </li>
            `);
        }

        // Next button
        paginationContainer.append(`
            <li class="page-item ${pagination.current_page === pagination.total_pages ? 'disabled' : ''}">
                <a class="page-link" href="#" data-page="${pagination.current_page + 1}" aria-label="Next">
                    <span aria-hidden="true">&raquo;</span>
                </a>
            </li>
        `);
    }
}

// Join/Leave group
function joinLeaveGroup(groupId, buttonElement) {
    const originalText = buttonElement.html();
    buttonElement.prop('disabled', true).html('<i class="fas fa-spinner fa-spin me-2"></i>Processing...');

    axios.post(`${base_url}/webapi/groups/join-leave`, { group_id: groupId })
        .then(response => {
            if (response.status === 200) {
                const action = response.data.action;
                const membersCount = response.data.members_count;
                
                // Update button based on action
                if (action === 'joined') {
                    buttonElement.removeClass('btn-primary').addClass('btn-secondary')
                        .html('<i class="fas fa-check me-2"></i>Already Joined')
                        .prop('disabled', true);
                    
                    // Show success message
                    if (typeof myAlert !== 'undefined') {
                        myAlert.fire('Success!', 'Joined group successfully', 'success');
                    }
                } else if (action === 'left') {
                    buttonElement.removeClass('btn-secondary').addClass('btn-primary')
                        .html('<i class="fas fa-user-plus me-2"></i>Join Group')
                        .prop('disabled', false);
                    
                    // Show success message
                    if (typeof myAlert !== 'undefined') {
                        myAlert.fire('Success!', 'Left group successfully', 'success');
                    }
                }
                
                // Update member count in the card
                const card = buttonElement.closest('.card');
                const memberCountBadge = card.find('.badge:contains("members")');
                memberCountBadge.html(`<i class="fas fa-users me-1"></i>${membersCount} members`);
            }
        })
        .catch(error => {
            console.error('Error joining/leaving group:', error);
            buttonElement.prop('disabled', false).html(originalText);
            
            if (typeof myAlert !== 'undefined') {
                myAlert.fire('Error!', 'Failed to join/leave group', 'error');
            }
        });
}

// Load group stats
function loadGroupStats() {
    axios.get(`${base_url}/webapi/groups/stats`)
        .then(response => {
            if (response.status === 200) {
                const stats = response.data.data;
                
                // Update stats in the UI
                $('#total-groups-count').text(stats.total_groups);
                $('#joined-groups-count').text(stats.joined_groups);
                $('#my-groups-count').text(stats.my_groups);
                $('#public-groups-count').text(stats.public_groups);
                $('#private-groups-count').text(stats.private_groups);
                $('#featured-groups-count').text(stats.featured_groups);
                $('#recent-groups-count').text(stats.recent_groups);
                
                // Update quick filter badges
                $('#all-groups-count').text(stats.total_groups);
                $('#my-groups-count-pill').text(stats.my_groups);
                $('#joined-groups-count-pill').text(stats.joined_groups);
                $('#public-groups-count').text(stats.public_groups);
                $('#featured-groups-count-pill').text(stats.featured_groups);
            }
        })
        .catch(error => {
            console.error('Error loading group stats:', error);
        });
}

// Handle quick filters
function handleQuickFilters() {
    $('.quick-filter').on('click', function() {
        $('.quick-filter').removeClass('active');
        $(this).addClass('active');
        
        const filter = $(this).data('filter');
        applyQuickFilter(filter);
    });
}

// Apply quick filter
function applyQuickFilter(filter) {
    switch (filter) {
        case 'all':
            filters = {
                privacy: [],
                memberCount: [],
                activityLevel: [],
                location: [],
                categories: []
            };
            break;
        case 'my':
            // This will be handled by isMe parameter
            break;
        case 'joined':
            // This will be handled by following parameter
            break;
        case 'public':
            filters.privacy = ['public'];
            break;
        case 'private':
            filters.privacy = ['private'];
            break;
        case 'featured':
            // This would need to be implemented in the backend
            break;
    }
    
    currentPage = 1;
    
    // Determine which function to call based on current page
    if (window.location.pathname.includes('liked-groups')) {
        get_liked_groups(1);
    } else if (window.location.pathname.includes('my-groups')) {
        get_all_groups(1, true);
    } else {
        get_all_groups(1, false);
    }
}

// Handle advanced filters
function handleAdvancedFilters() {
    $('.advanced-filter').on('change', function() {
        const filterType = $(this).data('filter-type');
        const value = $(this).val();
        
        if ($(this).is(':checked')) {
            if (!filters[filterType].includes(value)) {
                filters[filterType].push(value);
            }
        } else {
            filters[filterType] = filters[filterType].filter(item => item !== value);
        }
        
        currentPage = 1;
        
        // Determine which function to call based on current page
        if (window.location.pathname.includes('liked-groups')) {
            get_liked_groups(1);
        } else if (window.location.pathname.includes('my-groups')) {
            get_all_groups(1, true);
        } else {
            get_all_groups(1, false);
        }
    });
}

// Get advanced filters
function getAdvancedFilters() {
    const advancedFilters = {};
    
    $('.advanced-filter:checked').each(function() {
        const filterType = $(this).data('filter-type');
        const value = $(this).val();
        
        if (!advancedFilters[filterType]) {
            advancedFilters[filterType] = [];
        }
        advancedFilters[filterType].push(value);
    });
    
    return advancedFilters;
}

// Create group
function createGroup(formElement) {
    const form = $(formElement);
    const submitBtn = form.find('button[type="submit"]');
    const originalText = submitBtn.html();
    
    // Validate form
    if (!formElement.checkValidity()) {
        form.addClass('was-validated');
        return;
    }
    
    // Create FormData for file upload
    const formData = new FormData(formElement);
    
    // Disable submit button and show loading
    submitBtn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin me-2"></i>Creating...');
    
    // Submit via axios
    axios.post(`${base_url}/webapi/groups/create`, formData, {
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    })
    .then(response => {
        if (response.data.status === 200) {
            // Show success message
            if (typeof myAlert !== 'undefined') {
                myAlert.fire('Success!', response.data.message || 'Group created successfully', 'success');
            } else {
                alert(response.data.message || 'Group created successfully');
            }
            
            // Redirect to the group page or groups list
            setTimeout(() => {
                if (response.data.data && response.data.data.slug) {
                    window.location.href = `${base_url}/group/${response.data.data.slug}`;
                } else {
                    window.location.href = `${base_url}/groups`;
                }
            }, 1500);
        } else {
            throw new Error(response.data.message || 'Failed to create group');
        }
    })
    .catch(error => {
        console.error('Error creating group:', error);
        console.error('Error response:', error.response);
        
        let errorMessage = 'Failed to create group. Please try again.';
        
        if (error.response) {
            if (error.response.data?.errors) {
                // Handle validation errors
                const errors = error.response.data.errors;
                const errorMessages = [];
                
                Object.keys(errors).forEach(key => {
                    if (Array.isArray(errors[key])) {
                        errorMessages.push(errors[key].join(', '));
                    } else {
                        errorMessages.push(errors[key]);
                    }
                });
                
                errorMessage = errorMessages.join('<br>');
            } else if (error.response.data?.message) {
                errorMessage = error.response.data.message;
            }
        }
        
        // Show error message
        if (typeof myAlert !== 'undefined') {
            myAlert.fire('Error!', errorMessage, 'error');
        } else {
            alert(errorMessage);
        }
        
        // Re-enable submit button
        submitBtn.prop('disabled', false).html(originalText);
    });
}

// Document ready
$(document).ready(function() {
    // Handle create group form submission
    $('#createGroupForm').on('submit', function(e) {
        e.preventDefault();
        createGroup(this);
    });
    
    // Initialize based on current page
    if (window.location.pathname.includes('liked-groups')) {
        get_liked_groups(1);
    } else if (window.location.pathname.includes('my-groups')) {
        get_all_groups(1, true);
    } else if (!window.location.pathname.includes('create')) {
        get_all_groups(1, false);
        loadGroupStats();
    }
    
    // Handle search with debouncing
    let searchTimeout;
    $('.search-group').on('input', function() {
        clearTimeout(searchTimeout);
        searchTimeout = setTimeout(() => {
            currentPage = 1;
            
            if (window.location.pathname.includes('liked-groups')) {
                get_liked_groups(1);
            } else if (window.location.pathname.includes('my-groups')) {
                get_all_groups(1, true);
            } else {
                get_all_groups(1, false);
            }
        }, 500);
    });
    
    // Handle search button click
    $('.search-btn').on('click', function() {
        currentPage = 1;
        
        if (window.location.pathname.includes('liked-groups')) {
            get_liked_groups(1);
        } else if (window.location.pathname.includes('my-groups')) {
            get_all_groups(1, true);
        } else {
            get_all_groups(1, false);
        }
    });
    
    // Handle search on enter key
    $('.search-group').on('keypress', function(e) {
        if (e.which === 13) { // Enter key
            currentPage = 1;
            
            if (window.location.pathname.includes('liked-groups')) {
                get_liked_groups(1);
            } else if (window.location.pathname.includes('my-groups')) {
                get_all_groups(1, true);
            } else {
                get_all_groups(1, false);
            }
        }
    });
    
    // Handle category filter
    $('.category-filter').on('change', function() {
        currentPage = 1;
        
        if (window.location.pathname.includes('liked-groups')) {
            get_liked_groups(1);
        } else if (window.location.pathname.includes('my-groups')) {
            get_all_groups(1, true);
        } else {
            get_all_groups(1, false);
        }
    });
    
    // Handle clear search button
    $('.clear-search-btn').on('click', function() {
        $('.search-group').val('');
        currentPage = 1;
        
        if (window.location.pathname.includes('liked-groups')) {
            get_liked_groups(1);
        } else if (window.location.pathname.includes('my-groups')) {
            get_all_groups(1, true);
        } else {
            get_all_groups(1, false);
        }
    });
    
    // Show/hide clear search button
    $('.search-group').on('input', function() {
        if ($(this).val().length > 0) {
            $('.clear-search-btn').show();
        } else {
            $('.clear-search-btn').hide();
        }
    });
    
    // Handle join/leave group button clicks
    $(document).on('click', '.join-group-btn, .leave-group-btn', function() {
        const groupId = $(this).data('group-id');
        joinLeaveGroup(groupId, $(this));
    });
    
    // Handle pagination clicks
    $(document).on('click', '.pagination .page-link', function(e) {
        e.preventDefault();
        const page = $(this).data('page');
        if (page) {
            currentPage = page;
            
            if (window.location.pathname.includes('liked-groups')) {
                get_liked_groups(page);
            } else if (window.location.pathname.includes('my-groups')) {
                get_all_groups(page, true);
            } else {
                get_all_groups(page, false);
            }
        }
    });
    
    // Handle quick filters
    handleQuickFilters();
    
    // Handle advanced filters
    handleAdvancedFilters();
    
    // Handle apply filters button
    $('.apply-filters-btn').on('click', function() {
        const advancedFilters = getAdvancedFilters();
        currentPage = 1;
        
        if (window.location.pathname.includes('liked-groups')) {
            get_liked_groups(1, advancedFilters);
        } else if (window.location.pathname.includes('my-groups')) {
            get_all_groups(1, true, advancedFilters);
        } else {
            get_all_groups(1, false, advancedFilters);
        }
    });
    
    // Handle reset filters button
    $('.reset-filters-btn').on('click', function() {
        filters = {
            privacy: [],
            memberCount: [],
            activityLevel: [],
            location: [],
            categories: []
        };
        $('.advanced-filter').prop('checked', false);
        $('.quick-filter').removeClass('active');
        $('.quick-filter[data-filter="all"]').addClass('active');
        currentPage = 1;
        
        if (window.location.pathname.includes('liked-groups')) {
            get_liked_groups(1);
        } else if (window.location.pathname.includes('my-groups')) {
            get_all_groups(1, true);
        } else {
            get_all_groups(1, false);
        }
    });
});