jQuery(document).ready(function($) {
    // Handle ticket header click to load ticket details
    $('.ticket-list').on('click', '.ticket-header', function() {
        var $ticketItem = $(this).closest('.ticket-item');
        var ticketId = $ticketItem.data('ticket-id');
        
        loadTicketDetails(ticketId);
    });
    
    // Handle back to list button
    $('.back-to-list-btn').on('click', function() {
        $('.ticket-detail-view').hide();
        $('.ticket-list-view').show();
    });

    // Handle adding a new message (works for both list and detail view)
    $(document).on('click', '.kaveh-add-message', function() {
        var $button = $(this);
        var ticketId = $button.data('ticket-id');
        var $messageInput = $button.closest('.ticket-reply-form').find('.ticket-reply-message');
        var messageContent = $messageInput.val();
        var $fileInput = $button.closest('.ticket-reply-form').find('.reply-attachments-input');
        var isDetailView = $('.ticket-detail-view').is(':visible');

        if (messageContent.trim() === '') {
            alert('Message cannot be empty.');
            return;
        }

        $button.prop('disabled', true).text('Sending...');

        // Create FormData to handle file uploads
        var formData = new FormData();
        formData.append('action', 'kaveh_add_ticket_message');
        formData.append('nonce', kavehTicketDashboardAjax.nonce);
        formData.append('ticket_id', ticketId);
        formData.append('message_content', messageContent);
        
        // Add files if any
        if ($fileInput[0] && $fileInput[0].files.length > 0) {
            for (var i = 0; i < $fileInput[0].files.length; i++) {
                formData.append('reply_attachments[]', $fileInput[0].files[i]);
            }
        }

        $.ajax({
            url: kavehTicketDashboardAjax.ajaxurl,
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                if (response.success) {
                    $messageInput.val(''); // Clear input
                    $fileInput.val(''); // Clear file input
                    
                    if (isDetailView) {
                        // Reload ticket details to show new message
                        loadTicketDetails(ticketId);
                    } else {
                        // Reload messages in list view
                        var $messagesDiv = $button.closest('.ticket-content').find('.ticket-messages');
                        loadTicketMessages(ticketId, $messagesDiv);
                    }
                } else {
                    alert(response.data.message);
                }
            },
            error: function() {
                alert('Error adding message.');
            },
            complete: function() {
                $button.prop('disabled', false).text('Add Reply');
            }
        });
    });

    // Handle closing a ticket (works for both list and detail view)
    $(document).on('click', '.kaveh-close-ticket', function() {
        if (!confirm('Are you sure you want to close this ticket?')) {
            return;
        }

        var $button = $(this);
        var ticketId = $button.data('ticket-id');
        var $ticketItem = $button.closest('.ticket-item');
        var isDetailView = $('.ticket-detail-view').is(':visible');

        $button.prop('disabled', true).text('Closing...');

        $.ajax({
            url: kavehTicketDashboardAjax.ajaxurl,
            type: 'POST',
            data: {
                action: 'kaveh_close_ticket',
                nonce: kavehTicketDashboardAjax.nonce,
                ticket_id: ticketId
            },
            success: function(response) {
                if (response.success) {
                    alert(response.data.message);
                    
                    if (isDetailView) {
                        // Reload ticket details to show updated status
                        loadTicketDetails(ticketId);
                    } else {
                        // Update status in list view
                        $ticketItem.find('.ticket-status').text('Closed').removeClass('status-open status-replied').addClass('status-closed');
                        $button.remove(); // Remove close button
                    }
                } else {
                    alert(response.data.message);
                }
            },
            error: function() {
                alert('Error closing ticket.');
            },
            complete: function() {
                $button.prop('disabled', false).text('Close Ticket');
            }
        });
    });

    // Handle ticket filtering
    $('#status-filter, #priority-filter').on('change', function() {
        filterTickets();
    });

    $('#clear-filters').on('click', function() {
        $('#status-filter').val('all');
        $('#priority-filter').val('all');
        filterTickets();
    });

    function filterTickets() {
        var statusFilter = $('#status-filter').val();
        var priorityFilter = $('#priority-filter').val();
        var visibleCount = 0;

        $('.ticket-item').each(function() {
            var $ticket = $(this);
            var ticketStatus = '';
            var ticketPriority = '';
            var showTicket = true;

            // Get ticket status from class names
            if ($ticket.hasClass('open')) {
                ticketStatus = 'open';
            } else if ($ticket.hasClass('replied')) {
                ticketStatus = 'replied';
            } else if ($ticket.hasClass('closed')) {
                ticketStatus = 'closed';
            }

            // Get ticket priority from priority span class
            var $prioritySpan = $ticket.find('.ticket-priority');
            if ($prioritySpan.hasClass('priority-urgent')) {
                ticketPriority = 'urgent';
            } else if ($prioritySpan.hasClass('priority-high')) {
                ticketPriority = 'high';
            } else if ($prioritySpan.hasClass('priority-medium')) {
                ticketPriority = 'medium';
            } else if ($prioritySpan.hasClass('priority-low')) {
                ticketPriority = 'low';
            }

            // Apply filters
            if (statusFilter !== 'all' && ticketStatus !== statusFilter) {
                showTicket = false;
            }

            if (priorityFilter !== 'all' && ticketPriority !== priorityFilter) {
                showTicket = false;
            }

            if (showTicket) {
                $ticket.show();
                visibleCount++;
            } else {
                $ticket.hide();
            }
        });

        // Show message if no tickets match filters
        var $noTicketsMsg = $('.no-filtered-tickets');
        if (visibleCount === 0) {
            if ($noTicketsMsg.length === 0) {
                $('.ticket-list').append('<p class="no-filtered-tickets">No tickets match the selected filters.</p>');
            }
        } else {
            $noTicketsMsg.remove();
        }
    }

    function loadTicketMessages(ticketId, $targetDiv) {
        $targetDiv.html('<p>Loading messages...</p>');
        $.ajax({
            url: kavehTicketDashboardAjax.ajaxurl,
            type: 'POST',
            data: {
                action: 'kaveh_get_ticket_messages',
                nonce: kavehTicketDashboardAjax.nonce,
                ticket_id: ticketId
            },
            success: function(response) {
                if (response.success) {
                    $targetDiv.html(response.data.messages_html);
                } else {
                    $targetDiv.html('<p>' + response.data.message + '</p>');
                }
            },
            error: function() {
                $targetDiv.html('<p>Error loading messages.</p>');
            }
        });
    }
    
    // Load ticket details in detail view
    function loadTicketDetails(ticketId) {
        $('.ticket-detail-content').html('<p>Loading ticket details...</p>');
        
        $.ajax({
            url: kavehTicketDashboardAjax.ajaxurl,
            type: 'POST',
            data: {
                action: 'kaveh_get_ticket_details',
                nonce: kavehTicketDashboardAjax.nonce,
                ticket_id: ticketId
            },
            success: function(response) {
                if (response.success) {
                    $('.ticket-detail-title').text(response.data.title);
                    $('.ticket-detail-info').html(response.data.info_html);
                    $('.ticket-detail-messages').html(response.data.messages_html);
                    $('.ticket-detail-reply-form').html(response.data.reply_form_html);
                    
                    // Show detail view and hide list view
                    $('.ticket-list-view').hide();
                    $('.ticket-detail-view').show();
                    
                    // Force visibility and ensure elements exist
                    $('.ticket-detail-view').css('display', 'block');
                    
                    // Ensure elements exist and update content
                    setTimeout(function() {
                        // If elements still not found, create them
                        if ($('.ticket-detail-info').length === 0) {
                            $('.ticket-detail-content').html(
                                '<div class="ticket-detail-info"></div>' +
                                '<div class="ticket-detail-messages"></div>' +
                                '<div class="ticket-detail-reply-form"></div>'
                            );
                        }
                        
                        // Update content
                        $('.ticket-detail-info').html(response.data.info_html);
                        $('.ticket-detail-messages').html(response.data.messages_html);
                        $('.ticket-detail-reply-form').html(response.data.reply_form_html);
                    }, 100);
                } else {
                    alert(response.data.message);
                }
            },
            error: function(xhr, status, error) {
                alert('Error loading ticket details: ' + error);
            }
        });
    }
});