import React, { useMemo } from 'react';
import { useQuery } from 'convex/react';
import { api } from '../../../../convex/_generated/api';
import { useOnlineUsers } from '../contexts/PresenceContext';
import Tooltip from './Tooltip';

const ChatHeader = ({
    channelName,
    channelType,
    channelTopic,
    channelId,
    onToggleMembers,
    showMembers,
    onTogglePinned,
    serverName,
    isMobile,
    onMobileBack,
    onStartCall,
    isDMCallActive,
    onOpenMembersScreen,
    // Search props
    searchQuery,
    onSearchQueryChange,
    onSearchSubmit,
    onSearchFocus,
    onSearchBlur,
    searchInputRef,
    searchActive,
}) => {
    const isDM = channelType === 'dm';
    const searchPlaceholder = isDM ? 'Search' : `Search ${serverName || 'Server'}`;

    // Query members on mobile text channels only for online count
    const shouldQueryMembers = isMobile && !isDM && channelId;
    const members = useQuery(
        api.members.getChannelMembers,
        shouldQueryMembers ? { channelId } : "skip"
    ) || [];
    const { resolveStatus } = useOnlineUsers();
    const onlineCount = useMemo(() => {
        if (!shouldQueryMembers) return 0;
        return members.filter(m => resolveStatus(m.status, m.id) !== 'offline').length;
    }, [members, resolveStatus, shouldQueryMembers]);

    const handleSearchKeyDown = (e) => {
        if (e.key === 'Enter') {
            e.preventDefault();
            onSearchSubmit?.();
        }
        if (e.key === 'Escape') {
            e.preventDefault();
            onSearchBlur?.();
            e.target.blur();
        }
    };

    return (
        <div className="chat-header">
            <div className="chat-header-left">
                {isMobile && onMobileBack && (
                    <button className="mobile-back-btn" onClick={onMobileBack}>
                        <svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor"><path d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z"/></svg>
                    </button>
                )}
                {isMobile && !isDM ? (
                    <button className="mobile-channel-header-tap" onClick={onOpenMembersScreen}>
                        <div className="mobile-channel-header-top">
                            <span className="chat-header-icon">#</span>
                            <span className="chat-header-name">{channelName}</span>
                            <svg className="mobile-channel-chevron" width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
                                <path d="M9.29 6.71a1 1 0 0 0 0 1.41L13.17 12l-3.88 3.88a1 1 0 1 0 1.42 1.41l4.59-4.59a1 1 0 0 0 0-1.41L10.71 6.7a1 1 0 0 0-1.42 0Z"/>
                            </svg>
                        </div>
                        <div className="mobile-channel-header-bottom">
                            <span className="mobile-online-dot" />
                            <span className="mobile-online-count">{onlineCount ?? 0} Online</span>
                        </div>
                    </button>
                ) : (
                    <>
                        <span className="chat-header-icon">{isDM ? '@' : '#'}</span>
                        <span className="chat-header-name">{channelName}</span>
                        {channelTopic && !isDM && !isMobile && (
                            <>
                                <div className="chat-header-divider" />
                                <span className="chat-header-topic" title={channelTopic}>{channelTopic}</span>
                            </>
                        )}
                        {isDM && <span className="chat-header-status-text"></span>}
                    </>
                )}
            </div>
            <div className="chat-header-right">
                {!isDM && !isMobile && (
                    <Tooltip text="Threads" position="bottom">
                        <button className="chat-header-btn">
                            <svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
                                <path d="M5.43309 21C5.35842 21 5.30189 20.9325 5.31494 20.859L5.99991 17H2.14274C2.06819 17 2.01168 16.9327 2.02453 16.8593L2.33253 15.0993C2.34258 15.0419 2.39244 15 2.45074 15H6.34991L7.14991 10.5H3.29274C3.21819 10.5 3.16168 10.4327 3.17453 10.3593L3.48253 8.59926C3.49258 8.54185 3.54244 8.5 3.60074 8.5H7.49991L8.25674 4.49395C8.26688 4.43665 8.31672 4.395 8.37491 4.395H10.1919C10.2666 4.395 10.3231 4.4625 10.3101 4.536L9.59991 8.5H14.0999L14.8568 4.49395C14.8669 4.43665 14.9167 4.395 14.9749 4.395H16.7919C16.8666 4.395 16.9231 4.4625 16.9101 4.536L16.1999 8.5H20.0571C20.1316 8.5 20.1881 8.56734 20.1753 8.64074L19.8673 10.4007C19.8572 10.4581 19.8074 10.5 19.7491 10.5H15.8499L15.0499 15H18.9071C18.9816 15 19.0381 15.0673 19.0253 15.1407L18.7173 16.9007C18.7072 16.9581 18.6574 17 18.5991 17H14.6999L13.9431 21.006C13.9329 21.0634 13.8831 21.105 13.8249 21.105H12.0079C11.9332 21.105 11.8767 21.0375 11.8897 20.964L12.5999 17H8.09991L7.34309 21.006C7.33295 21.0634 7.28311 21.105 7.22491 21.105H5.43309V21ZM8.44991 15H12.9499L13.7499 10.5H9.24991L8.44991 15Z" />
                            </svg>
                        </button>
                    </Tooltip>
                )}
                {isDM && !isMobile && (
                    <Tooltip text={isDMCallActive ? "Join Call" : "Start Call"} position="bottom">
                        <button
                            className={`chat-header-btn ${isDMCallActive ? 'active' : ''}`}
                            onClick={onStartCall}
                            style={isDMCallActive ? { color: '#3ba55c' } : undefined}
                        >
                            <svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
                                <path d="M6.62 10.79a15.053 15.053 0 006.59 6.59l2.2-2.2a1.003 1.003 0 011.01-.24c1.12.37 2.33.57 3.57.57.55 0 1 .45 1 1V20c0 .55-.45 1-1 1C10.07 21 3 13.93 3 4c0-.55.45-1 1-1h3.5c.55 0 1 .45 1 1 0 1.25.2 2.45.57 3.57.1.31.03.66-.25 1.02l-2.2 2.2z"/>
                            </svg>
                        </button>
                    </Tooltip>
                )}
                <Tooltip text="Pinned Messages" position="bottom">
                    <button className="chat-header-btn" onClick={onTogglePinned}>
                        <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
                            <path fill="currentColor" d="M19.38 11.38a3 3 0 0 0 4.24 0l.03-.03a.5.5 0 0 0 0-.7L13.35.35a.5.5 0 0 0-.7 0l-.03.03a3 3 0 0 0 0 4.24L13 5l-2.92 2.92-3.65-.34a2 2 0 0 0-1.6.58l-.62.63a1 1 0 0 0 0 1.42l9.58 9.58a1 1 0 0 0 1.42 0l.63-.63a2 2 0 0 0 .58-1.6l-.34-3.64L19 11zM9.07 17.07a.5.5 0 0 1-.08.77l-5.15 3.43a.5.5 0 0 1-.63-.06l-.42-.42a.5.5 0 0 1-.06-.63L6.16 15a.5.5 0 0 1 .77-.08l2.14 2.14Z"/>
                        </svg>
                    </button>
                </Tooltip>
                {!isDM && !isMobile && (
                    <Tooltip text={showMembers ? "Hide Members" : "Show Members"} position="bottom">
                        <button
                            className={`chat-header-btn ${showMembers ? 'active' : ''}`}
                            onClick={onToggleMembers}
                        >
                            <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
                                <path fill="currentColor" d="M14.5 8a3 3 0 1 0-2.7-4.3c-.2.4.06.86.44 1.12a5 5 0 0 1 2.14 3.08c.01.06.06.1.12.1ZM18.44 17.27c.15.43.54.73 1 .73h1.06c.83 0 1.5-.67 1.5-1.5a7.5 7.5 0 0 0-6.5-7.43c-.55-.08-.99.38-1.1.92-.06.3-.15.6-.26.87-.23.58-.05 1.3.47 1.63a9.53 9.53 0 0 1 3.83 4.78ZM12.5 9a3 3 0 1 1-6 0 3 3 0 0 1 6 0ZM2 20.5a7.5 7.5 0 0 1 15 0c0 .83-.67 1.5-1.5 1.5a.2.2 0 0 1-.2-.16c-.2-.96-.56-1.87-.88-2.54-.1-.23-.42-.15-.42.1v2.1a.5.5 0 0 1-.5.5h-8a.5.5 0 0 1-.5-.5v-2.1c0-.25-.31-.33-.42-.1-.32.67-.67 1.58-.88 2.54a.2.2 0 0 1-.2.16A1.5 1.5 0 0 1 2 20.5Z"/>
                            </svg>
                        </button>
                    </Tooltip>
                )}
                {!isMobile && (
                    <Tooltip text="Notification Settings" position="bottom">
                        <button className="chat-header-btn">
                            <svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
                                <path d="M18 9V14C18 15.657 19.344 17 21 17V18H3V17C4.656 17 6 15.657 6 14V9C6 5.686 8.686 3 12 3C15.314 3 18 5.686 18 9ZM11.9999 22C10.5239 22 9.24993 20.955 8.99993 19.5H14.9999C14.7499 20.955 13.4759 22 11.9999 22Z" />
                            </svg>
                        </button>
                    </Tooltip>
                )}
                {!isMobile && (
                    <div className="chat-header-search-wrapper" ref={searchInputRef}>
                        <svg className="chat-header-search-icon" width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
                            <path d="M21.71 20.29L18 16.61A9 9 0 1016.61 18l3.68 3.68a1 1 0 001.42 0 1 1 0 000-1.39zM11 18a7 7 0 110-14 7 7 0 010 14z"/>
                        </svg>
                        <input
                            type="text"
                            placeholder={searchPlaceholder}
                            className={`chat-header-search ${searchActive ? 'focused' : ''}`}
                            value={searchQuery || ''}
                            onChange={(e) => onSearchQueryChange?.(e.target.value)}
                            onFocus={onSearchFocus}
                            onKeyDown={handleSearchKeyDown}
                        />
                        {searchQuery && (
                            <button
                                className="chat-header-search-clear"
                                onClick={() => onSearchQueryChange?.('')}
                            >
                                <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
                                    <path d="M18.4 4L12 10.4L5.6 4L4 5.6L10.4 12L4 18.4L5.6 20L12 13.6L18.4 20L20 18.4L13.6 12L20 5.6L18.4 4Z"/>
                                </svg>
                            </button>
                        )}
                    </div>
                )}
            </div>
        </div>
    );
};

export default ChatHeader;
