import BaseComponent from './BaseComponent.js';

/**
 * VariantSelector component
 * Handles variant selection with smart filtering algorithm
 * Inspired by fusecommerce-pro implementation
 */
class VariantSelector extends BaseComponent {
    constructor(containerSelector, productData, gallery) {
        super(containerSelector);
        this.productData = productData;
        this.gallery = gallery;
        this.variants = productData.variants || [];
        this.options = productData.options || {};
        this.selectedOptions = {};
        this.matchedVariant = null;
    }

    /**
     * Initialize variant selector
     */
    init() {
        if (!this.variants || this.variants.length === 0) {
            console.warn('ShopyPress: No variants available');
            return;
        }

        this.bindEvents();
        this.applySmartFiltering();

        console.log('ShopyPress: Variant selector initialized with', this.variants.length, 'variants');
    }

    /**
     * Bind event handlers
     */
    bindEvents() {
        // Handle option button clicks
        this._element.on('click', '.variant-option-btn', (event) => {
            const btn = jQuery(event.currentTarget);

            // Don't allow selecting disabled buttons
            if (btn.prop('disabled')) {
                return;
            }

            const optionName = btn.data('option-name');
            const optionValue = btn.data('option-value');

            this.selectOption(optionName, optionValue);
        });
    }

    /**
     * Select an option value
     * @param {string} optionName - Option name (e.g., 'Color', 'Size')
     * @param {string} optionValue - Option value (e.g., 'Red', 'XL')
     */
    selectOption(optionName, optionValue) {
        // Toggle selection if clicking same button
        if (this.selectedOptions[optionName] === optionValue) {
            delete this.selectedOptions[optionName];
        } else {
            this.selectedOptions[optionName] = optionValue;
        }

        // Update UI
        this.updateButtonStates();

        // Apply smart filtering
        this.applySmartFiltering();

        // Try to match variant
        this.matchVariant();
    }

    /**
     * Update button visual states (selected/not selected)
     */
    updateButtonStates() {
        // Remove selected class from all buttons
        this._element.find('.variant-option-btn').removeClass('selected bg-black text-white');
        this._element.find('.variant-option-btn').addClass('bg-white text-black');

        // Add selected class to active buttons
        Object.keys(this.selectedOptions).forEach(optionName => {
            const value = this.selectedOptions[optionName];
            const btn = this._element.find(`.variant-option-btn[data-option-name="${optionName}"][data-option-value="${value}"]`);

            btn.removeClass('bg-white text-black');
            btn.addClass('selected bg-black text-white');
        });
    }

    /**
     * Smart filtering algorithm
     * Dynamically enable/disable buttons based on available variants
     */
    applySmartFiltering() {
        const optionNames = Object.keys(this.options);

        // For each unselected option, determine which values are available
        optionNames.forEach(optionName => {
            // Skip currently selected option
            if (this.selectedOptions[optionName]) {
                return;
            }

            // Get all possible values for this option
            const optionValues = this.options[optionName];

            optionValues.forEach(optionValue => {
                const btn = this._element.find(`.variant-option-btn[data-option-name="${optionName}"][data-option-value="${optionValue}"]`);

                // Check if this value has any in-stock variations with current selections
                const isAvailable = this.isValueAvailable(optionName, optionValue);

                if (isAvailable) {
                    btn.prop('disabled', false);
                    btn.removeClass('opacity-50 cursor-not-allowed');
                } else {
                    btn.prop('disabled', true);
                    btn.addClass('opacity-50 cursor-not-allowed');
                }
            });
        });
    }

    /**
     * Check if an option value is available (has in-stock variants)
     * @param {string} optionName - Option name to test
     * @param {string} optionValue - Option value to test
     * @returns {boolean} - True if available
     */
    isValueAvailable(optionName, optionValue) {
        // Create test selection with this value added
        const testSelection = { ...this.selectedOptions, [optionName]: optionValue };

        // Find variants that match this test selection
        const matchingVariants = this.variants.filter(variant => {
            // Check if variant matches all selected attributes
            return Object.keys(testSelection).every(opt => {
                const variantOption = variant.selected_options.find(vo => vo.name === opt);
                return variantOption && variantOption.value === testSelection[opt];
            });
        });

        // Check if any matching variant is available
        return matchingVariants.some(variant => variant.available);
    }

    /**
     * Try to match a variant based on selected options
     */
    matchVariant() {
        const optionNames = Object.keys(this.options);

        // Check if all options are selected
        const allSelected = optionNames.every(optionName => {
            return this.selectedOptions[optionName] !== undefined;
        });

        if (!allSelected) {
            // Not all options selected, clear match
            this.matchedVariant = null;
            this.onVariantChanged(null);
            return;
        }

        // Find exact match
        const match = this.variants.find(variant => {
            return optionNames.every(optionName => {
                const variantOption = variant.selected_options.find(vo => vo.name === optionName);
                return variantOption && variantOption.value === this.selectedOptions[optionName];
            });
        });

        if (match) {
            this.matchedVariant = match;
            this.onVariantMatched(match);
        } else {
            // No match found (shouldn't happen with smart filtering)
            this.matchedVariant = null;
            this.onVariantChanged(null);
        }
    }

    /**
     * Handle variant matched
     * @param {Object} variant - Matched variant object
     */
    onVariantMatched(variant) {
        console.log('ShopyPress: Variant matched', variant);

        // Update gallery if variant has image
        if (this.gallery && variant.image && variant.image.id) {
            this.gallery.switchToImage(variant.image.id);
        }

        // Update add to cart button state
        this.updateAddToCartButton(variant);

        // Update stock status
        this.updateStockStatus(variant);

        // Trigger event
        this.onVariantChanged(variant);
    }

    /**
     * Update add to cart button based on variant
     * @param {Object} variant - Variant object
     */
    updateAddToCartButton(variant) {
        const addToCartBtn = jQuery('#shopypress-add-to-cart');

        if (!variant || !variant.available) {
            addToCartBtn.prop('disabled', true);
            addToCartBtn.text(addToCartBtn.data('out-of-stock-text') || 'Out of Stock');
        } else {
            // Still disabled as functionality not implemented
            // But update text to show it would be available
            addToCartBtn.text('Add to Cart (Coming Soon)');
        }
    }

    /**
     * Update stock status message
     * @param {Object} variant - Variant object
     */
    updateStockStatus(variant) {
        const stockStatus = jQuery('#shopypress-stock-status');

        if (!variant) {
            stockStatus.text('');
            return;
        }

        if (!variant.available) {
            stockStatus.text('Out of stock');
            stockStatus.removeClass('text-green-600').addClass('text-red-600');
        } else if (variant.inventory_quantity && variant.inventory_quantity < 10) {
            stockStatus.text(`Only ${variant.inventory_quantity} left in stock`);
            stockStatus.removeClass('text-red-600').addClass('text-yellow-600');
        } else {
            stockStatus.text('In stock');
            stockStatus.removeClass('text-red-600 text-yellow-600').addClass('text-green-600');
        }
    }

    /**
     * Trigger variant changed event
     * @param {Object|null} variant - Variant object or null
     */
    onVariantChanged(variant) {
        // Trigger custom event for other components (like PriceDisplay)
        if (window.ShopyPressEventBus) {
            window.ShopyPressEventBus.trigger('variant:changed', {
                variant: variant,
                selectedOptions: this.selectedOptions,
            });
        }
    }

    /**
     * Get currently matched variant
     * @returns {Object|null} - Matched variant or null
     */
    getMatchedVariant() {
        return this.matchedVariant;
    }

    /**
     * Reset selection
     */
    reset() {
        this.selectedOptions = {};
        this.matchedVariant = null;
        this.updateButtonStates();
        this.applySmartFiltering();
        this.onVariantChanged(null);
    }

    /**
     * Destroy and clean up
     */
    destroy() {
        this._element.off('click');
    }
}

export default VariantSelector;
