class FetchCollections {

    _isFetching = false;
    _labels = {};
    _shopDomain = '';
    _selectedCollections = {};

    init() {
        if (!jQuery('#btn-fetch-collections')[0]) {
            return;
        }

        this._labels = window.SHOPYPRESS_ADMIN_SETTINGS?.labels || {};
        this._shopDomain = window.SHOPYPRESS_ADMIN_SETTINGS?.shop_domain || '';
        this._selectedCollections = window.SHOPYPRESS_ADMIN_SETTINGS?.selected_collections || {};
        this._handleEvents();

        // Fetch collections on page load
        this._fetchCollections();
    }

    _handleEvents() {
        const _this = this;

        jQuery('#btn-fetch-collections').on('click', function(e) {
            e.preventDefault();
            _this._fetchCollections(true);
        });
    }

    _fetchCollections(calledFromUserAction = false) {
        if (this._isFetching) {
            return;
        }

        const _this = this;
        const $btn = jQuery('#btn-fetch-collections');
        const $statusContainer = jQuery('#collections-status-container');
        const $listContainer = jQuery('#collections-list-container');

        // Disable button and show loading
        this._setFetching(true);
        $btn.text(this._labels.fetchingText || 'Fetching...');
        $statusContainer.html('<div class="alert alert-info">' + (this._labels.fetchingCollections || 'Fetching collections from Shopify...') + '</div>');
        $listContainer.hide();

        const ajaxPayload = {
            action: 'shopypress_fetch_collections',
            nonce: window.SHOPYPRESS_ADMIN_SETTINGS?.nonce || '',
            shop: this._shopDomain
        };

        jQuery.ajax({
            url: window.SHOPYPRESS_ADMIN_SETTINGS?.ajax_url || ajaxurl,
            type: 'POST',
            data: ajaxPayload,
            success: function(response) {
                _this._setFetching(false);
                $btn.text(_this._labels.fetchCollectionsBtn || 'Fetch Collections');

                if (response.success && response.data) {
                    const collections = response.data.collections || [];
                    const total = response.data.total || 0;

                    $statusContainer.html(
                        '<div class="alert alert-success"><strong>' +
                        (_this._labels.successText || 'Success!') +
                        '</strong> ' + total + ' ' +
                        (_this._labels.collectionsFetched || 'collections fetched.') +
                        '</div>'
                    );

                    if (collections.length > 0) {
                        _this._displayCollections(collections);
                        $listContainer.show();
                    }

                    _this._showSuccess(total + ' ' + (_this._labels.collectionsSuccess || 'collections fetched successfully'), calledFromUserAction);
                } else {
                    const errorMsg = response.data?.message || (_this._labels.fetchError || 'Failed to fetch collections');
                    $statusContainer.html(
                        '<div class="alert alert-danger"><strong>' +
                        (_this._labels.errorText || 'Error:') +
                        '</strong> ' + errorMsg + '</div>'
                    );
                    _this._showError(errorMsg);
                }
            },
            error: function(xhr, status, error) {
                _this._setFetching(false);
                $btn.text(_this._labels.fetchCollectionsBtn || 'Fetch Collections');

                const errorMsg = (_this._labels.fetchingError || 'Error fetching collections') + ': ' + error;
                $statusContainer.html(
                    '<div class="alert alert-danger"><strong>' +
                    (_this._labels.errorText || 'Error:') +
                    '</strong> ' + errorMsg + '</div>'
                );
                _this._showError(errorMsg);
            }
        });
    }

    _displayCollections(collections) {
        const $tableBody = jQuery('#collections-table-body');
        $tableBody.empty();

        const _this = this;
        collections.forEach(function(collection) {
            const isChecked = _this._selectedCollections[collection.id] ? 'checked' : '';
            const checkboxHtml = '<div class="form-check visibility-toggle">' +
                '<input class="form-check-input collection-import-checkbox" type="checkbox" ' +
                'data-collection-id="' + collection.id + '" ' +
                'data-collection-title="' + collection.title + '" ' +
                isChecked + '>' +
                '<label class="form-check-label">' +
                (_this._labels.importCollection || 'Import') +
                '</label>' +
                '</div>';

            const imageHtml = collection.image_url
                ? '<img src="' + collection.image_url + '" alt="' + (collection.image_alt || collection.title) + '" style="width: 50px; height: 50px; object-fit: cover;">'
                : '<span class="text-muted">' + (_this._labels.noImage || 'No image') + '</span>';

            const descriptionText = collection.description
                ? (collection.description.length > 100 ? collection.description.substring(0, 100) + '...' : collection.description)
                : '<span class="text-muted">' + (_this._labels.noDescription || 'No description') + '</span>';

            const dragHandleHtml = '<span class="dashicons dashicons-move" style="cursor: move; font-size: 20px;"></span>';

            const row = '<tr data-collection-id="' + collection.id + '">' +
                '<td class="drag-handle">' + dragHandleHtml + '</td>' +
                '<td>' + checkboxHtml + '</td>' +
                '<td>' + imageHtml + '</td>' +
                '<td><strong>' + collection.title + '</strong></td>' +
                '<td><code>' + collection.handle + '</code></td>' +
                '<td>' + collection.products_count + '</td>' +
                '<td>' + descriptionText + '</td>' +
                '</tr>';

            $tableBody.append(row);
        });

        // Attach checkbox change handlers
        this._attachCheckboxHandlers();

        // Initialize sortable
        this._initializeSortable();
    }

    _attachCheckboxHandlers() {
        const _this = this;
        jQuery('.collection-import-checkbox').off('change').on('change', function() {
            const $checkbox = jQuery(this);
            const collectionId = $checkbox.data('collection-id');
            const collectionTitle = $checkbox.data('collection-title');
            const isChecked = $checkbox.is(':checked');
            _this._saveCollectionSelection(collectionId, collectionTitle, isChecked);
        });
    }

    _saveCollectionSelection(collectionId, collectionTitle, isChecked) {
        const _this = this;

        // Update local state
        if (isChecked) {
            this._selectedCollections[collectionId] = {
                title: collectionTitle,
                selected: true
            };
        } else {
            delete this._selectedCollections[collectionId];
        }

        if (jQuery('.product-sync-warning')[0]) {
            if (Object.keys(this._selectedCollections).length > 0) {
                jQuery('.product-sync-warning').addClass('d-none');
            } else {
                jQuery('.product-sync-warning').removeClass('d-none');
            }
        }

        // Save to server
        const ajaxPayload = {
            action: 'shopypress_save_collection_selection',
            nonce: window.SHOPYPRESS_ADMIN_SETTINGS?.nonce || '',
            collection_id: collectionId,
            collection_title: collectionTitle,
            is_checked: isChecked
        };

        jQuery.ajax({
            url: window.SHOPYPRESS_ADMIN_SETTINGS?.ajax_url || ajaxurl,
            type: 'POST',
            data: ajaxPayload,
            success: function(response) {
                if (response.success) {
                    const message = isChecked
                        ? collectionTitle + ' ' + (_this._labels.collectionSelected || 'selected for import')
                        : collectionTitle + ' ' + (_this._labels.collectionDeselected || 'deselected');

                    _this._showSuccess(message, true);
                } else {
                    _this._showError(response.data?.message || (_this._labels.saveFailed || 'Failed to save selection'));
                }
            },
            error: function() {
                _this._showError(_this._labels.saveError || 'Error saving selection');
            }
        });
    }

    _setFetching(val) {
        this._isFetching = val;
        const $btn = jQuery('#btn-fetch-collections');

        if (val) {
            $btn.addClass('disabled').prop('disabled', true);
        } else {
            $btn.removeClass('disabled').prop('disabled', false);
        }
    }

    _showSuccess(message, calledFromUserAction) {
        if (!calledFromUserAction) {
            return;
        }
        if (typeof toastr !== 'undefined') {
            toastr.success(message);
        }
    }

    _showError(message) {
        if (typeof toastr !== 'undefined') {
            toastr.error(message);
        }
    }

    _initializeSortable() {
        const _this = this;
        const $tableBody = jQuery('#collections-table-body');

        if ($tableBody.hasClass('ui-sortable')) {
            $tableBody.sortable('destroy');
        }

        $tableBody.sortable({
            handle: '.drag-handle',
            items: 'tr',
            axis: 'y',
            cursor: 'move',
            opacity: 0.6,
            placeholder: 'ui-state-highlight',
            helper: function(e, tr) {
                const $originals = tr.children();
                const $helper = tr.clone();
                $helper.children().each(function(index) {
                    jQuery(this).width($originals.eq(index).width());
                });
                return $helper;
            },
            update: function(event, ui) {
                _this._saveCollectionOrder();
            }
        });
    }

    _saveCollectionOrder() {
        const _this = this;
        const collectionOrder = [];

        jQuery('#collections-table-body tr').each(function(index) {
            const collectionId = jQuery(this).data('collection-id');
            if (collectionId) {
                collectionOrder.push({
                    id: collectionId,
                    order: index
                });
            }
        });

        const ajaxPayload = {
            action: 'shopypress_save_collection_order',
            nonce: window.SHOPYPRESS_ADMIN_SETTINGS?.nonce || '',
            collection_order: collectionOrder
        };

        jQuery.ajax({
            url: window.SHOPYPRESS_ADMIN_SETTINGS?.ajax_url || ajaxurl,
            type: 'POST',
            data: ajaxPayload,
            success: function(response) {
                if (response.success) {
                    _this._showSuccess(_this._labels.orderSaved || 'Collection order saved successfully', true);
                } else {
                    _this._showError(response.data?.message || (_this._labels.orderSaveFailed || 'Failed to save collection order'));
                }
            },
            error: function() {
                _this._showError(_this._labels.orderSaveError || 'Error saving collection order');
            }
        });
    }
}

export default FetchCollections;
