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

const BrandSelector = ({ selectedBrands = [], onChange, showError, showSuccess }) => {
    const [brands, setBrands] = useState([]);
    const [loading, setLoading] = useState(true);
    const [searchTerm, setSearchTerm] = useState('');
    const [showCreateModal, setShowCreateModal] = useState(false);
    const [newBrandName, setNewBrandName] = useState('');
    const [creating, setCreating] = useState(false);

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

    const loadBrands = async () => {
        try {
            setLoading(true);
            const response = await api.getProductBrands();
            console.log('Brands API response:', response);
            if (response.success) {
                setBrands(response.brands || []);
            }
        } catch (error) {
            console.error('Error loading brands:', error);
            if (showError) showError('Failed to load brands');
        } finally {
            setLoading(false);
        }
    };

    const handleToggleBrand = (brand) => {
        const isSelected = selectedBrands.some(b => b.id === brand.id);

        if (isSelected) {
            onChange(selectedBrands.filter(b => b.id !== brand.id));
        } else {
            onChange([...selectedBrands, brand]);
        }
    };

    const handleRemoveBrand = (brandId) => {
        onChange(selectedBrands.filter(b => b.id !== brandId));
    };

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

        if (!newBrandName.trim()) {
            if (showError) showError('Brand name is required');
            return;
        }

        try {
            setCreating(true);
            const response = await api.createProductBrand({ name: newBrandName.trim() });

            if (response.success) {
                if (showSuccess) showSuccess('Brand created successfully');
                setNewBrandName('');
                setShowCreateModal(false);
                await loadBrands();
            } else {
                if (showError) showError(response.message || 'Failed to create brand');
            }
        } catch (error) {
            console.error('Error creating brand:', error);
            if (showError) showError('Failed to create brand');
        } finally {
            setCreating(false);
        }
    };

    const filteredBrands = brands.filter(brand =>
        brand.name.toLowerCase().includes(searchTerm.toLowerCase())
    );

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

    return (
        <div className="brand-selector">
            {/* Selected Brands */}
            {selectedBrands.length > 0 && (
                <div className="selected-brands">
                    {selectedBrands.map(brand => (
                        <span key={brand.id} className="brand-chip">
                            {brand.name}
                            <button
                                type="button"
                                onClick={() => handleRemoveBrand(brand.id)}
                                className="brand-remove"
                            >
                                ✕
                            </button>
                        </span>
                    ))}
                </div>
            )}

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

            {/* Brands List */}
            <div className="brand-list">
                {filteredBrands.length === 0 ? (
                    <p style={{ padding: '12px', color: '#6b7280', margin: 0 }}>
                        {searchTerm ? 'No brands found' : 'No brands available'}
                    </p>
                ) : (
                    <div className="brand-checkboxes">
                        {filteredBrands.map(brand => (
                            <label key={brand.id} className="brand-item">
                                <input
                                    type="checkbox"
                                    checked={selectedBrands.some(b => b.id === brand.id)}
                                    onChange={() => handleToggleBrand(brand)}
                                />
                                <span>{brand.name}</span>
                            </label>
                        ))}
                    </div>
                )}
            </div>

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

            {/* Create Brand Modal */}
            {showCreateModal && createPortal(
                <div className="modal-overlay" onClick={(e) => {
                    e.stopPropagation();
                    setShowCreateModal(false);
                }}>
                    <div className="modal-content modal-sm" onClick={(e) => e.stopPropagation()}>
                        <div className="modal-header">
                            <h3>Create New Brand</h3>
                            <button
                                type="button"
                                className="modal-close"
                                onClick={(e) => {
                                    e.preventDefault();
                                    e.stopPropagation();
                                    setShowCreateModal(false);
                                }}
                            >
                                ✕
                            </button>
                        </div>

                        <form onSubmit={handleCreateBrand} onClick={(e) => e.stopPropagation()}>
                            <div className="modal-body">
                                <div className="form-group">
                                    <label>Brand Name *</label>
                                    <input
                                        type="text"
                                        value={newBrandName}
                                        onChange={(e) => setNewBrandName(e.target.value)}
                                        placeholder="e.g., Nike, Apple, Samsung"
                                        required
                                        autoFocus
                                    />
                                </div>
                            </div>

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

export default BrandSelector;
