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

const TagSelector = ({ selectedTags = [], onChange, showError, showSuccess }) => {
    const [tags, setTags] = useState([]);
    const [loading, setLoading] = useState(true);
    const [searchTerm, setSearchTerm] = useState('');
    const [showAddModal, setShowAddModal] = useState(false);
    const [newTag, setNewTag] = useState({
        name: '',
        slug: '',
        description: ''
    });
    const [saving, setSaving] = useState(false);

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

    const loadTags = async () => {
        try {
            setLoading(true);
            const response = await api.getProductTags();
            if (response.success) {
                setTags(response.tags || []);
            }
        } catch (error) {
            console.error('Error loading tags:', error);
        } finally {
            setLoading(false);
        }
    };

    const handleToggleTag = (tag) => {
        const isSelected = selectedTags.some(t => t.id === tag.id);
        
        if (isSelected) {
            onChange(selectedTags.filter(t => t.id !== tag.id));
        } else {
            onChange([...selectedTags, tag]);
        }
    };

    const handleRemoveTag = (tagId) => {
        onChange(selectedTags.filter(t => t.id !== tagId));
    };

    const handleCreateTag = async (e) => {
        e.preventDefault();
        e.stopPropagation();
        
        if (!newTag.name.trim()) {
            if (showError) showError('Tag name is required');
            return;
        }

        try {
            setSaving(true);
            // Remove empty slug to let WordPress auto-generate it
            const tagData = { ...newTag };
            if (!tagData.slug || tagData.slug.trim() === '') {
                delete tagData.slug;
            }
            const response = await api.createProductTag(tagData);
            
            if (response.success) {
                if (showSuccess) showSuccess('Tag created successfully');
                const createdTag = response.tag || response.data;
                setTags([...tags, createdTag]);
                onChange([...selectedTags, createdTag]);
                setShowAddModal(false);
                setNewTag({ name: '', slug: '', description: '' });
                await loadTags(); // Reload to ensure we have the latest
            } else {
                throw new Error(response.message || 'Failed to create tag');
            }
        } catch (error) {
            console.error('Error creating tag:', error);
            if (showError) showError(error.message || 'Failed to create tag');
        } finally {
            setSaving(false);
        }
    };

    const filteredTags = tags.filter(tag =>
        tag.name.toLowerCase().includes(searchTerm.toLowerCase())
    );

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

    return (
        <div className="tag-selector">
            {/* Selected Tags */}
            {selectedTags.length > 0 && (
                <div className="selected-tags">
                    {selectedTags.map(tag => (
                        <span key={tag.id} className="tag-chip">
                            {tag.name}
                            <button
                                type="button"
                                onClick={() => handleRemoveTag(tag.id)}
                                className="tag-remove"
                            >
                                ✕
                            </button>
                        </span>
                    ))}
                </div>
            )}

            {/* Search Input */}
            <div className="form-group" style={{ marginBottom: '12px' }}>
                <input
                    type="text"
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                    placeholder="Search tags..."
                />
            </div>

            {/* Available Tags */}
            <div className="tag-list">
                {filteredTags.length === 0 ? (
                    <p style={{ padding: '12px', color: '#6b7280', margin: 0 }}>
                        {searchTerm ? 'No tags found' : 'No tags available'}
                    </p>
                ) : (
                    <div className="tag-checkboxes">
                        {filteredTags.map(tag => (
                            <label key={tag.id} className="tag-item">
                                <input
                                    type="checkbox"
                                    checked={selectedTags.some(t => t.id === tag.id)}
                                    onChange={() => handleToggleTag(tag)}
                                />
                                <span>{tag.name}</span>
                                {tag.count > 0 && (
                                    <span className="tag-count">({tag.count})</span>
                                )}
                            </label>
                        ))}
                    </div>
                )}
            </div>

            <button
                type="button"
                className="btn btn-secondary btn-sm btn-block"
                onClick={() => setShowAddModal(true)}
                style={{ marginTop: '12px' }}
            >
                + Add New Tag
            </button>

            {/* Add Tag Modal */}
            {showAddModal && createPortal(
                <div className="modal-overlay" onClick={(e) => {
                    e.stopPropagation();
                    setShowAddModal(false);
                }}>
                    <div className="modal-content modal-sm" onClick={(e) => e.stopPropagation()}>
                        <div className="modal-header">
                            <h3>Add New Tag</h3>
                            <button 
                                type="button" 
                                className="modal-close"
                                onClick={(e) => {
                                    e.preventDefault();
                                    e.stopPropagation();
                                    setShowAddModal(false);
                                }}
                            >
                                ✕
                            </button>
                        </div>
                        
                        <form onSubmit={handleCreateTag} onClick={(e) => e.stopPropagation()}>
                            <div className="modal-body">
                                <div className="form-group">
                                    <label>Name *</label>
                                    <input
                                        type="text"
                                        value={newTag.name}
                                        onChange={(e) => setNewTag(prev => ({
                                            ...prev,
                                            name: e.target.value
                                        }))}
                                        placeholder="Tag name"
                                        required
                                    />
                                </div>

                                <div className="form-group">
                                    <label>Slug</label>
                                    <input
                                        type="text"
                                        value={newTag.slug}
                                        onChange={(e) => setNewTag(prev => ({
                                            ...prev,
                                            slug: e.target.value
                                        }))}
                                        placeholder="tag-slug"
                                    />
                                    <p className="help-text">
                                        Leave blank to auto-generate from name
                                    </p>
                                </div>

                                <div className="form-group">
                                    <label>Description</label>
                                    <textarea
                                        value={newTag.description}
                                        onChange={(e) => setNewTag(prev => ({
                                            ...prev,
                                            description: e.target.value
                                        }))}
                                        rows="3"
                                        placeholder="Optional tag description"
                                    />
                                </div>
                            </div>

                            <div className="modal-footer">
                                <button
                                    type="button"
                                    className="btn btn-secondary"
                                    onClick={(e) => {
                                        e.preventDefault();
                                        e.stopPropagation();
                                        setShowAddModal(false);
                                    }}
                                    disabled={saving}
                                >
                                    Cancel
                                </button>
                                <button
                                    type="submit"
                                    className="btn btn-primary"
                                    disabled={saving}
                                >
                                    {saving ? 'Creating...' : 'Create Tag'}
                                </button>
                            </div>
                        </form>
                    </div>
                </div>,
                document.body
            )}
        </div>
    );
};

export default TagSelector;
