// UserSearch Component
// Multi-field search for finding users by email, username, or share code

function UserSearch({ token, onUserSelect, t }) {
    const [query, setQuery] = useState('');
    const [results, setResults] = useState([]);
    const [loading, setLoading] = useState(false);
    const [debounceTimer, setDebounceTimer] = useState(null);

    const searchUsers = async (searchQuery) => {
        if (!searchQuery || searchQuery.length < 2) {
            setResults([]);
            return;
        }

        setLoading(true);
        try {
            const response = await fetch(API_URL + `/users/search?q=${encodeURIComponent(searchQuery)}`, {
                headers: { 'Authorization': `Bearer ${token}` }
            });
            const data = await response.json();
            setResults(data.users || []);
        } catch (err) {
            console.error('Search failed:', err);
            setResults([]);
        } finally {
            setLoading(false);
        }
    };

    const handleInputChange = (e) => {
        const value = e.target.value;
        setQuery(value);

        // Debounce search
        if (debounceTimer) {
            clearTimeout(debounceTimer);
        }

        const timer = setTimeout(() => {
            searchUsers(value);
        }, 300); // 300ms delay

        setDebounceTimer(timer);
    };

    const handleUserClick = (user) => {
        if (onUserSelect) {
            onUserSelect(user);
        }
    };

    const handleAddFriend = async (user) => {
        try {
            const response = await fetch(API_URL + `/connections/add?connected_user_id=${user.id}`, {
                method: 'POST',
                headers: { 'Authorization': `Bearer ${token}` }
            });

            if (response.ok) {
                // Update the user's is_friend status in results
                setResults(prev => prev.map(u =>
                    u.id === user.id ? { ...u, is_friend: true } : u
                ));
                window.showToast?.(`✓ Added ${user.name} to your friends!`, 'success');
            } else {
                window.showToast?.('Failed to add friend', 'error');
            }
        } catch (err) {
            console.error('Add friend failed:', err);
            window.showToast?.('Failed to add friend', 'error');
        }
    };

    return (
        <div style={{ marginBottom: '2rem' }}>
            {/* Search Input */}
            <div style={{ position: 'relative', marginBottom: '1.5rem' }}>
                <div style={{
                    display: 'flex',
                    alignItems: 'center',
                    padding: '0.75rem 1rem',
                    background: 'var(--card-bg)',
                    border: '2px solid var(--border-color)',
                    borderRadius: '12px',
                    transition: 'border-color 0.2s'
                }}>
                    <span style={{ fontSize: '20px', marginRight: '0.75rem' }}>🔍</span>
                    <input
                        type="text"
                        value={query}
                        onChange={handleInputChange}
                        placeholder="@username, email, NV-XXXXXX, or profile link"
                        style={{
                            flex: 1,
                            border: 'none',
                            background: 'transparent',
                            fontSize: '16px',
                            outline: 'none',
                            color: 'var(--text-primary)'
                        }}
                    />
                    {loading && <span style={{ fontSize: '16px' }}>⏳</span>}
                </div>
                <p style={{ fontSize: '12px', color: 'var(--text-tertiary)', marginTop: '0.5rem' }}>
                    Search by username, email, share code, or profile URL
                </p>
            </div>

            {/* Results */}
            {query.length >= 2 && (
                <div>
                    {loading && results.length === 0 ? (
                        <div style={{ textAlign: 'center', padding: '2rem', color: 'var(--text-secondary)' }}>
                            Searching...
                        </div>
                    ) : results.length > 0 ? (
                        <div style={{ display: 'grid', gap: '1rem' }}>
                            {results.map(user => (
                                <div
                                    key={user.id}
                                    className="card"
                                    style={{
                                        padding: '1rem',
                                        cursor: 'pointer',
                                        transition: 'transform 0.2s, box-shadow 0.2s',
                                        border: '1px solid var(--border-color)'
                                    }}
                                    onMouseEnter={(e) => {
                                        e.currentTarget.style.transform = 'translateY(-2px)';
                                        e.currentTarget.style.boxShadow = '0 4px 12px rgba(0,0,0,0.1)';
                                    }}
                                    onMouseLeave={(e) => {
                                        e.currentTarget.style.transform = 'translateY(0)';
                                        e.currentTarget.style.boxShadow = 'none';
                                    }}
                                >
                                    <div style={{ display: 'flex', alignItems: 'center', gap: '1rem' }}>
                                        {/* Avatar */}
                                        <div style={{
                                            width: '48px',
                                            height: '48px',
                                            borderRadius: '50%',
                                            background: 'linear-gradient(135deg, var(--primary), var(--secondary, #6366f1))',
                                            display: 'flex',
                                            alignItems: 'center',
                                            justifyContent: 'center',
                                            fontSize: '20px',
                                            fontWeight: '700',
                                            color: 'white'
                                        }}>
                                            {user.name?.charAt(0).toUpperCase() || '?'}
                                        </div>

                                        {/* User Info */}
                                        <div style={{ flex: 1 }}>
                                            <div style={{ fontWeight: '600', fontSize: '16px', marginBottom: '0.25rem' }}>
                                                {user.name}
                                            </div>
                                            <div style={{ fontSize: '14px', color: 'var(--text-secondary)' }}>
                                                {user.username ? `@${user.username}` : user.email}
                                                {user.share_code && (
                                                    <span style={{ marginLeft: '0.5rem', fontSize: '12px', opacity: 0.7 }}>
                                                        • NV-{user.share_code}
                                                    </span>
                                                )}
                                            </div>
                                            {user.bio && (
                                                <div style={{
                                                    fontSize: '12px',
                                                    color: 'var(--text-tertiary)',
                                                    marginTop: '0.25rem',
                                                    overflow: 'hidden',
                                                    textOverflow: 'ellipsis',
                                                    whiteSpace: 'nowrap'
                                                }}>
                                                    {user.bio}
                                                </div>
                                            )}
                                        </div>

                                        {/* Action Button */}
                                        {user.is_friend ? (
                                            <span style={{
                                                padding: '0.5rem 1rem',
                                                fontSize: '14px',
                                                color: 'var(--success, #10b981)',
                                                border: '2px solid var(--success, #10b981)',
                                                borderRadius: '8px',
                                                fontWeight: '600',
                                                whiteSpace: 'nowrap'
                                            }}>
                                                ✓ Friend
                                            </span>
                                        ) : (
                                            <button
                                                onClick={() => handleAddFriend(user)}
                                                className="btn btn-primary"
                                                style={{
                                                    padding: '0.5rem 1rem',
                                                    fontSize: '14px',
                                                    whiteSpace: 'nowrap'
                                                }}
                                            >
                                                + Add Friend
                                            </button>
                                        )}
                                    </div>
                                </div>
                            ))}
                        </div>
                    ) : query.length >= 2 && !loading ? (
                        <div className="card" style={{ padding: '2rem', textAlign: 'center' }}>
                            <div style={{ fontSize: '48px', marginBottom: '1rem' }}>🔍</div>
                            <h3 style={{ fontSize: '18px', fontWeight: '600', marginBottom: '0.5rem' }}>
                                No users found
                            </h3>
                            <p style={{ fontSize: '14px', color: 'var(--text-secondary)' }}>
                                Try: @username, email, NV-ABC123, or /profile/username
                            </p>
                        </div>
                    ) : null}
                </div>
            )}

            {/* Empty State */}
            {query.length === 0 && (
                <div className="card" style={{ padding: '2rem', textAlign: 'center', background: 'var(--secondary-bg)' }}>
                    <div style={{ fontSize: '48px', marginBottom: '1rem' }}>👥</div>
                    <h3 style={{ fontSize: '18px', fontWeight: '600', marginBottom: '0.5rem' }}>
                        Find People to Collaborate
                    </h3>
                    <p style={{ fontSize: '14px', color: 'var(--text-secondary)', marginBottom: '1rem' }}>
                        Start typing to search for users
                    </p>
                    <div style={{ display: 'flex', gap: '1rem', justifyContent: 'center', flexWrap: 'wrap', fontSize: '13px', color: 'var(--text-tertiary)' }}>
                        <span>💡 @username</span>
                        <span>•</span>
                        <span>📧 email@example.com</span>
                        <span>•</span>
                        <span>🔢 NV-ABC123</span>
                        <span>•</span>
                        <span>🔗 /profile/user</span>
                    </div>
                </div>
            )}
        </div>
    );
}

window.UserSearch = UserSearch;
