jQuery(document).ready(function($) {
    // Delete client functionality
    $(document).on("click", ".delete-client", function(e) {
        e.preventDefault();
        
        const $button = $(this);
        const clientId = $button.data("id");
        const clientEmail = $button.closest("tr").find("td:nth-child(2) div").text().trim(); // Get email from second column
        
        // Always show our custom choice dialog (ignore existing confirmation systems)
        // Create custom confirmation dialog with choice
        const choiceDialog = `
            <div class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50">
                <div class="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white">
                    <div class="mt-3 text-center">
                        <div class="mx-auto flex items-center justify-center h-12 w-12 rounded-full bg-red-100">
                            <svg class="h-6 w-6 text-red-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z"></path>
                            </svg>
                        </div>
                        <h3 class="text-lg leading-6 font-medium text-gray-900 mt-4">Delete Client</h3>
                        <div class="mt-2 px-7">
                            <p class="text-sm text-gray-500">
                                Are you sure you want to delete client "<strong>${clientEmail}</strong>"?
                            </p>
                            <div class="mt-4 p-3 bg-yellow-50 border border-yellow-200 rounded-md">
                                <p class="text-sm text-yellow-800">
                                    <strong>Important:</strong> This client may have associated invoices, quotes, and payments.
                                </p>
                            </div>
                        </div>
                    </div>
                    <div class="mt-4 flex justify-center space-x-3">
                        <button type="button" class="delete-client-only px-4 py-2 bg-blue-600 text-white text-sm font-medium rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500">
                            Delete Client Only
                        </button>
                        <button type="button" class="delete-client-and-docs px-4 py-2 bg-red-600 text-white text-sm font-medium rounded-md hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-red-500">
                            Delete All
                        </button>
                        <button type="button" class="cancel-delete px-4 py-2 bg-gray-300 text-gray-700 text-sm font-medium rounded-md hover:bg-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-500">
                            Cancel
                        </button>
                    </div>
                </div>
            </div>
        `;
        
        // Remove any existing confirmation dialogs first
        $('body').find('.fixed.inset-0').remove();
        
        // Add our dialog to page
        $('body').append(choiceDialog);
        
        // Handle delete client only (preserve documents)
        $('.delete-client-only').on('click', function() {
            $('body').find('.fixed.inset-0').remove();
            deleteClient(clientId, false);
        });
        
        // Handle delete client and all documents
        $('.delete-client-and-docs').on('click', function() {
            $('body').find('.fixed.inset-0').remove();
            deleteClient(clientId, true);
        });
        
        // Handle cancel
        $('.cancel-delete').on('click', function() {
            $('body').find('.fixed.inset-0').remove();
        });
    });
    
    // Function to handle client deletion
    function deleteClient(clientId, deleteAssociatedDocuments) {
        const $button = $('.delete-client[data-id="' + clientId + '"]');
        const clientName = $button.closest("tr").find("td:first-child div").text().trim();
        
        // Disable the button to prevent double-clicks
        $button.prop('disabled', true);
        
        $.ajax({
            url: easyInvoice.ajaxUrl,
            type: "POST",
            data: {
                action: "easy_invoice_delete_client",
                client_id: clientId,
                delete_associated_documents: deleteAssociatedDocuments,
                nonce: easyInvoice.nonce
            },
            success: function(response) {
                if (response.success) {
                    const message = deleteAssociatedDocuments ? 
                        'Client and all associated documents deleted successfully' : 
                        'Client deleted successfully. Documents preserved.';
                    
                    if (typeof EasyInvoiceToast !== 'undefined') {
                        EasyInvoiceToast.show('success', response.data.message || message);
                    }
                    
                    // Remove the row
                    const $row = $button.closest("tr");
                    $row.fadeOut(400, function() {
                        $row.remove();
                        
                        // Update total clients count
                        const $countElement = $("h3:contains('Total Clients')").next();
                        const currentCount = parseInt($countElement.text()) || 0;
                        $countElement.text(Math.max(0, currentCount - 1));
                        
                        // Check if table is empty and show "No clients found"
                        if ($("tbody tr").length === 0) {
                            $("tbody").html('<tr><td colspan="6" class="px-6 py-4 whitespace-nowrap text-center text-sm text-gray-500">No clients found</td></tr>');
                        }
                    });
                    
                    // Reload the page after a short delay to ensure everything is updated
                    setTimeout(function() {
                        window.location.reload();
                    }, 1000);
                } else {
                    const errorMessage = response.data.message || 'Error deleting client';
                    if (typeof EasyInvoiceToast !== 'undefined') {
                        EasyInvoiceToast.show('error', errorMessage);
                    }
                    $button.prop('disabled', false);
                }
            },
            error: function(xhr) {
                let errorMessage = 'Error connecting to server';
                if (xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message) {
                    errorMessage = xhr.responseJSON.data.message;
                }
                if (typeof EasyInvoiceToast !== 'undefined') {
                    EasyInvoiceToast.show('error', errorMessage);
                }
                $button.prop('disabled', false);
            }
        });
    }
});
