import React, { useState } from 'react';

const VariationGenerateModal = ({ 
    open, 
    onClose, 
    attributes = [],
    onGenerate,
    showError,
    showSuccess 
}) => {
    const [loading, setLoading] = useState(false);

    const calculateCombinations = () => {
        if (!attributes || attributes.length === 0) return 0;
        
        return attributes.reduce((total, attr) => {
            const termCount = attr.terms ? attr.terms.length : 0;
            return total === 0 ? termCount : total * termCount;
        }, 0);
    };

    const handleGenerate = async () => {
        setLoading(true);
        
        try {
            const combinations = calculateCombinations();
            if (combinations > 50) {
                throw new Error('Too many combinations. Maximum 50 variations can be generated at once.');
            }

            await onGenerate();
            showSuccess(`${combinations} variations generated successfully`);
            onClose();
        } catch (error) {
            showError(error.message);
        } finally {
            setLoading(false);
        }
    };

    if (!open) return null;

    const combinations = calculateCombinations();

    return (
        <div className="modal-overlay" onClick={onClose}>
            <div className="modal-content" onClick={(e) => e.stopPropagation()}>
                <div className="modal-header">
                    <h3>Generate Variations</h3>
                    <button type="button" className="modal-close" onClick={onClose}>
                        ✕
                    </button>
                </div>

                <div className="modal-body">
                    <div className="generate-confirmation">
                        <div className="warning-icon">
                            ⚠️
                        </div>
                        <h4>Do you want to generate all variations?</h4>
                        <p>
                            This will create a new variation for each and every possible combination 
                            of variation attributes (max 50 per run).
                        </p>

                        <div className="combinations-info">
                            <h5>Current Attributes:</h5>
                            <ul>
                                {attributes.map(attr => (
                                    <li key={attr.id}>
                                        <strong>{attr.name}:</strong> {attr.terms?.length || 0} terms
                                        {attr.terms && attr.terms.length > 0 && (
                                            <span className="terms-preview">
                                                ({attr.terms.map(term => term.name).join(', ')})
                                            </span>
                                        )}
                                    </li>
                                ))}
                            </ul>
                            
                            <div className="combinations-count">
                                <strong>Total combinations: {combinations}</strong>
                                {combinations > 50 && (
                                    <div className="error-message">
                                        ❌ Too many combinations! Maximum 50 variations allowed per generation.
                                    </div>
                                )}
                                {combinations === 0 && (
                                    <div className="error-message">
                                        ❌ No attribute terms found. Please add terms to your attributes first.
                                    </div>
                                )}
                            </div>
                        </div>

                        {combinations > 0 && combinations <= 50 && (
                            <div className="generation-preview">
                                <h5>Example variations that will be created:</h5>
                                <div className="preview-list">
                                    {attributes.length >= 2 && attributes[0].terms && attributes[1].terms && (
                                        <>
                                            <div className="preview-item">
                                                {attributes[0].name}: {attributes[0].terms[0]?.name}, {attributes[1].name}: {attributes[1].terms[0]?.name}
                                            </div>
                                            {attributes[0].terms[1] && (
                                                <div className="preview-item">
                                                    {attributes[0].name}: {attributes[0].terms[1]?.name}, {attributes[1].name}: {attributes[1].terms[0]?.name}
                                                </div>
                                            )}
                                            <div className="preview-more">
                                                ... and {combinations - 2} more variations
                                            </div>
                                        </>
                                    )}
                                </div>
                            </div>
                        )}
                    </div>
                </div>

                <div className="modal-footer">
                    <button
                        type="button"
                        className="btn btn-secondary"
                        onClick={onClose}
                    >
                        Cancel
                    </button>
                    <button
                        type="button"
                        className={`btn btn-primary ${loading ? 'btn-loading' : ''}`}
                        onClick={handleGenerate}
                        disabled={loading || combinations === 0 || combinations > 50}
                    >
                        {loading ? 'Generating...' : `Generate ${combinations} Variations`}
                    </button>
                </div>
            </div>

            <style jsx>{`
                .generate-confirmation {
                    text-align: center;
                    padding: 20px;
                }

                .warning-icon {
                    font-size: 48px;
                    margin-bottom: 16px;
                }

                .combinations-info {
                    background: #f8f9fa;
                    border: 1px solid #dee2e6;
                    border-radius: 8px;
                    padding: 16px;
                    margin: 20px 0;
                    text-align: left;
                }

                .combinations-info ul {
                    margin: 10px 0;
                    padding-left: 20px;
                }

                .combinations-info li {
                    margin: 8px 0;
                }

                .terms-preview {
                    color: #6c757d;
                    font-size: 0.9em;
                    margin-left: 8px;
                }

                .combinations-count {
                    background: #e9ecef;
                    padding: 12px;
                    border-radius: 4px;
                    margin-top: 12px;
                    text-align: center;
                }

                .error-message {
                    color: #dc3545;
                    font-weight: bold;
                    margin-top: 8px;
                }

                .generation-preview {
                    background: #f8f9fa;
                    border: 1px solid #dee2e6;
                    border-radius: 8px;
                    padding: 16px;
                    margin: 20px 0;
                    text-align: left;
                }

                .preview-list {
                    margin-top: 10px;
                }

                .preview-item {
                    background: white;
                    border: 1px solid #dee2e6;
                    border-radius: 4px;
                    padding: 8px 12px;
                    margin: 4px 0;
                    font-family: monospace;
                    font-size: 0.9em;
                }

                .preview-more {
                    color: #6c757d;
                    font-style: italic;
                    margin-top: 8px;
                    text-align: center;
                }
            `}</style>
        </div>
    );
};

export default VariationGenerateModal;