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

const AttributeModal = ({
    open,
    onClose,
    onSave,
    showError,
    showSuccess
}) => {
    const [loading, setLoading] = useState(false);
    const [activeTab, setActiveTab] = useState('create');
    const [attributes, setAttributes] = useState([]);
    const [selectedAttribute, setSelectedAttribute] = useState(null);
    const [attributeTerms, setAttributeTerms] = useState([]);

    const [newAttribute, setNewAttribute] = useState({
        name: '',
        slug: '',
        type: 'select'
    });

    const [newTerm, setNewTerm] = useState({
        name: '',
        slug: ''
    });

    useEffect(() => {
        if (open) {
            loadAttributes();
        }
    }, [open]);

    const loadAttributes = async () => {
        try {
            const response = await api.getProductAttributes();
            if (response.success) {
                setAttributes(response.attributes || []);
            }
        } catch (error) {
            console.error('Error loading attributes:', error);
        }
    };

    const loadAttributeTerms = async (attributeId) => {
        try {
            const response = await api.getAttributeTerms(attributeId);
            if (response.success) {
                setAttributeTerms(response.terms || []);
            }
        } catch (error) {
            console.error('Error loading attribute terms:', error);
            setAttributeTerms([]);
        }
    };

    const handleCreateAttribute = async (e) => {
        e.preventDefault();

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

        setLoading(true);

        try {
            const response = await api.createProductAttribute(newAttribute);

            if (response.success) {
                showSuccess('Attribute created successfully');
                setNewAttribute({ name: '', slug: '', type: 'select' });
                await loadAttributes();
                setActiveTab('manage');
            } else {
                throw new Error(response.message || 'Failed to create attribute');
            }
        } catch (error) {
            showError(error.message);
        } finally {
            setLoading(false);
        }
    };

    const handleCreateTerm = async (e) => {
        e.preventDefault();

        if (!newTerm.name.trim() || !selectedAttribute) {
            showError('Term name and attribute selection are required');
            return;
        }

        setLoading(true);

        try {
            const response = await api.createAttributeTerm(selectedAttribute.id, newTerm);

            if (response.success) {
                showSuccess('Term created successfully');
                setNewTerm({ name: '', slug: '' });
                await loadAttributeTerms(selectedAttribute.id);
            } else {
                throw new Error(response.message || 'Failed to create term');
            }
        } catch (error) {
            showError(error.message);
        } finally {
            setLoading(false);
        }
    };

    const handleAttributeSelect = (attribute) => {
        setSelectedAttribute(attribute);
        loadAttributeTerms(attribute.id);
    };

    const handleInputChange = (field, value, target = 'attribute') => {
        if (target === 'attribute') {
            setNewAttribute(prev => ({ ...prev, [field]: value }));

            // Auto-generate slug from name
            if (field === 'name') {
                const slug = value.toLowerCase()
                    .replace(/[^a-z0-9\s-]/g, '')
                    .replace(/\s+/g, '-')
                    .replace(/-+/g, '-')
                    .trim();
                setNewAttribute(prev => ({ ...prev, slug }));
            }
        } else {
            setNewTerm(prev => ({ ...prev, [field]: value }));

            // Auto-generate slug from name
            if (field === 'name') {
                const slug = value.toLowerCase()
                    .replace(/[^a-z0-9\s-]/g, '')
                    .replace(/\s+/g, '-')
                    .replace(/-+/g, '-')
                    .trim();
                setNewTerm(prev => ({ ...prev, slug }));
            }
        }
    };

    const handleSaveAttribute = (attribute) => {
        onSave(attribute);
        onClose();
    };

    if (!open) return null;

    return (
        <div className="modal-overlay" onClick={onClose}>
            <div className="modal-content modal-large" onClick={(e) => e.stopPropagation()}>
                <div className="modal-header">
                    <h3>Manage Product Attributes</h3>
                    <button type="button" className="modal-close" onClick={onClose}>
                        ✕
                    </button>
                </div>

                <div className="modal-body">
                    {/* Tab Navigation */}
                    <div className="tab-navigation mb-4">
                        <button
                            type="button"
                            className={`tab-button ${activeTab === 'create' ? 'active' : ''}`}
                            onClick={() => setActiveTab('create')}
                        >
                            Create Attribute
                        </button>
                        <button
                            type="button"
                            className={`tab-button ${activeTab === 'manage' ? 'active' : ''}`}
                            onClick={() => setActiveTab('manage')}
                        >
                            Manage Terms
                        </button>
                        <button
                            type="button"
                            className={`tab-button ${activeTab === 'select' ? 'active' : ''}`}
                            onClick={() => setActiveTab('select')}
                        >
                            Select Attributes
                        </button>
                    </div>

                    {/* Create Attribute Tab */}
                    {activeTab === 'create' && (
                        <form onSubmit={handleCreateAttribute}>
                            <div className="form-group">
                                <label>Attribute Name *</label>
                                <input
                                    type="text"
                                    value={newAttribute.name}
                                    onChange={(e) => handleInputChange('name', e.target.value, 'attribute')}
                                    placeholder="Enter attribute name (e.g., Color, Size)"
                                    required
                                />
                            </div>

                            <div className="form-group">
                                <label>Slug</label>
                                <input
                                    type="text"
                                    value={newAttribute.slug}
                                    onChange={(e) => handleInputChange('slug', e.target.value, 'attribute')}
                                    placeholder="Auto-generated from name"
                                />
                                <small className="form-help">
                                    The slug is the URL-friendly version of the name
                                </small>
                            </div>

                            <div className="form-group">
                                <label>Type</label>
                                <select
                                    value={newAttribute.type}
                                    onChange={(e) => handleInputChange('type', e.target.value, 'attribute')}
                                >
                                    <option value="select">Select</option>
                                    <option value="text">Text</option>
                                </select>
                            </div>

                            <button
                                type="submit"
                                className={`btn btn-primary ${loading ? 'btn-loading' : ''}`}
                                disabled={loading}
                            >
                                {loading ? 'Creating...' : 'Create Attribute'}
                            </button>
                        </form>
                    )}

                    {/* Manage Terms Tab */}
                    {activeTab === 'manage' && (
                        <div>
                            <div className="form-group">
                                <label>Select Attribute</label>
                                <select
                                    value={selectedAttribute?.id || ''}
                                    onChange={(e) => {
                                        const attr = attributes.find(a => a.id === parseInt(e.target.value));
                                        handleAttributeSelect(attr);
                                    }}
                                >
                                    <option value="">Choose an attribute</option>
                                    {attributes.map(attr => (
                                        <option key={attr.id} value={attr.id}>
                                            {attr.name}
                                        </option>
                                    ))}
                                </select>
                            </div>

                            {selectedAttribute && (
                                <div>
                                    <h4>Terms for "{selectedAttribute.name}"</h4>

                                    {/* Existing Terms */}
                                    <div className="terms-list mb-4">
                                        {attributeTerms.length > 0 ? (
                                            <div className="terms-grid">
                                                {attributeTerms.map(term => (
                                                    <div key={term.id} className="term-item">
                                                        <span className="term-name">{term.name}</span>
                                                        <span className="term-slug">({term.slug})</span>
                                                    </div>
                                                ))}
                                            </div>
                                        ) : (
                                            <p className="text-gray-500">No terms found for this attribute</p>
                                        )}
                                    </div>

                                    {/* Add New Term */}
                                    <form onSubmit={handleCreateTerm}>
                                        <h5>Add New Term</h5>
                                        <div className="grid grid-cols-2 gap-4">
                                            <div className="form-group">
                                                <label>Term Name *</label>
                                                <input
                                                    type="text"
                                                    value={newTerm.name}
                                                    onChange={(e) => handleInputChange('name', e.target.value, 'term')}
                                                    placeholder="Enter term name (e.g., Red, Large)"
                                                    required
                                                />
                                            </div>
                                            <div className="form-group">
                                                <label>Slug</label>
                                                <input
                                                    type="text"
                                                    value={newTerm.slug}
                                                    onChange={(e) => handleInputChange('slug', e.target.value, 'term')}
                                                    placeholder="Auto-generated from name"
                                                />
                                            </div>
                                        </div>
                                        <button
                                            type="submit"
                                            className={`btn btn-secondary ${loading ? 'btn-loading' : ''}`}
                                            disabled={loading}
                                        >
                                            {loading ? 'Adding...' : 'Add Term'}
                                        </button>
                                    </form>
                                </div>
                            )}
                        </div>
                    )}

                    {/* Select Attributes Tab */}
                    {activeTab === 'select' && (
                        <div>
                            <h4>Available Attributes</h4>
                            <p className="text-gray-600 mb-4">
                                Click on an attribute to add it to your product
                            </p>

                            <div className="attributes-grid">
                                {attributes.map(attribute => (
                                    <div
                                        key={attribute.id}
                                        className="attribute-card"
                                        onClick={() => handleSaveAttribute(attribute)}
                                    >
                                        <div className="attribute-name">{attribute.name}</div>
                                        <div className="attribute-type">{attribute.type}</div>
                                        <div className="attribute-slug">{attribute.slug}</div>
                                    </div>
                                ))}
                            </div>

                            {attributes.length === 0 && (
                                <p className="text-gray-500">
                                    No attributes found. Create some attributes first.
                                </p>
                            )}
                        </div>
                    )}
                </div>

                <div className="modal-footer">
                    <button
                        type="button"
                        className="btn btn-secondary"
                        onClick={onClose}
                    >
                        Close
                    </button>
                </div>
            </div>
        </div>
    );
};

export default AttributeModal;