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

const CategoryTagModal = ({
    type = 'category', // 'category', 'tag', or 'brand'
    open,
    onClose,
    onSave,
    showError,
    showSuccess
}) => {
    const [loading, setLoading] = useState(false);
    const [formData, setFormData] = useState({
        name: '',
        slug: '',
        description: '',
        parent: 0
    });
    const [availableParents, setAvailableParents] = useState([]);

    useEffect(() => {
        if (open && type === 'category') {
            loadParentCategories();
        }
    }, [open, type]);

    const loadParentCategories = async () => {
        try {
            const response = await api.getProductCategories();
            if (response.success) {
                setAvailableParents(response.categories || []);
            }
        } catch (error) {
            console.error('Error loading parent categories:', error);
        }
    };

    const handleInputChange = (field, value) => {
        setFormData(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();
            setFormData(prev => ({ ...prev, slug }));
        }
    };

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

        if (!formData.name.trim()) {
            showError('Name is required');
            return;
        }

        setLoading(true);

        try {
            let response;
            if (type === 'category') {
                response = await api.createProductCategory(formData);
            } else if (type === 'tag') {
                response = await api.createProductTag(formData);
            } else if (type === 'brand') {
                response = await api.createProductBrand(formData);
            }

            if (response.success) {
                showSuccess(`${type === 'category' ? 'Category' : type === 'tag' ? 'Tag' : 'Brand'} created successfully`);
                onSave(response.data);
                onClose();
                setFormData({ name: '', slug: '', description: '', parent: 0 });
            } else {
                throw new Error(response.message || `Failed to create ${type}`);
            }
        } catch (error) {
            showError(error.message);
        } finally {
            setLoading(false);
        }
    };

    if (!open) return null;

    return (
        <div className="modal-overlay" onClick={onClose}>
            <div className="modal-content" onClick={(e) => e.stopPropagation()}>
                <div className="modal-header">
                    <h3>Create New {type === 'category' ? 'Category' : type === 'tag' ? 'Tag' : 'Brand'}</h3>
                    <button type="button" className="modal-close" onClick={onClose}>
                        ✕
                    </button>
                </div>

                <form onSubmit={handleSubmit}>
                    <div className="modal-body">
                        <div className="form-group">
                            <label>Name *</label>
                            <input
                                type="text"
                                value={formData.name}
                                onChange={(e) => handleInputChange('name', e.target.value)}
                                placeholder={`Enter ${type} name`}
                                required
                            />
                        </div>

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

                        {type === 'category' && (
                            <div className="form-group">
                                <label>Parent Category</label>
                                <select
                                    value={formData.parent}
                                    onChange={(e) => handleInputChange('parent', parseInt(e.target.value))}
                                >
                                    <option value={0}>None (Top Level)</option>
                                    {availableParents.map(category => (
                                        <option key={category.id} value={category.id}>
                                            {category.name}
                                        </option>
                                    ))}
                                </select>
                            </div>
                        )}

                        <div className="form-group">
                            <label>Description</label>
                            <textarea
                                value={formData.description}
                                onChange={(e) => handleInputChange('description', e.target.value)}
                                placeholder={`Optional ${type} description`}
                                rows="3"
                            />
                        </div>
                    </div>

                    <div className="modal-footer">
                        <button
                            type="button"
                            className="btn btn-secondary"
                            onClick={onClose}
                            disabled={loading}
                        >
                            Cancel
                        </button>
                        <button
                            type="submit"
                            className={`btn btn-primary ${loading ? 'btn-loading' : ''}`}
                            disabled={loading}
                        >
                            {loading ? (
                                <>
                                    <div className="spinner"></div>
                                    Creating...
                                </>
                            ) : (
                                `Create ${type === 'category' ? 'Category' : type === 'tag' ? 'Tag' : 'Brand'}`
                            )}
                        </button>
                    </div>
                </form>
            </div>
        </div>
    );
};

export default CategoryTagModal;