// Event form handling
$(document).ready(function() {
    // Toggle approval requirement based on guests setting
    $('#allowGuests').change(function() {
        $('#requireApproval').prop('disabled', $(this).is(':checked'));
    });

    // Initialize date pickers
    if ($.fn.datepicker) {
        $('.date-filter').datepicker({
            format: 'yyyy-mm-dd',
            autoclose: true,
            todayHighlight: true
        });
    }

    // Initialize category filter
    $('.category-filter').on('change', function() {
        fetchEvents(1, isMyEvents);
    });

    // Initialize event filter
    $('.event-filter').on('change', function() {
        fetchEvents(1, isMyEvents);
    });

    // Initialize timeframe filter
    $('.timeframe-filter').on('change', function() {
        fetchEvents(1, isMyEvents);
    });

    // Initialize search functionality
    $('.search-btn').click(function() {
        fetchEvents(1, isMyEvents);
    });

    // Enter key in search box
    $('.search-event').keypress(function(e) {
        if (e.which === 13) {
            fetchEvents(1, isMyEvents);
            return false;
        }
    });

    // Handle form submission for creating/editing events
    $('#create-event-form, #edit-event-form').on('submit', function(e) {
        e.preventDefault(); // Prevent the default form submission

        // Show loading state
        const submitBtn = $(this).find('button[type="submit"]');
        const originalBtnText = submitBtn.html();
        submitBtn.html('<i class="fas fa-spinner fa-spin me-2"></i>Processing...');
        submitBtn.prop('disabled', true);

        // Create a FormData object to hold the form data
        var formData = new FormData(this);

        // Send the data using Axios
        axios.post($(this).attr('action'), formData)
            .then(function(response) {
                // Handle success
                myAlert.fire({
                    icon: 'success',
                    title: 'Success!',
                    text: response.data.message
                });
                
                // Redirect to the appropriate page
                if (response.data.data && response.data.data.slug) {
                    window.location.href = `${base_url}/events/${response.data.data.slug}`;
                } else {
                    window.location.href = `${base_url}/events`;
                }
            })
            .catch(function(error) {
                // Reset button state
                submitBtn.html(originalBtnText);
                submitBtn.prop('disabled', false);
                
                // Handle validation errors
                if (error.response && error.response.status === 422) {
                    const errors = error.response.data.errors;
                    let errorMessage = '<ul class="list-unstyled">';
                    
                    for (const field in errors) {
                        errorMessage += `<li><i class="fas fa-exclamation-circle me-2"></i>${errors[field][0]}</li>`;
                        
                        // Add error class to the field
                        $(`[name="${field}"]`).addClass('is-invalid');
                        
                        // Add error message below the field
                        if ($(`[name="${field}"]`).next('.invalid-feedback').length === 0) {
                            $(`[name="${field}"]`).after(`<div class="invalid-feedback">${errors[field][0]}</div>`);
                        }
                    }
                    
                    errorMessage += '</ul>';
                    
                    myAlert.fire({
                        icon: 'error',
                        title: 'Validation Error',
                        html: errorMessage
                    });
                } else {
                    // Handle other errors
                    myAlert.fire({
                        icon: 'error',
                        title: 'Error',
                        text: error.response ? error.response.data.message : 'An unexpected error occurred.'
                    });
                }
            });
    });

    // Clear validation errors when user starts typing
    $(document).on('input', '.form-control, .form-select', function() {
        $(this).removeClass('is-invalid');
        $(this).next('.invalid-feedback').remove();
    });

    // Initialize event filters on page load
    initializeEventFilters();
});

// Global variable to track if we're viewing "My Events" or all events
let isMyEvents = false;

// Fetch events from the API
function fetchEvents(page = 1, isMe = false) {
    isMyEvents = isMe;
    
    // Show loading state
    $('#eventholder').html('<div class="col-12 text-center py-5"><i class="fas fa-spinner fa-spin fa-3x"></i><p class="mt-3">Loading events...</p></div>');
    
    // Get filter values
    const search = $(".search-event").val() || null;
    const dateRange = $(".date-filter").val() || null;
    const category = $(".category-filter").val() || null;
    const filter = $(".event-filter").val() || null;
    const timeframe = $(".timeframe-filter").val() || null;
    
    // Build query parameters
    const params = {
        page: page,
        limit: 6,
        search: search,
        date_search: dateRange,
        isMe: isMe,
        category: category,
        filter: filter,
        timeframe: timeframe
    };
    
    // Make API request
    axios.post(`${base_url}/webapi/event/get-events`, params)
        .then(function(response) {
            if (response.data.status === 200) {
                const events = response.data.data;
                let pagination = response.data.pagination;
                const eventHolder = $('#eventholder');
                const paginationHolder = $('#pagination');

                // Clear existing content
                eventHolder.empty();
                paginationHolder.empty();

                // Check if we have events
                if (events.length === 0) {
                    eventHolder.html(`
                        <div class="col-12 text-center py-5">
                            <i class="fas fa-calendar-times fa-3x text-muted mb-3"></i>
                            <h4>No events found</h4>
                            <p class="text-muted">Try adjusting your search or filters</p>
                            <a href="${base_url}/events/create" class="btn btn-primary mt-3">
                                <i class="fas fa-plus-circle me-2"></i>Create New Event
                            </a>
                        </div>
                    `);
                    return;
                }

                // Render each event
                events.forEach(event => {
                    const eventHtml = `
                        <div class="col-md-6 col-lg-4 mb-4">
                            <div class="card h-100 border-0 shadow-sm hover-shadow-md">
                                <div class="position-relative">
                                    <img src="${event.cover_image}" class="card-img-top" alt="${event.name}" style="height: 180px; object-fit: cover;">
                                    <div class="position-absolute top-0 start-0 m-3">
                                        <span class="badge bg-${event.type === 'public' ? 'success' : 'warning'}">${event.type}</span>
                                    </div>
                                    <div class="position-absolute top-0 end-0 m-3">
                                        <span class="badge bg-${event.is_expired ? 'danger' : (event.is_going_on ? 'primary' : 'info')}">
                                            ${event.is_expired ? 'Ended' : (event.is_going_on ? 'Ongoing' : 'Upcoming')}
                                        </span>
                                    </div>
                                    <div class="position-absolute bottom-0 start-0 m-3">
                                        <span class="badge bg-light text-dark text-capitalize">
                                            <i class="fas fa-tag me-1"></i>${event.category}
                                        </span>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <h5 class="card-title mb-1">
                                        <a href="${base_url}/events/${event.slug}" class="text-decoration-none text-dark stretched-link">
                                            ${event.name}
                                        </a>
                                    </h5>
                                    <p class="text-muted small mb-2">
                                        <i class="far fa-calendar-alt me-1"></i>${event.start_date}
                                    </p>
                                    <div class="d-flex justify-content-between align-items-center mb-2">
                                        <p class="text-muted small mb-0">
                                            <i class="fas fa-map-marker-alt me-1"></i>${event.location.substring(0, 20)}${event.location.length > 20 ? '...' : ''}
                                        </p>
                                    </div>
                                    <div class="d-flex justify-content-between align-items-center">
                                        <div class="d-flex align-items-center">
                                            <img src="${event.organizer.avatar}" class="rounded-circle me-2" width="24" height="24">
                                            <span class="small text-muted">By ${event.organizer.name}</span>
                                        </div>
                                        <span class="text-muted small">
                                            <i class="fas fa-users me-1"></i>${event.participants_count}
                                        </span>
                                    </div>
                                </div>
                                <div class="card-footer bg-white border-0 pt-0">
                                    <div class="d-flex justify-content-between">
                                        <div class="btn-group w-100">
                                            ${event.already_joined ? 
                                                `<button class="btn btn-sm btn-success flex-grow-1"><i class="fas fa-check me-1"></i>Going</button>` : 
                                                `<button class="btn btn-sm btn-outline-primary flex-grow-1 btn-join-event" data-action="join" data-event-id="${event.id}"><i class="fas fa-calendar-check me-1"></i>Join</button>`}
                                            <button class="btn btn-sm btn-outline-secondary btn-interest-event" data-event-id="${event.id}">
                                                <i class="far fa-star"></i>
                                            </button>
                                            <a href="${base_url}/events/${event.slug}" class="btn btn-sm btn-outline-info">
                                                <i class="fas fa-info-circle"></i>
                                            </a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    `;
                    eventHolder.append(eventHtml);
                });

                // Build pagination
                let paginationHtml = '';
                    
                // Previous button
                paginationHtml += `
                    <li class="page-item ${pagination.current_page === 1 ? 'disabled' : ''}">
                        <a class="page-link" href="#" onclick="fetchEvents(${pagination.current_page - 1}, ${isMyEvents})" aria-label="Previous">
                            <span aria-hidden="true">&laquo;</span>
                        </a>
                    </li>
                `;

                // Page numbers
                for (let i = 1; i <= pagination.last_page; i++) {
                    paginationHtml += `
                        <li class="page-item ${pagination.current_page === i ? 'active' : ''}">
                            <a class="page-link" href="#" onclick="fetchEvents(${i}, ${isMyEvents})">${i}</a>
                        </li>
                    `;
                }

                // Next button
                paginationHtml += `
                    <li class="page-item ${pagination.current_page === pagination.last_page ? 'disabled' : ''}">
                        <a class="page-link" href="#" onclick="fetchEvents(${pagination.current_page + 1}, ${isMyEvents})" aria-label="Next">
                            <span aria-hidden="true">&raquo;</span>
                        </a>
                    </li>
                `;

                $("#pagination").html(paginationHtml);
            } else {
                console.error("Error fetching events:", response.data.message);
                $('#eventholder').html(`
                    <div class="col-12 text-center py-5">
                        <i class="fas fa-exclamation-triangle fa-3x text-warning mb-3"></i>
                        <h4>Error Loading Events</h4>
                        <p class="text-muted">${response.data.message}</p>
                        <button class="btn btn-primary mt-3" onclick="fetchEvents(1, ${isMyEvents})">
                            <i class="fas fa-sync-alt me-2"></i>Try Again
                        </button>
                    </div>
                `);
            }
        })
        .catch(function(error) {
            console.error("Error:", error);
            $('#eventholder').html(`
                <div class="col-12 text-center py-5">
                    <i class="fas fa-exclamation-triangle fa-3x text-danger mb-3"></i>
                    <h4>Error Loading Events</h4>
                    <p class="text-muted">An unexpected error occurred. Please try again.</p>
                    <button class="btn btn-primary mt-3" onclick="fetchEvents(1, ${isMyEvents})">
                        <i class="fas fa-sync-alt me-2"></i>Try Again
                    </button>
                </div>
            `);
        });
}

// Event participation handlers
$(document).on('click', '.btn-join-event', function() {
    const eventId = $(this).attr('data-event-id');
    const button = $(this);
    
    // Disable button to prevent multiple clicks
    button.prop('disabled', true);
    
    // Call the API to join the event
    axios.post(`${base_url}/webapi/event/join-event`, {
        event_id: eventId
    })
    .then(function(response) {
        if (response.data.status === 200) {
            // Show success message
            myAlert.fire({
                icon: 'success',
                title: 'Success!',
                text: response.data.message
            });
            
            // Update button state
            if (response.data.status === 'joined') {
                button.html('<i class="fas fa-check me-1"></i>Going');
                button.removeClass('btn-outline-primary').addClass('btn-success');
            } else {
                button.html('<i class="fas fa-calendar-check me-1"></i>Join');
                button.removeClass('btn-success').addClass('btn-outline-primary');
            }
        } else {
            // Show error message
            myAlert.fire({
                icon: 'error',
                title: 'Error',
                text: response.data.message
            });
        }
        
        // Re-enable button
        button.prop('disabled', false);
    })
    .catch(function(error) {
        // Show error message
        myAlert.fire({
            icon: 'error',
            title: 'Error',
            text: error.response ? error.response.data.message : 'An unexpected error occurred.'
        });
        
        // Re-enable button
        button.prop('disabled', false);
    });
});

// Interest button handler
$(document).on('click', '.btn-interest-event', function() {
    const eventId = $(this).attr('data-event-id');
    const button = $(this);
    
    // Disable button to prevent multiple clicks
    button.prop('disabled', true);
    
    // Call the API to show interest in the event
    axios.post(`${base_url}/webapi/event/show-interest`, {
        event_id: eventId
    })
    .then(function(response) {
        // Update button state
        if (response.data.status === 'interested') {
            button.html('<i class="fas fa-star"></i>');
            button.removeClass('btn-outline-secondary').addClass('btn-warning');
        } else {
            button.html('<i class="far fa-star"></i>');
            button.removeClass('btn-warning').addClass('btn-outline-secondary');
        }
        
        // Re-enable button
        button.prop('disabled', false);
    })
    .catch(function(error) {
        // Show error message
        myAlert.fire({
            icon: 'error',
            title: 'Error',
            text: error.response ? error.response.data.message : 'An unexpected error occurred.'
        });
        
        // Re-enable button
        button.prop('disabled', false);
    });
});

// Initialize event filters
function initializeEventFilters() {
    // Date range picker
    if ($.fn.daterangepicker) {
        $('.daterange-picker').daterangepicker({
            opens: 'left',
            autoUpdateInput: false,
            locale: {
                cancelLabel: 'Clear',
                format: 'YYYY-MM-DD'
            }
        });
        
        $('.daterange-picker').on('apply.daterangepicker', function(ev, picker) {
            $(this).val(picker.startDate.format('YYYY-MM-DD') + ' - ' + picker.endDate.format('YYYY-MM-DD'));
            fetchEvents(1, isMyEvents);
        });
        
        $('.daterange-picker').on('cancel.daterangepicker', function(ev, picker) {
            $(this).val('');
            fetchEvents(1, isMyEvents);
        });
    }
    
    // Reset filters button
    $('.reset-filters').click(function() {
        $('.search-event').val('');
        $('.date-filter').val('');
        $('.category-filter').val('');
        $('.event-filter').val('');
        $('.timeframe-filter').val('');
        fetchEvents(1, isMyEvents);
    });
    
    // Apply filters button
    $('.apply-filters').click(function() {
        fetchEvents(1, isMyEvents);
    });
}
