/**
 * API Manager Specific JavaScript
 * Tab functionality is handled by tabs-common.js
 * This file only contains API key management specific logic
 */
(function($) {
    'use strict';

    const APIKeysManager = {
        init: function() {
            this.bindEvents();
        },

        bindEvents: function() {
            $(document)
                .off('click.aiautotoolApiKeys', '.btn-add-api-key')
                .off('click.aiautotoolApiKeys', '.btn-remove-key')
                .off('click.aiautotoolApiKeys', '.btn-test-key')
                .off('click.aiautotoolApiKeys', '.btn-toggle-key');

            $(document)
                .on('click.aiautotoolApiKeys', '.btn-add-api-key', this.handleAddKey)
                .on('click.aiautotoolApiKeys', '.btn-remove-key', this.handleRemoveKey)
                .on('click.aiautotoolApiKeys', '.btn-test-key', this.handleTestKey)
                .on('click.aiautotoolApiKeys', '.btn-toggle-key', this.handleToggleStatus);
        },

        handleAddKey: function(e) {
            e.preventDefault();
            e.stopImmediatePropagation();
            
            const $form = $(this).closest('.add-key-form');
            const provider = $form.data('provider');
            const apiKey = $form.find('.input-api-key').val().trim();
            const name = $form.find('.input-key-name').val().trim();
            const $btn = $(this);

            if ($form.data('adding') || $btn.prop('disabled')) {
                return;
            }
            
            if (!apiKey) {
                Swal.fire({
                    icon: 'warning',
                    title: aiautotool_api_manager.strings.error,
                    text: 'Please enter an API key',
                    confirmButtonColor: '#dc3545'
                });
                return;
            }
            
            const originalHtml = $btn.html();
            
            $form.data('adding', true);
            $btn.prop('disabled', true).html('<i class="fa-solid fa-spinner fa-spin"></i> Adding...');
            
            $.ajax({
                url: aiautotool_api_manager.ajax_url,
                type: 'POST',
                data: {
                    action: 'aiautotool_add_api_key',
                    nonce: aiautotool_api_manager.nonce,
                    provider: provider,
                    api_key: apiKey,
                    name: name
                },
                success: function(response) {
                    if (response.success) {
                        Swal.fire({
                            icon: 'success',
                            title: aiautotool_api_manager.strings.success,
                            text: response.data.message,
                            confirmButtonColor: '#00875c',
                            timer: 2000
                        });
                        
                        // Clear form
                        $form.find('.input-api-key').val('');
                        $form.find('.input-key-name').val('');
                        
                        // Reload page to show new key
                        setTimeout(function() {
                            location.reload();
                        }, 1500);
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: aiautotool_api_manager.strings.error,
                            text: response.data.message,
                            confirmButtonColor: '#dc3545'
                        });
                    }
                },
                error: function() {
                    Swal.fire({
                        icon: 'error',
                        title: aiautotool_api_manager.strings.error,
                        text: 'Failed to add API key. Please try again.',
                        confirmButtonColor: '#dc3545'
                    });
                },
                complete: function() {
                    $form.removeData('adding');
                    $btn.prop('disabled', false).html(originalHtml);
                }
            });
        },

        handleRemoveKey: function(e) {
            e.preventDefault();
            
            const provider = $(this).data('provider');
            const keyId = $(this).data('key-id');
            const $keyItem = $(this).closest('.api-key-item');
            
            Swal.fire({
                title: 'Are you sure?',
                text: "Do you want to remove this API key?",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#dc3545',
                cancelButtonColor: '#6c757d',
                confirmButtonText: 'Yes, remove it!',
                cancelButtonText: 'Cancel'
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: aiautotool_api_manager.ajax_url,
                        type: 'POST',
                        data: {
                            action: 'aiautotool_remove_api_key',
                            nonce: aiautotool_api_manager.nonce,
                            provider: provider,
                            key_id: keyId
                        },
                        success: function(response) {
                            if (response.success) {
                                $keyItem.fadeOut(300, function() {
                                    $(this).remove();
                                    
                                    // Check if list is empty
                                    const $list = $('.api-keys-list[data-provider="' + provider + '"]');
                                    if ($list.find('.api-key-item').length === 0) {
                                        $list.html('<div class="empty-state"><i class="fa-solid fa-key"></i><p>No API keys added yet. Add your first key above.</p></div>');
                                    }
                                });
                                
                                Swal.fire({
                                    icon: 'success',
                                    title: 'Removed!',
                                    text: response.data.message,
                                    confirmButtonColor: '#00875c',
                                    timer: 2000
                                });
                            } else {
                                Swal.fire({
                                    icon: 'error',
                                    title: aiautotool_api_manager.strings.error,
                                    text: response.data.message,
                                    confirmButtonColor: '#dc3545'
                                });
                            }
                        },
                        error: function() {
                            Swal.fire({
                                icon: 'error',
                                title: aiautotool_api_manager.strings.error,
                                text: 'Failed to remove API key. Please try again.',
                                confirmButtonColor: '#dc3545'
                            });
                        }
                    });
                }
            });
        },

        handleTestKey: function(e) {
            e.preventDefault();
            
            const provider = $(this).data('provider');
            const apiKey = $(this).data('api-key');
            const $btn = $(this);
            const originalHtml = $btn.html();
            
            $btn.prop('disabled', true).html('<i class="fa-solid fa-spinner fa-spin"></i>');
            
            $.ajax({
                url: aiautotool_api_manager.ajax_url,
                type: 'POST',
                data: {
                    action: 'aiautotool_test_specific_key',
                    nonce: aiautotool_api_manager.nonce,
                    provider: provider,
                    api_key: apiKey
                },
                success: function(response) {
                    if (response.success) {
                        Swal.fire({
                            icon: 'success',
                            title: aiautotool_api_manager.strings.success,
                            text: response.data.message,
                            confirmButtonColor: '#00875c'
                        });
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: aiautotool_api_manager.strings.error,
                            text: response.data.message,
                            confirmButtonColor: '#dc3545'
                        });
                    }
                },
                error: function() {
                    Swal.fire({
                        icon: 'error',
                        title: aiautotool_api_manager.strings.error,
                        text: 'Failed to test API key. Please try again.',
                        confirmButtonColor: '#dc3545'
                    });
                },
                complete: function() {
                    $btn.prop('disabled', false).html(originalHtml);
                }
            });
        },

        handleToggleStatus: function(e) {
            e.preventDefault();
            
            const provider = $(this).data('provider');
            const keyId = $(this).data('key-id');
            const $btn = $(this);
            const $keyItem = $btn.closest('.api-key-item');
            const $badge = $keyItem.find('.api-key-status-badge');
            const originalHtml = $btn.html();
            
            $btn.prop('disabled', true).html('<i class="fa-solid fa-spinner fa-spin"></i>');
            
            $.ajax({
                url: aiautotool_api_manager.ajax_url,
                type: 'POST',
                data: {
                    action: 'aiautotool_toggle_key_status',
                    nonce: aiautotool_api_manager.nonce,
                    provider: provider,
                    key_id: keyId
                },
                success: function(response) {
                    if (response.success) {
                        // Toggle visual state
                        $keyItem.toggleClass('disabled');
                        
                        if ($keyItem.hasClass('disabled')) {
                            $badge.removeClass('active').addClass('disabled').text('Disabled');
                            $btn.html('<i class="fa-solid fa-check"></i> Enable');
                        } else {
                            $badge.removeClass('disabled').addClass('active').text('Active');
                            $btn.html('<i class="fa-solid fa-ban"></i> Disable');
                        }
                        
                        // Show toast notification
                        const Toast = Swal.mixin({
                            toast: true,
                            position: 'top-end',
                            showConfirmButton: false,
                            timer: 2000,
                            timerProgressBar: true
                        });
                        
                        Toast.fire({
                            icon: 'success',
                            title: response.data.message
                        });
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: aiautotool_api_manager.strings.error,
                            text: response.data.message,
                            confirmButtonColor: '#dc3545'
                        });
                        $btn.html(originalHtml);
                    }
                },
                error: function() {
                    Swal.fire({
                        icon: 'error',
                        title: aiautotool_api_manager.strings.error,
                        text: 'Failed to update status. Please try again.',
                        confirmButtonColor: '#dc3545'
                    });
                    $btn.html(originalHtml);
                },
                complete: function() {
                    $btn.prop('disabled', false);
                }
            });
        }
    };

    // Initialize when document is ready
    $(document).ready(function() {
        APIKeysManager.init();
    });

    // Make APIKeysManager available globally
    window.APIKeysManager = APIKeysManager;

})(jQuery);

