/**
 * Modal to add a restaurant concept. Used from Property Management (Dining, Venues & Amenities).
 * - Textbox filters over existing concept names (from all properties); user can select if available.
 * - If not found, user can proceed to create/add a new concept for this property.
 * onSave(name, propertyCode) — propertyCode required when adding from a property context.
 */
const RestaurantModal = ({ onSave, onClose, saving, propertyCode }) => {
    const { useState, useEffect, useRef } = React;
    const [inputValue, setInputValue] = useState('');
    const [suggestions, setSuggestions] = useState([]);
    const [loadingSuggestions, setLoadingSuggestions] = useState(false);
    const [selectedSuggestion, setSelectedSuggestion] = useState(null); // { name } when user picked from list
    const [showDropdown, setShowDropdown] = useState(false);
    const dropdownRef = useRef(null);

    // Debounced fetch of concept names (skip when user just selected a suggestion so dropdown doesn't re-open)
    useEffect(() => {
        if (!inputValue.trim()) {
            setSuggestions([]);
            setShowDropdown(false);
            return;
        }
        if (selectedSuggestion && inputValue.trim() === selectedSuggestion.name) {
            setSuggestions([]);
            setShowDropdown(false);
            return;
        }
        const t = setTimeout(async () => {
            setLoadingSuggestions(true);
            try {
                const q = encodeURIComponent(inputValue.trim());
                const res = await fetch(`/api/restaurants/concept-names?q=${q}&limit=15`, {
                    headers: window.getApiHeaders ? window.getApiHeaders() : { 'X-OTO-User': window.localStorage.getItem('oto_username') || '' }
                });
                if (res.ok) {
                    const data = await res.json();
                    const names = data.concept_names || [];
                    setSuggestions(names);
                    setShowDropdown(names.length > 0);
                } else {
                    setSuggestions([]);
                }
            } catch (err) {
                setSuggestions([]);
            } finally {
                setLoadingSuggestions(false);
            }
        }, 200);
        return () => clearTimeout(t);
    }, [inputValue, selectedSuggestion]);

    // Click outside to close dropdown
    useEffect(() => {
        const handleClickOutside = (e) => {
            if (dropdownRef.current && !dropdownRef.current.contains(e.target)) {
                setShowDropdown(false);
            }
        };
        document.addEventListener('mousedown', handleClickOutside);
        return () => document.removeEventListener('mousedown', handleClickOutside);
    }, []);

    const handleSelectSuggestion = (name) => {
        setInputValue(name);
        setSelectedSuggestion({ name });
        setShowDropdown(false);
        setSuggestions([]);
    };

    const handleSubmit = (e) => {
        e.preventDefault();
        const trimmed = (inputValue || '').trim();
        if (!trimmed || !propertyCode) return;
        onSave(trimmed, propertyCode);
        setInputValue('');
        setSelectedSuggestion(null);
    };

    const displayValue = selectedSuggestion ? selectedSuggestion.name : inputValue;
    const canCreate = (inputValue || '').trim().length > 0;

    return (
        <div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-4" onClick={onClose}>
            <div className="bg-white rounded-xl shadow-xl max-w-md w-full p-6" onClick={e => e.stopPropagation()}>
                <h3 className="text-lg font-semibold text-gray-900 mb-2">Add Dining Brand</h3>
                <p className="text-sm text-gray-600 mb-4">
                    Type to search existing dining brands or enter a new name to create one for this property.
                </p>
                <form onSubmit={handleSubmit}>
                    <div className="relative" ref={dropdownRef}>
                        <input
                            type="text"
                            value={displayValue}
                            onChange={(e) => {
                                setInputValue(e.target.value);
                                setSelectedSuggestion(null);
                            }}
                            onFocus={() => suggestions.length > 0 && setShowDropdown(true)}
                            placeholder="Search or enter dining brand name"
                            className="w-full border border-gray-300 rounded-lg px-4 py-2 mb-1 focus:ring-2 focus:ring-primary focus:border-primary"
                            autoFocus
                        />
                        {loadingSuggestions && (
                            <div className="absolute right-3 top-1/2 -translate-y-1/2">
                                <svg className="animate-spin h-4 w-4 text-gray-400" fill="none" viewBox="0 0 24 24">
                                    <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                                    <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
                                </svg>
                            </div>
                        )}
                        {showDropdown && suggestions.length > 0 && (
                            <ul className="absolute z-10 w-full mt-0.5 bg-white border border-gray-200 rounded-lg shadow-lg max-h-48 overflow-y-auto">
                                {suggestions.map((name) => (
                                    <li
                                        key={name}
                                        onClick={() => handleSelectSuggestion(name)}
                                        className="px-4 py-2 cursor-pointer hover:bg-primary/10 text-gray-900"
                                    >
                                        {name}
                                    </li>
                                ))}
                            </ul>
                        )}
                    </div>
                    <div className="flex justify-end gap-2 mt-4">
                        <button type="button" onClick={onClose} className="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50">
                            Cancel
                        </button>
                        <button
                            type="submit"
                            disabled={saving || !canCreate}
                            className="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary-hover disabled:opacity-50"
                        >
                            {saving ? 'Saving...' : (selectedSuggestion ? 'Add to this property' : 'Create & add to property')}
                        </button>
                    </div>
                </form>
            </div>
        </div>
    );
};

if (typeof window !== 'undefined') window.RestaurantModal = RestaurantModal;
