/**
 * Token Editor JavaScript
 *
 * @package FunnelKit_Square
 * @subpackage Admin
 */

/* global fkwcsq_token_editor, FKWCSQTokenEditor */

(function ($) {
    'use strict';

    /**
     * Token Editor Class
     */
    window.FKWCSQTokenEditor = {

        /**
         * Initialize
         */
        init() {
            this.bindEvents();
            this.updateNoTokensMessages();
        },

        /**
         * Bind events
         */
        bindEvents() {
            $(document).on('click', '.fkwcsq-payment-gateway-token-editor-action-button', this.handleActionClick);
            $(document).on('click', '.fkwcsq-payment-gateway-token-action-button', this.handleTokenActionClick);
            $(document).on('change', '.fkwcsq_payment_gateway_token_editor input[type="radio"]', this.handleDefaultChange);
        },

        /**
         * Handle action button click
         */
        handleActionClick(e) {
            e.preventDefault();

            const $button = $(this);
            const action = $button.data('action');
            const userId = $button.data('user-id');
            const $editor = $button.closest('.fkwcsq_payment_gateway_token_editor');

            switch (action) {
            case 'refresh':
                FKWCSQTokenEditor.refreshTokens($editor, userId);
                break;
            case 'save':
                FKWCSQTokenEditor.saveTokens($editor, userId);
                break;
            }
        },

        /**
         * Handle token action button click
         */
        handleTokenActionClick(e) {
            e.preventDefault();

            const $button = $(this);
            const action = $button.data('action');
            const tokenId = $button.data('token-id');
            const paymentTokenId = $button.data('payment-token-id');
            const userId = $button.data('user-id');
            const $editor = $button.closest('.fkwcsq_payment_gateway_token_editor');

            switch (action) {
            case 'remove':
                FKWCSQTokenEditor.removeToken($editor, userId, tokenId, paymentTokenId);
                break;
            }
        },

        /**
         * Handle default token change
         */
        handleDefaultChange(_e) {
            const $radio = $(this);
            const $row = $radio.closest('tr');

            // Remove active class from all rows
            $radio.closest('table').find('tr').removeClass('active');

            // Add active class to current row
            $row.addClass('active');
        },

        /**
         * Refresh tokens
         */
        refreshTokens($editor, userId) {
            this.setLoading($editor, true);

            $.ajax({
                url: fkwcsq_token_editor.ajax_url,
                type: 'POST',
                data: {
                    action: 'fkwcsq_square_admin_refresh_payment_tokens',
                    user_id: userId,
                    security: fkwcsq_token_editor.actions.refresh.nonce
                },
                success(response) {
                    if (response.success) {
                        $editor.find('tbody.tokens').html(response.data);
                        FKWCSQTokenEditor.updateNoTokensMessage($editor);
                        FKWCSQTokenEditor.showNotice('Tokens refreshed successfully.', 'success');
                    } else {
                        FKWCSQTokenEditor.showNotice(response.data || 'Failed to refresh tokens.', 'error');
                    }
                },
                error() {
                    FKWCSQTokenEditor.showNotice('An error occurred while refreshing tokens.', 'error');
                },
                complete() {
                    FKWCSQTokenEditor.setLoading($editor, false);
                }
            });
        },

        /**
         * Save tokens
         */
        saveTokens($editor, userId) {
            const tokens = [];

            // Collect token data
            $editor.find('tbody.tokens tr.token').each(function () {
                const $row = $(this);
                const token = {};

                $row.find('input, select').each(function () {
                    const $input = $(this);
                    const name = $input.attr('name');

                    if (name && name.indexOf('[') > -1) {
                        const parts = name.match(/\[([^\]]+)\]/g);
                        if (parts) {
                            const field = parts[parts.length - 1].replace(/[\[\]]/g, '');
                            token[field] = $input.val();
                        }
                    }
                });

                if (token.id) {
                    tokens.push(token);
                }
            });

            // Get default token
            const defaultToken = $editor.find('input[name$="_default"]:checked').val();

            // Get WordPress nonce from data attribute
            const wpnonce = $editor.data('wpnonce');

            this.setLoading($editor, true);

            $.ajax({
                url: fkwcsq_token_editor.ajax_url,
                type: 'POST',
                data: {
                    action: 'fkwcsq_square_admin_save_payment_tokens',
                    fkwcsq_square_tokens: JSON.stringify(tokens),
                    fkwcsq_square_tokens_default: defaultToken,
                    user_id: userId,
                    security: fkwcsq_token_editor.actions.save.nonce,
                    _wpnonce: wpnonce
                },
                success(response) {
                    if (response.success) {
                        FKWCSQTokenEditor.showNotice('Tokens saved successfully.', 'success');
                        // Refresh the page after successful save
                        setTimeout(function () {
                            window.location.reload();
                        }, 1000);
                    } else {
                        FKWCSQTokenEditor.showNotice(response.data || 'Failed to save tokens.', 'error');
                    }
                },
                error() {
                    FKWCSQTokenEditor.showNotice('An error occurred while saving tokens.', 'error');
                },
                complete() {
                    FKWCSQTokenEditor.setLoading($editor, false);
                }
            });
        },

        /**
         * Remove token
         */
        removeToken($editor, userId, tokenId, paymentTokenId) {
            if (!confirm(fkwcsq_token_editor.actions.remove_token.ays)) {
                return;
            }

            $.ajax({
                url: fkwcsq_token_editor.ajax_url,
                type: 'POST',
                data: {
                    action: 'fkwcsq_square_admin_remove_payment_token',
                    user_id: userId,
                    token_id: tokenId,
                    payment_token_id: paymentTokenId,
                    security: fkwcsq_token_editor.actions.remove_token.nonce
                },
                success(response) {
                    if (response.success) {
                        FKWCSQTokenEditor.showNotice('Token removed successfully.', 'success');
                        // Refresh the page after successful deletion
                        setTimeout(function () {
                            window.location.reload();
                        }, 1000);
                    } else {
                        FKWCSQTokenEditor.showNotice(response.data || 'Failed to remove token.', 'error');
                    }
                },
                error() {
                    FKWCSQTokenEditor.showNotice('An error occurred while removing token.', 'error');
                }
            });
        },

        /**
         * Set loading state
         */
        setLoading($editor, loading) {
            if (loading) {
                $editor.addClass('loading');
                $editor.find('.fkwcsq-payment-gateway-token-editor-action-button').prop('disabled', true);
            } else {
                $editor.removeClass('loading');
                $editor.find('.fkwcsq-payment-gateway-token-editor-action-button').prop('disabled', false);
            }
        },

        /**
         * Show notice
         */
        showNotice(message, type) {
            const $notice = $('<div>').addClass(`notice notice-${type} is-dismissible`)
                .append($('<p>').text(message));

            $('.fkwcsq_payment_gateway_user_settings').before($notice);

            // Auto-dismiss after 5 seconds
            setTimeout(function () {
                $notice.fadeOut(300, function () {
                    $(this).remove();
                });
            }, 5000);
        },

        /**
         * Update no tokens message
         */
        updateNoTokensMessage($editor) {
            const tokenCount = $editor.find('tbody.tokens tr.token').length;
            const $noTokens = $editor.find('.no-tokens');

            if (tokenCount === 0) {
                $noTokens.show();
            } else {
                $noTokens.hide();
            }
        },

        /**
         * Update no tokens messages for all editors
         */
        updateNoTokensMessages() {
            $('.fkwcsq_payment_gateway_token_editor').each(function () {
                FKWCSQTokenEditor.updateNoTokensMessage($(this));
            });
        }
    };

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

})(jQuery);
