import React, { useState, useEffect } from 'react';
import api from '../utils/api';

const VariationManager = ({ productId, attributes, showError, showSuccess }) => {
    const [variations, setVariations] = useState([]);
    const [originalVariations, setOriginalVariations] = useState({}); // Store original data for cancel
    const [modifiedVariations, setModifiedVariations] = useState({}); // Track which variations are modified
    const [savingVariations, setSavingVariations] = useState({}); // Track which variations are being saved
    const [loading, setLoading] = useState(false);
    const [generating, setGenerating] = useState(false);
    const [expandedVariations, setExpandedVariations] = useState({});
    const [selectedAttributeTerms, setSelectedAttributeTerms] = useState({});
    const [showGenerateConfirm, setShowGenerateConfirm] = useState(false);
    const [parentProduct, setParentProduct] = useState(null);

    useEffect(() => {
        if (productId) {
            // Add a small delay to ensure product is saved
            const timer = setTimeout(() => {
                loadVariations();
                loadParentProduct();
            }, 500);
            return () => clearTimeout(timer);
        }
    }, [productId]);

    const loadParentProduct = async () => {
        try {
            const response = await api.getProduct(productId);
            if (response.success) {
                setParentProduct(response.product);
            }
        } catch (error) {
            console.error('Error loading parent product:', error);
        }
    };

    const inheritFromParent = async (variationId, field) => {
        if (!parentProduct) return;
        
        let value;
        switch (field) {
            case 'shipping':
                value = {
                    weight: parentProduct.weight || '',
                    dimensions: parentProduct.dimensions || { length: '', width: '', height: '' },
                    shipping_class: parentProduct.shipping_class || ''
                };
                // Update multiple fields
                await updateVariation(variationId, 'weight', value.weight);
                await updateVariation(variationId, 'dimensions', value.dimensions);
                await updateVariation(variationId, 'shipping_class', value.shipping_class);
                break;
            case 'weight':
                value = parentProduct.weight || '';
                await updateVariation(variationId, 'weight', value);
                break;
            case 'dimensions':
                value = parentProduct.dimensions || { length: '', width: '', height: '' };
                await updateVariation(variationId, 'dimensions', value);
                break;
            case 'shipping_class':
                value = parentProduct.shipping_class || '';
                await updateVariation(variationId, 'shipping_class', value);
                break;
            default:
                break;
        }
    };

    // Initialize selected terms when attributes change
    useEffect(() => {
        const variationAttributes = attributes.filter(attr => attr.variation);
        const initialTerms = {};
        variationAttributes.forEach(attr => {
            if (!selectedAttributeTerms[attr.id]) {
                initialTerms[attr.id] = attr.options || [];
            }
        });
        if (Object.keys(initialTerms).length > 0) {
            setSelectedAttributeTerms(prev => ({ ...prev, ...initialTerms }));
        }
    }, [attributes]);

    const loadVariations = async () => {
        try {
            setLoading(true);
            console.log('Loading variations for product ID:', productId);
            const response = await api.getProductVariations(productId);
            console.log('Variations response:', response);
            if (response.success) {
                const loadedVariations = response.variations || [];
                setVariations(loadedVariations);
                
                // Store original data for each variation
                const originals = {};
                loadedVariations.forEach(variation => {
                    originals[variation.id] = { ...variation };
                });
                setOriginalVariations(originals);
                setModifiedVariations({});
            } else {
                console.error('API returned error:', response.message);
                if (showError) showError(response.message || 'Failed to load variations');
            }
        } catch (error) {
            console.error('Error loading variations:', error);
            if (showError) showError('Failed to load variations: ' + error.message);
        } finally {
            setLoading(false);
        }
    };

    const generateVariations = async () => {
        try {
            setGenerating(true);
            
            // Get variation attributes with selected terms
            const variationAttributes = attributes.filter(attr => attr.variation);
            const attributesWithTerms = variationAttributes.map(attr => ({
                id: attr.id,
                name: attr.name,
                slug: attr.slug,
                terms: (selectedAttributeTerms[attr.id] || []).map(term => ({ name: term }))
            })).filter(attr => attr.terms.length > 0);
            
            if (attributesWithTerms.length === 0) {
                if (showError) showError('No variation attributes with terms selected.');
                return;
            }

            // Calculate total combinations
            const totalCombinations = attributesWithTerms.reduce((total, attr) => total * attr.terms.length, 1);
            
            if (totalCombinations > 50) {
                if (showError) showError(`Too many combinations (${totalCombinations}). Maximum 50 variations allowed.`);
                return;
            }

            const response = await api.generateProductVariations(productId, attributesWithTerms);
            
            if (response.success) {
                if (showSuccess) showSuccess(`Generated ${response.created_count || totalCombinations} variations successfully`);
                await loadVariations();
                setShowGenerateConfirm(false);
            } else {
                if (showError) showError(response.message || 'Failed to generate variations');
            }
        } catch (error) {
            console.error('Error generating variations:', error);
            if (showError) showError('Failed to generate variations: ' + error.message);
        } finally {
            setGenerating(false);
        }
    };

    const handleAttributeTermChange = (attributeId, selectedTerms) => {
        setSelectedAttributeTerms(prev => ({
            ...prev,
            [attributeId]: selectedTerms
        }));
    };

    const getTotalCombinations = () => {
        const variationAttributes = attributes.filter(attr => attr.variation);
        return variationAttributes.reduce((total, attr) => {
            const terms = selectedAttributeTerms[attr.id] || [];
            return total * Math.max(terms.length, 1);
        }, 1);
    };

    const toggleVariation = (index) => {
        setExpandedVariations(prev => ({
            ...prev,
            [index]: !prev[index]
        }));
    };

    const updateVariation = (variationId, field, value) => {
        // Update local state only
        setVariations(prev => prev.map(variation => 
            variation.id === variationId 
                ? { ...variation, [field]: value }
                : variation
        ));
        
        // Mark this variation as modified
        setModifiedVariations(prev => ({ ...prev, [variationId]: true }));
    };

    const saveVariation = async (variationId) => {
        try {
            setSavingVariations(prev => ({ ...prev, [variationId]: true }));
            
            const variation = variations.find(v => v.id === variationId);
            if (!variation) return;
            
            // Prepare clean data for API - remove fields that shouldn't be sent or need formatting
            const cleanData = { ...variation };
            
            // Remove read-only fields
            delete cleanData.id;
            delete cleanData.permalink;
            delete cleanData.date_created;
            delete cleanData.date_modified;
            
            // Convert manage_stock to boolean if it's a string
            if (typeof cleanData.manage_stock === 'string') {
                cleanData.manage_stock = cleanData.manage_stock === 'true' || cleanData.manage_stock === '1';
            }
            
            // Ensure stock_quantity is a number
            if (cleanData.stock_quantity) {
                cleanData.stock_quantity = parseInt(cleanData.stock_quantity) || 0;
            }
            
            // Ensure prices are strings (API expects strings)
            if (cleanData.regular_price !== undefined && cleanData.regular_price !== null) {
                cleanData.regular_price = String(cleanData.regular_price);
            }
            if (cleanData.sale_price !== undefined && cleanData.sale_price !== null) {
                cleanData.sale_price = String(cleanData.sale_price);
            }
            
            const response = await api.updateProductVariation(productId, variationId, cleanData);
            
            if (response.success) {
                // Update original data
                setOriginalVariations(prev => ({ ...prev, [variationId]: { ...variation } }));
                // Remove from modified list
                setModifiedVariations(prev => {
                    const newModified = { ...prev };
                    delete newModified[variationId];
                    return newModified;
                });
                if (showSuccess) showSuccess('Variation saved successfully');
            } else {
                if (showError) showError(response.message || 'Failed to save variation');
            }
        } catch (error) {
            console.error('Error saving variation:', error);
            if (showError) showError('Failed to save variation');
        } finally {
            setSavingVariations(prev => {
                const newSaving = { ...prev };
                delete newSaving[variationId];
                return newSaving;
            });
        }
    };

    const cancelVariationChanges = (variationId) => {
        // Restore original data
        const original = originalVariations[variationId];
        if (original) {
            setVariations(prev => prev.map(variation => 
                variation.id === variationId ? { ...original } : variation
            ));
            // Remove from modified list
            setModifiedVariations(prev => {
                const newModified = { ...prev };
                delete newModified[variationId];
                return newModified;
            });
        }
    };

    const deleteVariation = async (variationId) => {
        if (!confirm('Are you sure you want to delete this variation?')) {
            return;
        }

        try {
            const response = await api.deleteProductVariation(productId, variationId);
            
            if (response.success) {
                setVariations(prev => prev.filter(v => v.id !== variationId));
                if (showSuccess) showSuccess('Variation deleted');
            } else {
                if (showError) showError(response.message || 'Failed to delete variation');
            }
        } catch (error) {
            console.error('Error deleting variation:', error);
            if (showError) showError('Failed to delete variation');
        }
    };

    const addManualVariation = async () => {
        try {
            // Create a basic variation with default attributes
            const variationAttributes = attributes.filter(attr => attr.variation);
            const defaultAttributes = {};
            
            variationAttributes.forEach(attr => {
                const attrKey = attr.id > 0 ? `attribute_pa_${attr.slug}` : `attribute_${attr.slug}`;
                defaultAttributes[attrKey] = attr.options[0] || '';
            });

            const variationData = {
                attributes: defaultAttributes,
                regular_price: '',
                stock_status: 'instock',
                manage_stock: false,
                enabled: true
            };

            const response = await api.createProductVariation(productId, variationData);
            
            if (response.success) {
                if (showSuccess) showSuccess('Variation created successfully');
                await loadVariations();
            } else {
                if (showError) showError(response.message || 'Failed to create variation');
            }
        } catch (error) {
            console.error('Error creating variation:', error);
            if (showError) showError('Failed to create variation: ' + error.message);
        }
    };

    const getVariationName = (variation) => {
        const attributeNames = [];
        for (const [key, value] of Object.entries(variation.attributes || {})) {
            if (value) {
                const cleanKey = key.replace('attribute_', '').replace('pa_', '');
                attributeNames.push(`${cleanKey}: ${value}`);
            }
        }
        return attributeNames.join(', ') || `Variation #${variation.id}`;
    };

    if (!productId) {
        return (
            <div className="variations-empty">
                <div className="empty-state">
                    <h4>Save Product First</h4>
                    <p>You need to save this product before you can manage variations.</p>
                    <p>Click the "Save Product" button at the bottom of the page, then return to this tab.</p>
                </div>
            </div>
        );
    }

    if (loading) {
        return <div style={{ padding: '20px', textAlign: 'center' }}>Loading variations...</div>;
    }

    const variationAttributes = attributes.filter(attr => attr.variation);

    return (
        <div className="variation-manager">
            {/* Attribute Selection Section */}
            {variationAttributes.length > 0 && (
                <div className="attribute-selection-section">
                    <h4>Select Attribute Terms</h4>
                    <p className="field-description">
                        Choose which terms to use for each attribute. Only selected terms will be used to generate variations.
                    </p>
                    
                    <div className="attribute-selectors">
                        {variationAttributes.map(attr => (
                            <div key={attr.id} className="attribute-selector">
                                <label>{attr.name}</label>
                                <select
                                    multiple
                                    value={selectedAttributeTerms[attr.id] || []}
                                    onChange={(e) => {
                                        const selected = Array.from(e.target.selectedOptions, option => option.value);
                                        handleAttributeTermChange(attr.id, selected);
                                    }}
                                    className="terms-multiselect"
                                >
                                    {(attr.options || []).map(term => (
                                        <option key={term} value={term}>
                                            {term}
                                        </option>
                                    ))}
                                </select>
                                <p className="help-text">
                                    Hold Ctrl (Cmd on Mac) to select multiple terms. 
                                    Selected: {(selectedAttributeTerms[attr.id] || []).length} of {(attr.options || []).length}
                                </p>
                            </div>
                        ))}
                    </div>

                    <div className="generation-info">
                        <p>
                            <strong>Total combinations:</strong> {getTotalCombinations()} variations will be created
                        </p>
                        <p className="field-description">
                            Add variations for each attribute combination or add a single variation for all attributes.
                        </p>
                    </div>

                    <div className="variations-toolbar">
                        <button
                            type="button"
                            className="btn btn-primary"
                            onClick={() => setShowGenerateConfirm(true)}
                            disabled={getTotalCombinations() === 0}
                        >
                            Generate Variations
                        </button>
                        <button
                            type="button"
                            className="btn btn-secondary"
                            onClick={addManualVariation}
                        >
                            Add Manual
                        </button>
                        {variations.length > 0 && (
                            <span className="variations-count">
                                {variations.length} variation{variations.length !== 1 ? 's' : ''}
                            </span>
                        )}
                    </div>
                </div>
            )}

            {variations.length > 0 ? (
                <div className="variations-list">
                    {variations.map((variation, index) => (
                        <div key={variation.id} className="variation-item">
                            <div className="variation-header">
                                <button
                                    type="button"
                                    className="expand-btn"
                                    onClick={() => toggleVariation(index)}
                                >
                                    {expandedVariations[index] ? '▼' : '▶'}
                                </button>
                                
                                <div className="variation-info">
                                    <strong>{getVariationName(variation)}</strong>
                                    <span className="variation-details">
                                        SKU: {variation.sku || 'N/A'} | 
                                        Price: ${variation.regular_price || '0'} | 
                                        Stock: {variation.stock_quantity || 0}
                                    </span>
                                </div>

                                <div className="variation-actions">
                                    {modifiedVariations[variation.id] && (
                                        <>
                                            <button
                                                type="button"
                                                className="btn btn-primary btn-sm"
                                                onClick={() => saveVariation(variation.id)}
                                                disabled={savingVariations[variation.id]}
                                            >
                                                {savingVariations[variation.id] ? 'Saving...' : 'Save Changes'}
                                            </button>
                                            <button
                                                type="button"
                                                className="btn btn-secondary btn-sm"
                                                onClick={() => cancelVariationChanges(variation.id)}
                                                disabled={savingVariations[variation.id]}
                                            >
                                                Cancel
                                            </button>
                                        </>
                                    )}
                                    <label className="toggle-switch">
                                        <input
                                            type="checkbox"
                                            checked={variation.enabled}
                                            onChange={(e) => updateVariation(variation.id, 'enabled', e.target.checked)}
                                        />
                                        <span className="toggle-slider"></span>
                                    </label>
                                    <button
                                        type="button"
                                        className="btn-remove"
                                        onClick={() => deleteVariation(variation.id)}
                                        title="Delete variation"
                                    >
                                        ✕
                                    </button>
                                </div>
                            </div>

                            {expandedVariations[index] && (
                                <div className="variation-content">
                                    <div className="variation-form">
                                        {/* Image and Basic Info */}
                                        <div className="form-section">
                                            <h5>Basic Information</h5>
                                            <div className="form-row">
                                                <div className="form-group">
                                                    <label>Variation Image</label>
                                                    <div className="image-upload-placeholder">
                                                        {variation.image ? (
                                                            <img src={variation.image.src} alt={variation.image.alt} style={{ width: '60px', height: '60px', objectFit: 'cover' }} />
                                                        ) : (
                                                            <div className="no-image">No image</div>
                                                        )}
                                                        <button type="button" className="btn btn-sm btn-secondary">
                                                            Select Image
                                                        </button>
                                                    </div>
                                                </div>
                                                <div className="form-group">
                                                    <label>SKU</label>
                                                    <input
                                                        type="text"
                                                        value={variation.sku || ''}
                                                        onChange={(e) => updateVariation(variation.id, 'sku', e.target.value)}
                                                        placeholder="Enter SKU"
                                                    />
                                                </div>
                                            </div>
                                        </div>

                                        {/* Global Identifier */}
                                        <div className="form-section">
                                            <h5>Global Identifier</h5>
                                            <div className="form-row">
                                                <div className="form-group">
                                                    <label>GTIN, UPC, EAN, or ISBN</label>
                                                    <input
                                                        type="text"
                                                        value={variation.gtin || variation.upc || variation.ean || variation.isbn || ''}
                                                        onChange={(e) => {
                                                            // Store in gtin field
                                                            updateVariation(variation.id, 'gtin', e.target.value);
                                                            // Clear other fields
                                                            updateVariation(variation.id, 'upc', '');
                                                            updateVariation(variation.id, 'ean', '');
                                                            updateVariation(variation.id, 'isbn', '');
                                                        }}
                                                        placeholder="Enter GTIN, UPC, EAN, or ISBN"
                                                    />
                                                    <p className="help-text">Enter any global product identifier</p>
                                                </div>
                                            </div>
                                        </div>

                                        {/* Pricing */}
                                        <div className="form-section">
                                            <h5>Pricing</h5>
                                            <div className="form-row">
                                                <div className="form-group">
                                                    <label>Regular Price ($)</label>
                                                    <input
                                                        type="number"
                                                        step="0.01"
                                                        value={variation.regular_price || ''}
                                                        onChange={(e) => updateVariation(variation.id, 'regular_price', e.target.value)}
                                                        placeholder="0.00"
                                                    />
                                                </div>
                                                <div className="form-group">
                                                    <label>Sale Price ($)</label>
                                                    <input
                                                        type="number"
                                                        step="0.01"
                                                        value={variation.sale_price || ''}
                                                        onChange={(e) => updateVariation(variation.id, 'sale_price', e.target.value)}
                                                        placeholder="0.00"
                                                    />
                                                </div>
                                            </div>
                                            
                                            {/* Sale Price Dates */}
                                            {variation.sale_price && (
                                                <div className="form-row">
                                                    <div className="form-group">
                                                        <label>Sale Price Start Date</label>
                                                        <input
                                                            type="datetime-local"
                                                            value={variation.date_on_sale_from || ''}
                                                            onChange={(e) => updateVariation(variation.id, 'date_on_sale_from', e.target.value)}
                                                        />
                                                        <p className="help-text">Leave empty for no start date</p>
                                                    </div>
                                                    <div className="form-group">
                                                        <label>Sale Price End Date</label>
                                                        <input
                                                            type="datetime-local"
                                                            value={variation.date_on_sale_to || ''}
                                                            onChange={(e) => updateVariation(variation.id, 'date_on_sale_to', e.target.value)}
                                                        />
                                                        <p className="help-text">Leave empty for no end date</p>
                                                    </div>
                                                </div>
                                            )}
                                        </div>

                                        {/* Stock Management */}
                                        <div className="form-section">
                                            <h5>Stock Management</h5>
                                            <div className="form-row">
                                                <div className="form-group">
                                                    <label className="checkbox-label">
                                                        <input
                                                            type="checkbox"
                                                            checked={variation.manage_stock || false}
                                                            onChange={(e) => updateVariation(variation.id, 'manage_stock', e.target.checked)}
                                                        />
                                                        <span>Manage stock</span>
                                                    </label>
                                                </div>
                                                <div className="form-group">
                                                    <label>Stock Quantity</label>
                                                    <input
                                                        type="number"
                                                        value={variation.stock_quantity || ''}
                                                        onChange={(e) => updateVariation(variation.id, 'stock_quantity', parseInt(e.target.value) || 0)}
                                                        placeholder="0"
                                                        disabled={!variation.manage_stock}
                                                    />
                                                </div>
                                                <div className="form-group">
                                                    <label>Stock Status</label>
                                                    <select
                                                        value={variation.stock_status || 'instock'}
                                                        onChange={(e) => updateVariation(variation.id, 'stock_status', e.target.value)}
                                                    >
                                                        <option value="instock">In stock</option>
                                                        <option value="outofstock">Out of stock</option>
                                                        <option value="onbackorder">On backorder</option>
                                                    </select>
                                                </div>
                                            </div>
                                        </div>

                                        {/* Product Type */}
                                        <div className="form-section">
                                            <h5>Product Type</h5>
                                            <div className="form-row">
                                                <div className="form-group">
                                                    <label className="checkbox-label">
                                                        <input
                                                            type="checkbox"
                                                            checked={variation.virtual || false}
                                                            onChange={(e) => updateVariation(variation.id, 'virtual', e.target.checked)}
                                                        />
                                                        <span>Virtual</span>
                                                    </label>
                                                    <p className="help-text">Virtual products don't require shipping</p>
                                                </div>
                                                <div className="form-group">
                                                    <label className="checkbox-label">
                                                        <input
                                                            type="checkbox"
                                                            checked={variation.downloadable || false}
                                                            onChange={(e) => updateVariation(variation.id, 'downloadable', e.target.checked)}
                                                        />
                                                        <span>Downloadable</span>
                                                    </label>
                                                    <p className="help-text">Downloadable products give access to files</p>
                                                </div>
                                            </div>
                                        </div>

                                        {/* Physical Properties - Only show if not virtual */}
                                        {!variation.virtual && (
                                            <div className="form-section">
                                                <div className="section-header">
                                                    <h5>Physical Properties</h5>
                                                    {parentProduct && (
                                                        <button
                                                            type="button"
                                                            className="btn btn-sm btn-secondary inherit-btn"
                                                            onClick={() => inheritFromParent(variation.id, 'shipping')}
                                                            title="Copy shipping details from parent product"
                                                        >
                                                            Same as Parent
                                                        </button>
                                                    )}
                                                </div>
                                                <div className="form-row">
                                                    <div className="form-group">
                                                        <label>Weight (kg)</label>
                                                        <input
                                                            type="number"
                                                            step="0.01"
                                                            value={variation.weight || ''}
                                                            onChange={(e) => updateVariation(variation.id, 'weight', e.target.value)}
                                                            placeholder="0.00"
                                                        />
                                                        {parentProduct && (
                                                            <p className="help-text">Parent: {parentProduct.weight || 'Not set'} kg</p>
                                                        )}
                                                    </div>
                                                    <div className="form-group">
                                                        <label>Length (cm)</label>
                                                        <input
                                                            type="number"
                                                            step="0.01"
                                                            value={variation.dimensions?.length || ''}
                                                            onChange={(e) => updateVariation(variation.id, 'dimensions', {
                                                                ...variation.dimensions,
                                                                length: e.target.value
                                                            })}
                                                            placeholder="0.00"
                                                        />
                                                        {parentProduct && (
                                                            <p className="help-text">Parent: {parentProduct.dimensions?.length || 'Not set'} cm</p>
                                                        )}
                                                    </div>
                                                    <div className="form-group">
                                                        <label>Width (cm)</label>
                                                        <input
                                                            type="number"
                                                            step="0.01"
                                                            value={variation.dimensions?.width || ''}
                                                            onChange={(e) => updateVariation(variation.id, 'dimensions', {
                                                                ...variation.dimensions,
                                                                width: e.target.value
                                                            })}
                                                            placeholder="0.00"
                                                        />
                                                        {parentProduct && (
                                                            <p className="help-text">Parent: {parentProduct.dimensions?.width || 'Not set'} cm</p>
                                                        )}
                                                    </div>
                                                    <div className="form-group">
                                                        <label>Height (cm)</label>
                                                        <input
                                                            type="number"
                                                            step="0.01"
                                                            value={variation.dimensions?.height || ''}
                                                            onChange={(e) => updateVariation(variation.id, 'dimensions', {
                                                                ...variation.dimensions,
                                                                height: e.target.value
                                                            })}
                                                            placeholder="0.00"
                                                        />
                                                        {parentProduct && (
                                                            <p className="help-text">Parent: {parentProduct.dimensions?.height || 'Not set'} cm</p>
                                                        )}
                                                    </div>
                                                </div>
                                                <div className="form-row">
                                                    <div className="form-group">
                                                        <label>Shipping Class</label>
                                                        <select
                                                            value={variation.shipping_class || ''}
                                                            onChange={(e) => updateVariation(variation.id, 'shipping_class', e.target.value)}
                                                        >
                                                            <option value="">No shipping class</option>
                                                            <option value="standard">Standard</option>
                                                            <option value="express">Express</option>
                                                            <option value="free">Free shipping</option>
                                                        </select>
                                                        {parentProduct && (
                                                            <p className="help-text">Parent: {parentProduct.shipping_class || 'No shipping class'}</p>
                                                        )}
                                                    </div>
                                                </div>
                                            </div>
                                        )}

                                        {/* Downloadable Files - Only show if downloadable */}
                                        {variation.downloadable && (
                                            <div className="form-section">
                                                <h5>Downloadable Files</h5>
                                                <div className="form-row">
                                                    <div className="form-group">
                                                        <label>Download Limit</label>
                                                        <input
                                                            type="number"
                                                            value={variation.download_limit || -1}
                                                            onChange={(e) => updateVariation(variation.id, 'download_limit', parseInt(e.target.value))}
                                                            placeholder="-1 for unlimited"
                                                        />
                                                        <p className="help-text">Leave blank or -1 for unlimited downloads</p>
                                                    </div>
                                                    <div className="form-group">
                                                        <label>Download Expiry (days)</label>
                                                        <input
                                                            type="number"
                                                            value={variation.download_expiry || -1}
                                                            onChange={(e) => updateVariation(variation.id, 'download_expiry', parseInt(e.target.value))}
                                                            placeholder="-1 for never expires"
                                                        />
                                                        <p className="help-text">Leave blank or -1 for never expires</p>
                                                    </div>
                                                </div>
                                                <div className="downloadable-files-list">
                                                    {(variation.downloadable_files || []).map((file, fileIndex) => (
                                                        <div key={fileIndex} className="downloadable-file-item">
                                                            <div className="form-row">
                                                                <div className="form-group">
                                                                    <label>File Name</label>
                                                                    <input
                                                                        type="text"
                                                                        value={file.name || ''}
                                                                        onChange={(e) => {
                                                                            const newFiles = [...(variation.downloadable_files || [])];
                                                                            newFiles[fileIndex] = { ...file, name: e.target.value };
                                                                            updateVariation(variation.id, 'downloadable_files', newFiles);
                                                                        }}
                                                                        placeholder="File name"
                                                                    />
                                                                </div>
                                                                <div className="form-group" style={{ flex: 2 }}>
                                                                    <label>File URL</label>
                                                                    <div style={{ display: 'flex', gap: '8px' }}>
                                                                        <input
                                                                            type="url"
                                                                            value={file.file || ''}
                                                                            onChange={(e) => {
                                                                                const newFiles = [...(variation.downloadable_files || [])];
                                                                                newFiles[fileIndex] = { ...file, file: e.target.value };
                                                                                updateVariation(variation.id, 'downloadable_files', newFiles);
                                                                            }}
                                                                            placeholder="https://..."
                                                                            style={{ flex: 1 }}
                                                                        />
                                                                        <button
                                                                            type="button"
                                                                            className="btn btn-secondary btn-sm"
                                                                            onClick={() => {
                                                                                // Open WordPress Media Library
                                                                                if (window.wp && window.wp.media) {
                                                                                    const frame = window.wp.media({
                                                                                        title: 'Select File',
                                                                                        button: { text: 'Use this file' },
                                                                                        multiple: false
                                                                                    });

                                                                                    frame.on('select', function() {
                                                                                        const attachment = frame.state().get('selection').first().toJSON();
                                                                                        const newFiles = [...(variation.downloadable_files || [])];
                                                                                        newFiles[fileIndex] = {
                                                                                            ...file,
                                                                                            name: file.name || attachment.title || attachment.filename,
                                                                                            file: attachment.url
                                                                                        };
                                                                                        updateVariation(variation.id, 'downloadable_files', newFiles);
                                                                                    });

                                                                                    frame.open();
                                                                                }
                                                                            }}
                                                                        >
                                                                            Choose File
                                                                        </button>
                                                                    </div>
                                                                </div>
                                                                <button
                                                                    type="button"
                                                                    className="btn-remove-file"
                                                                    onClick={() => {
                                                                        const newFiles = (variation.downloadable_files || []).filter((_, i) => i !== fileIndex);
                                                                        updateVariation(variation.id, 'downloadable_files', newFiles);
                                                                    }}
                                                                    title="Remove file"
                                                                >
                                                                    ✕
                                                                </button>
                                                            </div>
                                                        </div>
                                                    ))}
                                                </div>
                                                <button
                                                    type="button"
                                                    className="btn btn-secondary btn-sm"
                                                    onClick={() => {
                                                        const newFiles = [...(variation.downloadable_files || []), { name: '', file: '' }];
                                                        updateVariation(variation.id, 'downloadable_files', newFiles);
                                                    }}
                                                >
                                                    + Add File
                                                </button>
                                            </div>
                                        )}

                                        {/* Description */}
                                        <div className="form-section">
                                            <h5>Description</h5>
                                            <div className="form-group">
                                                <label>Variation Description</label>
                                                <textarea
                                                    value={variation.description || ''}
                                                    onChange={(e) => updateVariation(variation.id, 'description', e.target.value)}
                                                    rows="3"
                                                    placeholder="Optional description for this variation"
                                                />
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            )}
                        </div>
                    ))}
                </div>
            ) : (
                <div className="variations-empty">
                    <p>No variations created yet. Click "Generate Variations" to create them automatically from your attributes.</p>
                </div>
            )}

            {/* Generate Variations Confirmation Modal */}
            {showGenerateConfirm && (
                <div className="modal-overlay" onClick={() => setShowGenerateConfirm(false)}>
                    <div className="modal-content" onClick={(e) => e.stopPropagation()}>
                        <div className="modal-header">
                            <h3>Generate Variations</h3>
                            <button
                                type="button"
                                className="modal-close"
                                onClick={() => setShowGenerateConfirm(false)}
                            >
                                ✕
                            </button>
                        </div>

                        <div className="modal-body">
                            <p>
                                This will generate <strong>{getTotalCombinations()} variations</strong> based on your selected attribute terms.
                            </p>
                            
                            <div className="attribute-summary">
                                <h4>Selected Attributes:</h4>
                                {variationAttributes.map(attr => (
                                    <div key={attr.id} className="attribute-summary-item">
                                        <strong>{attr.name}:</strong> {(selectedAttributeTerms[attr.id] || []).join(', ')}
                                    </div>
                                ))}
                            </div>

                            <div className="warning-box">
                                <p><strong>Note:</strong> Generated variations will not have prices set. You'll need to expand each variation and add:</p>
                                <ul>
                                    <li>Images and SKU</li>
                                    <li>Global identifiers (GTIN, UPC, EAN, ISBN)</li>
                                    <li>Pricing (Regular & Sale prices)</li>
                                    <li>Stock management settings</li>
                                    <li>Physical properties (weight, dimensions)</li>
                                    <li>Shipping class and description</li>
                                </ul>
                            </div>
                        </div>

                        <div className="modal-footer">
                            <button
                                type="button"
                                className="btn btn-secondary"
                                onClick={() => setShowGenerateConfirm(false)}
                            >
                                Cancel
                            </button>
                            <button
                                type="button"
                                className="btn btn-primary"
                                onClick={generateVariations}
                                disabled={generating}
                            >
                                {generating ? 'Generating...' : `Generate ${getTotalCombinations()} Variations`}
                            </button>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
};

export default VariationManager;