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

const AttributeManager = ({ attributes = [], onChange, productType, showError, showSuccess }) => {
    const [globalAttributes, setGlobalAttributes] = useState([]);
    const [loading, setLoading] = useState(true);
    const [expandedAttributes, setExpandedAttributes] = useState({});
    const [attributeTerms, setAttributeTerms] = useState({});
    const [termSearchQuery, setTermSearchQuery] = useState({});
    const [showAddModal, setShowAddModal] = useState(false);
    const [newAttribute, setNewAttribute] = useState({
        name: '',
        values: '',
        visible: true,
        variation: productType === 'variable'
    });

    useEffect(() => {
        loadGlobalAttributes();
    }, []);

    const loadGlobalAttributes = async () => {
        try {
            setLoading(true);
            const response = await api.getProductAttributes();

            console.log('Attributes API response:', response);

            if (response.success && response.attributes) {
                console.log('Loaded attributes:', response.attributes);
                setGlobalAttributes(response.attributes);

                // Load terms for each attribute
                const termsPromises = response.attributes.map(async (attr) => {
                    try {
                        // Use attribute_id if id doesn't exist
                        const attrId = String(attr.id || attr.attribute_id);
                        console.log('Loading terms for attribute:', attrId);
                        const termsResponse = await api.getAttributeTerms(attrId);
                        console.log('Terms response for', attrId, ':', termsResponse);
                        return {
                            id: attrId,
                            terms: termsResponse.success ? (termsResponse.terms || []) : []
                        };
                    } catch (err) {
                        console.error(`Error loading terms for attribute:`, err);
                        return { id: String(attr.id || attr.attribute_id), terms: [] };
                    }
                });

                const termsResults = await Promise.all(termsPromises);
                const termsMap = {};
                termsResults.forEach(result => {
                    termsMap[result.id] = result.terms || [];
                });
                console.log('Attribute terms map:', termsMap);
                setAttributeTerms(termsMap);
            } else {
                console.log('No attributes found or API error:', response);
                setGlobalAttributes([]);
            }
        } catch (error) {
            console.error('Error loading attributes:', error);
            setGlobalAttributes([]);
            if (showError) showError('Failed to load attributes');
        } finally {
            setLoading(false);
        }
    };

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

    const addGlobalAttribute = async (globalAttr) => {
        const exists = attributes.find(a => a.id === globalAttr.id);
        if (exists) {
            if (showError) showError('This attribute is already added');
            return;
        }

        // Load terms for this attribute if not already loaded
        const attrId = String(globalAttr.id);
        if (!attributeTerms[attrId]) {
            try {
                console.log('Loading terms for newly added attribute:', attrId);
                const termsResponse = await api.getAttributeTerms(attrId);
                console.log('Terms response:', termsResponse);
                if (termsResponse.success) {
                    setAttributeTerms(prev => ({
                        ...prev,
                        [attrId]: termsResponse.terms || []
                    }));
                }
            } catch (err) {
                console.error('Error loading terms:', err);
            }
        }

        const newAttribute = {
            id: globalAttr.id,
            name: globalAttr.name,
            slug: globalAttr.slug,
            options: [],
            visible: true,
            variation: productType === 'variable'
        };

        const newAttributes = [...attributes, newAttribute];
        onChange(newAttributes);

        // Auto-expand the newly added attribute
        setExpandedAttributes(prev => ({
            ...prev,
            [newAttributes.length - 1]: true
        }));

        if (showSuccess) showSuccess(`Added attribute: ${globalAttr.name}`);
    };

    const addCustomAttribute = () => {
        setShowAddModal(true);
    };

    const handleAddCustomAttribute = (e) => {
        e.preventDefault();

        if (!newAttribute.name.trim()) {
            if (showError) showError('Attribute name is required');
            return;
        }

        const values = newAttribute.values
            .split('|')
            .map(v => v.trim())
            .filter(v => v);

        onChange([...attributes, {
            id: 0,
            name: newAttribute.name.trim(),
            slug: newAttribute.name.toLowerCase().replace(/[^a-z0-9]+/g, '-'),
            options: values,
            visible: newAttribute.visible,
            variation: newAttribute.variation
        }]);

        setNewAttribute({
            name: '',
            values: '',
            visible: true,
            variation: productType === 'variable'
        });
        setShowAddModal(false);

        if (showSuccess) showSuccess(`Added custom attribute: ${newAttribute.name}`);
    };

    const removeAttribute = (index) => {
        onChange(attributes.filter((_, i) => i !== index));
    };

    const updateAttribute = (index, field, value) => {
        const newAttrs = [...attributes];
        newAttrs[index] = { ...newAttrs[index], [field]: value };
        onChange(newAttrs);
    };

    const toggleTerm = (attrIndex, term) => {
        const attr = attributes[attrIndex];
        const options = Array.isArray(attr.options) ? attr.options : [];
        const termName = typeof term === 'string' ? term : term.name;

        const newOptions = options.includes(termName)
            ? options.filter(o => o !== termName)
            : [...options, termName];

        updateAttribute(attrIndex, 'options', newOptions);
    };

    const selectAllTerms = (attrIndex) => {
        const attr = attributes[attrIndex];
        const terms = attributeTerms[String(attr.id)] || [];
        updateAttribute(attrIndex, 'options', terms.map(t => t.name));
    };

    const deselectAllTerms = (attrIndex) => {
        updateAttribute(attrIndex, 'options', []);
    };

    if (loading) {
        return <div style={{ padding: '12px', color: '#6b7280' }}>Loading attributes...</div>;
    }

    // Safety check
    if (!Array.isArray(attributes)) {
        console.error('Attributes is not an array:', attributes);
        return <div style={{ padding: '12px', color: '#dc2626' }}>Error: Invalid attributes data</div>;
    }

    const handleSaveAttributes = async () => {
        if (showSuccess) showSuccess('Attributes updated! You can now generate variations.');
        // The attributes are already in the parent state, so they'll be saved with the product
    };

    return (
        <div className="attribute-manager">
            <p className="field-description">
                Attributes let you define extra product data, such as size or color.
                {productType === 'variable' && ' Use them to create product variations.'}
            </p>

            {/* Existing Attributes */}
            {attributes.length > 0 && (
                <div className="attributes-list">
                    {attributes.map((attr, index) => {
                        if (!attr || !attr.name) {
                            console.error('Invalid attribute at index', index, attr);
                            return null;
                        }

                        const isExpanded = expandedAttributes[index];
                        const terms = attr.id ? attributeTerms[String(attr.id)] || [] : [];
                        const selectedOptions = Array.isArray(attr.options) ? attr.options : [];

                        console.log('Rendering attribute:', attr.name, 'ID:', attr.id, 'Terms:', terms);

                        return (
                            <div key={index} className="attribute-item">
                                <div className="attribute-header">
                                    <button
                                        type="button"
                                        className="expand-btn"
                                        onClick={() => toggleExpand(index)}
                                    >
                                        {isExpanded ? '▼' : '▶'}
                                    </button>
                                    <strong>{attr.name}</strong>
                                    <span className="attribute-count">
                                        ({selectedOptions.length} selected)
                                    </span>
                                    <button
                                        type="button"
                                        className="btn-remove"
                                        onClick={() => removeAttribute(index)}
                                        title="Remove attribute"
                                    >
                                        ✕
                                    </button>
                                </div>

                                {isExpanded && (
                                    <div className="attribute-content">
                                        {/* Terms Selection */}
                                        {attr.id > 0 ? (
                                            terms.length > 0 ? (
                                                <div className="form-group">
                                                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '8px' }}>
                                                        <label style={{ margin: 0 }}>Select Values</label>
                                                        <div className="terms-actions">
                                                            <button
                                                                type="button"
                                                                className="btn-link"
                                                                onClick={() => selectAllTerms(index)}
                                                                style={{ fontSize: '12px', padding: '2px 8px' }}
                                                            >
                                                                Select all
                                                            </button>
                                                            <span style={{ margin: '0 4px', color: '#d1d5db' }}>|</span>
                                                            <button
                                                                type="button"
                                                                className="btn-link"
                                                                onClick={() => deselectAllTerms(index)}
                                                                style={{ fontSize: '12px', padding: '2px 8px' }}
                                                            >
                                                                Clear
                                                            </button>
                                                        </div>
                                                    </div>

                                                    {/* Selected Terms Display */}
                                                    {selectedOptions.length > 0 && (
                                                        <div className="selected-terms" style={{
                                                            display: 'flex',
                                                            flexWrap: 'wrap',
                                                            gap: '6px',
                                                            marginBottom: '8px',
                                                            padding: '8px',
                                                            backgroundColor: '#f9fafb',
                                                            borderRadius: '4px',
                                                            border: '1px solid #e5e7eb'
                                                        }}>
                                                            {selectedOptions.map((option, optIdx) => (
                                                                <span key={optIdx} style={{
                                                                    display: 'inline-flex',
                                                                    alignItems: 'center',
                                                                    gap: '4px',
                                                                    padding: '4px 8px',
                                                                    backgroundColor: '#fff',
                                                                    border: '1px solid #d1d5db',
                                                                    borderRadius: '4px',
                                                                    fontSize: '13px'
                                                                }}>
                                                                    {option}
                                                                    <button
                                                                        type="button"
                                                                        onClick={() => {
                                                                            const term = terms.find(t => t.name === option);
                                                                            if (term) toggleTerm(index, term);
                                                                        }}
                                                                        style={{
                                                                            border: 'none',
                                                                            background: 'none',
                                                                            cursor: 'pointer',
                                                                            padding: '0 2px',
                                                                            color: '#6b7280',
                                                                            fontSize: '14px',
                                                                            lineHeight: '1'
                                                                        }}
                                                                        title="Remove"
                                                                    >
                                                                        ×
                                                                    </button>
                                                                </span>
                                                            ))}
                                                        </div>
                                                    )}

                                                    {/* Search Input */}
                                                    <input
                                                        type="text"
                                                        className="terms-search-input"
                                                        placeholder="Search terms..."
                                                        value={termSearchQuery[index] || ''}
                                                        onChange={(e) => setTermSearchQuery(prev => ({
                                                            ...prev,
                                                            [index]: e.target.value
                                                        }))}
                                                    />

                                                    {/* Searchable Checkbox List */}
                                                    <div className="terms-checkbox-list">
                                                        {terms
                                                            .filter(term => {
                                                                const query = (termSearchQuery[index] || '').toLowerCase();
                                                                return !query || term.name.toLowerCase().includes(query);
                                                            })
                                                            .map(term => (
                                                                <label
                                                                    key={term.id}
                                                                    className="term-checkbox-item"
                                                                >
                                                                    <input
                                                                        type="checkbox"
                                                                        checked={selectedOptions.includes(term.name)}
                                                                        onChange={() => toggleTerm(index, term)}
                                                                    />
                                                                    <span>{term.name}</span>
                                                                </label>
                                                            ))}
                                                        {terms.filter(term => {
                                                            const query = (termSearchQuery[index] || '').toLowerCase();
                                                            return !query || term.name.toLowerCase().includes(query);
                                                        }).length === 0 && (
                                                                <p className="no-terms-message">
                                                                    No terms found
                                                                </p>
                                                            )}
                                                    </div>
                                                </div>
                                            ) : (
                                                <div className="form-group">
                                                    <p style={{ color: '#6b7280', fontSize: '13px', marginBottom: '8px' }}>
                                                        No terms found for this attribute. {attr.id > 0 ? 'Add terms in WooCommerce → Products → Attributes.' : 'Enter custom values below.'}
                                                    </p>
                                                    <label>Values</label>

                                                    {/* Selected Values Display */}
                                                    {selectedOptions.length > 0 && (
                                                        <div style={{
                                                            display: 'flex',
                                                            flexWrap: 'wrap',
                                                            gap: '6px',
                                                            marginBottom: '8px',
                                                            padding: '8px',
                                                            backgroundColor: '#f9fafb',
                                                            borderRadius: '4px',
                                                            border: '1px solid #e5e7eb'
                                                        }}>
                                                            {selectedOptions.map((option, optIdx) => (
                                                                <span key={optIdx} style={{
                                                                    display: 'inline-flex',
                                                                    alignItems: 'center',
                                                                    gap: '4px',
                                                                    padding: '4px 8px',
                                                                    backgroundColor: '#fff',
                                                                    border: '1px solid #d1d5db',
                                                                    borderRadius: '4px',
                                                                    fontSize: '13px'
                                                                }}>
                                                                    {option}
                                                                    <button
                                                                        type="button"
                                                                        onClick={() => {
                                                                            updateAttribute(index, 'options', selectedOptions.filter((_, i) => i !== optIdx));
                                                                        }}
                                                                        style={{
                                                                            border: 'none',
                                                                            background: 'none',
                                                                            cursor: 'pointer',
                                                                            padding: '0 2px',
                                                                            color: '#6b7280',
                                                                            fontSize: '14px',
                                                                            lineHeight: '1'
                                                                        }}
                                                                        title="Remove"
                                                                    >
                                                                        ×
                                                                    </button>
                                                                </span>
                                                            ))}
                                                        </div>
                                                    )}

                                                    <input
                                                        type="text"
                                                        placeholder="Type a value and press Enter"
                                                        onKeyDown={(e) => {
                                                            if (e.key === 'Enter') {
                                                                e.preventDefault();
                                                                const value = e.target.value.trim();
                                                                if (value && !selectedOptions.includes(value)) {
                                                                    updateAttribute(index, 'options', [...selectedOptions, value]);
                                                                    e.target.value = '';
                                                                }
                                                            }
                                                        }}
                                                    />
                                                    <p className="help-text" style={{ fontSize: '12px', color: '#6b7280', marginTop: '4px' }}>
                                                        Press Enter to add each value
                                                    </p>
                                                </div>
                                            )
                                        ) : (
                                            <div className="form-group">
                                                <label>Values</label>

                                                {/* Selected Values Display */}
                                                {selectedOptions.length > 0 && (
                                                    <div style={{
                                                        display: 'flex',
                                                        flexWrap: 'wrap',
                                                        gap: '6px',
                                                        marginBottom: '8px',
                                                        padding: '8px',
                                                        backgroundColor: '#f9fafb',
                                                        borderRadius: '4px',
                                                        border: '1px solid #e5e7eb'
                                                    }}>
                                                        {selectedOptions.map((option, optIdx) => (
                                                            <span key={optIdx} style={{
                                                                display: 'inline-flex',
                                                                alignItems: 'center',
                                                                gap: '4px',
                                                                padding: '4px 8px',
                                                                backgroundColor: '#fff',
                                                                border: '1px solid #d1d5db',
                                                                borderRadius: '4px',
                                                                fontSize: '13px'
                                                            }}>
                                                                {option}
                                                                <button
                                                                    type="button"
                                                                    onClick={() => {
                                                                        updateAttribute(index, 'options', selectedOptions.filter((_, i) => i !== optIdx));
                                                                    }}
                                                                    style={{
                                                                        border: 'none',
                                                                        background: 'none',
                                                                        cursor: 'pointer',
                                                                        padding: '0 2px',
                                                                        color: '#6b7280',
                                                                        fontSize: '14px',
                                                                        lineHeight: '1'
                                                                    }}
                                                                    title="Remove"
                                                                >
                                                                    ×
                                                                </button>
                                                            </span>
                                                        ))}
                                                    </div>
                                                )}

                                                <input
                                                    type="text"
                                                    placeholder="Type a value and press Enter"
                                                    onKeyDown={(e) => {
                                                        if (e.key === 'Enter') {
                                                            e.preventDefault();
                                                            const value = e.target.value.trim();
                                                            if (value && !selectedOptions.includes(value)) {
                                                                updateAttribute(index, 'options', [...selectedOptions, value]);
                                                                e.target.value = '';
                                                            }
                                                        }
                                                    }}
                                                />
                                                <p className="help-text" style={{ fontSize: '12px', color: '#6b7280', marginTop: '4px' }}>
                                                    Press Enter to add each value
                                                </p>
                                            </div>
                                        )}

                                        {/* Toggles */}
                                        <div className="attribute-toggles">
                                            <label className="checkbox-label">
                                                <input
                                                    type="checkbox"
                                                    checked={attr.visible || false}
                                                    onChange={(e) => updateAttribute(index, 'visible', e.target.checked)}
                                                />
                                                <span>Visible on product page</span>
                                            </label>
                                            {productType === 'variable' && (
                                                <label className="checkbox-label">
                                                    <input
                                                        type="checkbox"
                                                        checked={attr.variation || false}
                                                        onChange={(e) => updateAttribute(index, 'variation', e.target.checked)}
                                                    />
                                                    <span>Used for variations</span>
                                                </label>
                                            )}
                                        </div>
                                    </div>
                                )}
                            </div>
                        );
                    })}
                </div>
            )}

            {attributes.length === 0 && (
                <p style={{ color: '#6b7280', fontSize: '14px', marginBottom: '16px' }}>
                    No attributes added yet
                </p>
            )}

            {/* Add Attribute Buttons */}
            <div className="add-attribute-buttons">
                {globalAttributes.length > 0 ? (
                    <div className="dropdown-wrapper">
                        <select
                            onChange={(e) => {
                                const value = e.target.value;
                                console.log('Selected attribute ID:', value, typeof value);
                                console.log('Available attributes:', globalAttributes);
                                if (value) {
                                    const attr = globalAttributes.find(a => {
                                        const attrId = String(a.id || a.attribute_id);
                                        console.log('Comparing:', attrId, 'with', value, '=', attrId === value);
                                        return attrId === value;
                                    });
                                    console.log('Found attribute:', attr);
                                    if (attr) {
                                        // Normalize the attribute structure
                                        const normalizedAttr = {
                                            id: attr.id || attr.attribute_id,
                                            name: attr.name || attr.attribute_name,
                                            slug: attr.slug || attr.attribute_name?.toLowerCase().replace(/[^a-z0-9]+/g, '-')
                                        };
                                        addGlobalAttribute(normalizedAttr);
                                    }
                                    e.target.value = '';
                                }
                            }}
                            className="attribute-select"
                            defaultValue=""
                        >
                            <option value="">+ Add global attribute</option>
                            {globalAttributes.map(attr => {
                                const attrId = attr.id || attr.attribute_id;
                                const attrName = attr.name || attr.attribute_name;
                                return (
                                    <option key={attrId} value={attrId}>
                                        {attrName}
                                    </option>
                                );
                            })}
                        </select>
                    </div>
                ) : (
                    <p style={{ fontSize: '13px', color: '#6b7280', marginBottom: '12px' }}>
                        No global attributes found. You can add custom attributes or create global attributes in WooCommerce.
                    </p>
                )}
                <button
                    type="button"
                    className="btn btn-secondary btn-sm"
                    onClick={addCustomAttribute}
                >
                    + Add custom attribute
                </button>
            </div>

            {/* Save Attributes Button */}
            {productType === 'variable' && attributes.length > 0 && (
                <button
                    type="button"
                    className="btn btn-primary btn-block"
                    onClick={handleSaveAttributes}
                    style={{ marginTop: '16px' }}
                >
                    Save Attributes
                </button>
            )}

            {/* Add Custom Attribute Modal */}
            {showAddModal && (
                <div className="modal-overlay" onClick={() => setShowAddModal(false)}>
                    <div className="modal-content modal-sm" onClick={(e) => e.stopPropagation()}>
                        <div className="modal-header">
                            <h3>Add Custom Attribute</h3>
                            <button
                                type="button"
                                className="modal-close"
                                onClick={() => setShowAddModal(false)}
                            >
                                ✕
                            </button>
                        </div>

                        <div className="modal-body">
                            <div className="form-group">
                                <label>Name *</label>
                                <input
                                    type="text"
                                    value={newAttribute.name}
                                    onChange={(e) => setNewAttribute(prev => ({
                                        ...prev,
                                        name: e.target.value
                                    }))}
                                    placeholder="e.g., Size, Color, Material"
                                    required
                                    autoFocus
                                />
                            </div>

                            <div className="form-group">
                                <label>Value(s)</label>
                                <input
                                    type="text"
                                    value={newAttribute.values}
                                    onChange={(e) => setNewAttribute(prev => ({
                                        ...prev,
                                        values: e.target.value
                                    }))}
                                    placeholder="Small | Medium | Large"
                                />
                                <p className="help-text">
                                    Separate multiple values with | (pipe)
                                </p>
                            </div>

                            <div className="form-group">
                                <label className="checkbox-label">
                                    <input
                                        type="checkbox"
                                        checked={newAttribute.visible}
                                        onChange={(e) => setNewAttribute(prev => ({
                                            ...prev,
                                            visible: e.target.checked
                                        }))}
                                    />
                                    <span>Visible on product page</span>
                                </label>
                            </div>

                            {productType === 'variable' && (
                                <div className="form-group">
                                    <label className="checkbox-label">
                                        <input
                                            type="checkbox"
                                            checked={newAttribute.variation}
                                            onChange={(e) => setNewAttribute(prev => ({
                                                ...prev,
                                                variation: e.target.checked
                                            }))}
                                        />
                                        <span>Used for variations</span>
                                    </label>
                                </div>
                            )}
                        </div>

                        <div className="modal-footer">
                            <button
                                type="button"
                                className="btn btn-secondary"
                                onClick={() => setShowAddModal(false)}
                            >
                                Cancel
                            </button>
                            <button
                                type="button"
                                className="btn btn-primary"
                                onClick={(e) => {
                                    e.preventDefault();
                                    e.stopPropagation();
                                    handleAddCustomAttribute(e);
                                }}
                            >
                                Add Attribute
                            </button>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
};

export default AttributeManager;
