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

const CategorySelector = ({ selectedCategories = [], onChange, showError, showSuccess }) => {
    const [categories, setCategories] = useState([]);
    const [loading, setLoading] = useState(true);
    const [showAddModal, setShowAddModal] = useState(false);
    const [newCategory, setNewCategory] = useState({
        name: '',
        slug: '',
        parent: 0,
        description: ''
    });
    const [saving, setSaving] = useState(false);

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

    const loadCategories = async () => {
        try {
            setLoading(true);
            const response = await api.getProductCategories();
            if (response.success) {
                setCategories(response.categories || []);
            }
        } catch (error) {
            console.error('Error loading categories:', error);
        } finally {
            setLoading(false);
        }
    };

    const handleToggleCategory = (category) => {
        const isSelected = selectedCategories.some(c => c.id === category.id);

        if (isSelected) {
            onChange(selectedCategories.filter(c => c.id !== category.id));
        } else {
            onChange([...selectedCategories, category]);
        }
    };

    const handleRemoveCategory = (categoryId) => {
        onChange(selectedCategories.filter(c => c.id !== categoryId));
    };

    const handleCreateCategory = async (e) => {
        e.preventDefault();
        e.stopPropagation();

        if (!newCategory.name.trim()) {
            if (showError) showError('Category name is required');
            return;
        }

        try {
            setSaving(true);
            // Remove empty slug to let WordPress auto-generate it
            const categoryData = { ...newCategory };
            if (!categoryData.slug || categoryData.slug.trim() === '') {
                delete categoryData.slug;
            }
            const response = await api.createProductCategory(categoryData);

            if (response.success) {
                if (showSuccess) showSuccess('Category created successfully');
                const createdCategory = response.category || response.data;
                setCategories([...categories, createdCategory]);
                onChange([...selectedCategories, createdCategory]);
                setShowAddModal(false);
                setNewCategory({ name: '', slug: '', parent: 0, description: '' });
                await loadCategories(); // Reload to ensure we have the latest
            } else {
                throw new Error(response.message || 'Failed to create category');
            }
        } catch (error) {
            console.error('Error creating category:', error);
            if (showError) showError(error.message || 'Failed to create category');
        } finally {
            setSaving(false);
        }
    };

    const renderCategoryTree = (parentId = 0, level = 0) => {
        return categories
            .filter(cat => cat.parent === parentId)
            .map(category => (
                <div key={category.id}>
                    <label
                        className="category-item"
                        style={{ paddingLeft: `${level * 20 + 8}px` }}
                    >
                        <input
                            type="checkbox"
                            checked={selectedCategories.some(c => c.id === category.id)}
                            onChange={() => handleToggleCategory(category)}
                        />
                        <span>{category.name}</span>
                        {category.count > 0 && (
                            <span className="category-count">({category.count})</span>
                        )}
                    </label>
                    {renderCategoryTree(category.id, level + 1)}
                </div>
            ));
    };

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

    return (
        <div className="category-selector">
            {/* Selected Categories */}
            {selectedCategories.length > 0 && (
                <div className="selected-categories">
                    {selectedCategories.map(category => (
                        <span key={category.id} className="category-chip">
                            {category.name}
                            <button
                                type="button"
                                onClick={() => handleRemoveCategory(category.id)}
                                className="category-remove"
                            >
                                ✕
                            </button>
                        </span>
                    ))}
                </div>
            )}

            <div className="category-list">
                {categories.length === 0 ? (
                    <p style={{ padding: '12px', color: '#6b7280', margin: 0 }}>
                        No categories found
                    </p>
                ) : (
                    renderCategoryTree()
                )}
            </div>

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

            {/* Add Category 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 Category</h3>
                            <button
                                type="button"
                                className="modal-close"
                                onClick={(e) => {
                                    e.preventDefault();
                                    e.stopPropagation();
                                    setShowAddModal(false);
                                }}
                            >
                                ✕
                            </button>
                        </div>

                        <form onSubmit={handleCreateCategory} onClick={(e) => e.stopPropagation()}>
                            <div className="modal-body">
                                <div className="form-group">
                                    <label>Name *</label>
                                    <input
                                        type="text"
                                        value={newCategory.name}
                                        onChange={(e) => setNewCategory(prev => ({
                                            ...prev,
                                            name: e.target.value
                                        }))}
                                        placeholder="Category name"
                                        required
                                    />
                                </div>

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

                                <div className="form-group">
                                    <label>Parent Category</label>
                                    <select
                                        value={newCategory.parent}
                                        onChange={(e) => setNewCategory(prev => ({
                                            ...prev,
                                            parent: parseInt(e.target.value)
                                        }))}
                                    >
                                        <option value="0">None</option>
                                        {categories.map(cat => (
                                            <option key={cat.id} value={cat.id}>
                                                {cat.name}
                                            </option>
                                        ))}
                                    </select>
                                </div>

                                <div className="form-group">
                                    <label>Description</label>
                                    <textarea
                                        value={newCategory.description}
                                        onChange={(e) => setNewCategory(prev => ({
                                            ...prev,
                                            description: e.target.value
                                        }))}
                                        rows="3"
                                        placeholder="Optional category 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 Category'}
                                </button>
                            </div>
                        </form>
                    </div>
                </div>,
                document.body
            )}
        </div>
    );
};

export default CategorySelector;
