import React, { useEffect, useRef, useState, useCallback } from 'react';
import ReactDOM from 'react-dom';
import { detectActivePrefix } from '../utils/searchUtils';

const FILTER_SUGGESTIONS = [
  { prefix: 'from:', label: 'from:', description: 'user', icon: 'user' },
  { prefix: 'mentions:', label: 'mentions:', description: 'user', icon: 'at' },
  { prefix: 'has:', label: 'has:', description: 'link, file, image, or video', icon: 'has' },
  { prefix: 'in:', label: 'in:', description: 'channel', icon: 'channel' },
  { prefix: 'before:', label: 'before:', description: 'date', icon: 'date' },
  { prefix: 'after:', label: 'after:', description: 'date', icon: 'date' },
  { prefix: 'pinned:', label: 'pinned:', description: 'true or false', icon: 'pin' },
];

const HAS_OPTIONS = [
  { value: 'link', label: 'link' },
  { value: 'file', label: 'file' },
  { value: 'image', label: 'image' },
  { value: 'video', label: 'video' },
];

function getAvatarColor(name) {
  const colors = ['#5865F2', '#57F287', '#FEE75C', '#EB459E', '#ED4245', '#F47B67', '#E67E22', '#3498DB'];
  let hash = 0;
  for (let i = 0; i < (name || '').length; i++) hash = name.charCodeAt(i) + ((hash << 5) - hash);
  return colors[Math.abs(hash) % colors.length];
}

function FilterIcon({ type }) {
  switch (type) {
    case 'user':
      return (
        <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
          <path d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z"/>
        </svg>
      );
    case 'at':
      return (
        <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
          <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10h5v-2h-5c-4.34 0-8-3.66-8-8s3.66-8 8-8 8 3.66 8 8v1.43c0 .79-.71 1.57-1.5 1.57s-1.5-.78-1.5-1.57V12c0-2.76-2.24-5-5-5s-5 2.24-5 5 2.24 5 5 5c1.38 0 2.64-.56 3.54-1.47.65.89 1.77 1.47 2.96 1.47 1.97 0 3.5-1.6 3.5-3.57V12c0-5.52-4.48-10-10-10zm0 13c-1.66 0-3-1.34-3-3s1.34-3 3-3 3 1.34 3 3-1.34 3-3 3z"/>
        </svg>
      );
    case 'has':
      return (
        <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
          <path d="M14 2H6c-1.1 0-2 .9-2 2v16c0 1.1.89 2 1.99 2H18c1.1 0 2-.9 2-2V8l-6-6zm4 18H6V4h7v5h5v11z"/>
        </svg>
      );
    case 'channel':
      return <span style={{ fontSize: 16, fontWeight: 700, opacity: 0.7 }}>#</span>;
    case 'date':
      return (
        <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
          <path d="M19 3h-1V1h-2v2H8V1H6v2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H5V8h14v11z"/>
        </svg>
      );
    case 'pin':
      return (
        <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
          <path d="M19.3 5.3a1 1 0 00-1.4-1.4L14.6 7.2l-1.5-.8a2 2 0 00-2.2.2L8.5 9a1 1 0 000 1.5l1.8 1.8-4.6 4.6a1 1 0 001.4 1.4l4.6-4.6 1.8 1.8a1 1 0 001.5 0l2.4-2.4a2 2 0 00.2-2.2l-.8-1.5 3.3-3.3z"/>
        </svg>
      );
    default:
      return null;
  }
}

const SearchDropdown = ({
  visible,
  searchText,
  channels,
  members,
  searchHistory,
  onSelectFilter,
  onSelectHistoryItem,
  onClearHistory,
  onClearHistoryItem,
  anchorRef,
  onClose,
}) => {
  const dropdownRef = useRef(null);
  const [pos, setPos] = useState({ top: 0, left: 0, width: 420 });

  // Position dropdown below anchor
  useEffect(() => {
    if (!visible || !anchorRef?.current) return;
    const rect = anchorRef.current.getBoundingClientRect();
    setPos({
      top: rect.bottom + 4,
      left: Math.max(rect.right - 420, 8),
      width: 420,
    });
  }, [visible, anchorRef, searchText]);

  // Click outside to close
  useEffect(() => {
    if (!visible) return;
    const handler = (e) => {
      if (
        dropdownRef.current && !dropdownRef.current.contains(e.target) &&
        anchorRef?.current && !anchorRef.current.contains(e.target)
      ) {
        onClose();
      }
    };
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, [visible, onClose, anchorRef]);

  if (!visible) return null;

  const activePrefix = detectActivePrefix(searchText);

  let content;

  if (activePrefix?.prefix === 'from' || activePrefix?.prefix === 'mentions') {
    const filtered = (members || []).filter(m =>
      m.username.toLowerCase().includes(activePrefix.partial)
    );
    const headerText = activePrefix.prefix === 'from' ? 'FROM USER' : 'MENTIONS USER';
    content = (
      <div className="search-dropdown-scrollable">
        <div className="search-dropdown-section-header">{headerText}</div>
        {filtered.length === 0 && (
          <div className="search-dropdown-empty">No matching users</div>
        )}
        {filtered.map(m => (
          <div
            key={m.id}
            className="search-dropdown-member"
            onClick={() => onSelectFilter(activePrefix.prefix, m.username)}
          >
            {m.avatarUrl ? (
              <img src={m.avatarUrl} className="search-dropdown-avatar" alt="" />
            ) : (
              <div className="search-dropdown-avatar" style={{ backgroundColor: getAvatarColor(m.username) }}>
                {m.username[0]?.toUpperCase()}
              </div>
            )}
            <span className="search-dropdown-member-name">{m.username}</span>
          </div>
        ))}
      </div>
    );
  } else if (activePrefix?.prefix === 'in') {
    const filtered = (channels || []).filter(c =>
      c.name?.toLowerCase().includes(activePrefix.partial) && c.type === 'text'
    );
    content = (
      <div className="search-dropdown-scrollable">
        <div className="search-dropdown-section-header">IN CHANNEL</div>
        {filtered.length === 0 && (
          <div className="search-dropdown-empty">No matching channels</div>
        )}
        {filtered.map(c => (
          <div
            key={c._id}
            className="search-dropdown-channel"
            onClick={() => onSelectFilter('in', c.name)}
          >
            <span className="search-dropdown-channel-hash">#</span>
            <span>{c.name}</span>
          </div>
        ))}
      </div>
    );
  } else if (activePrefix?.prefix === 'has') {
    const filtered = HAS_OPTIONS.filter(o =>
      o.value.includes(activePrefix.partial)
    );
    content = (
      <div className="search-dropdown-scrollable">
        <div className="search-dropdown-section-header">MESSAGE CONTAINS</div>
        {filtered.map(o => (
          <div
            key={o.value}
            className="search-dropdown-item"
            onClick={() => onSelectFilter('has', o.value)}
          >
            <FilterIcon type="has" />
            <span>{o.label}</span>
          </div>
        ))}
      </div>
    );
  } else {
    // Default: show filter suggestions + search history
    content = (
      <div className="search-dropdown-scrollable">
        <div className="search-dropdown-section-header">SEARCH OPTIONS</div>
        {FILTER_SUGGESTIONS.map(f => (
          <div
            key={f.prefix}
            className="search-dropdown-item"
            onClick={() => onSelectFilter(f.prefix.replace(':', ''), null)}
          >
            <span className="search-dropdown-item-icon"><FilterIcon type={f.icon} /></span>
            <span className="search-dropdown-item-label">{f.label}</span>
            <span className="search-dropdown-item-desc">{f.description}</span>
          </div>
        ))}
        {searchHistory && searchHistory.length > 0 && (
          <>
            <div className="search-dropdown-section-header search-dropdown-history-header">
              <span>SEARCH HISTORY</span>
              <button className="search-dropdown-clear-all" onClick={onClearHistory}>Clear</button>
            </div>
            {searchHistory.map((item, i) => (
              <div
                key={i}
                className="search-dropdown-history-item"
                onClick={() => onSelectHistoryItem(item)}
              >
                <svg className="search-dropdown-history-icon" width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
                  <path d="M13 3a9 9 0 00-9 9H1l3.89 3.89.07.14L9 12H6c0-3.87 3.13-7 7-7s7 3.13 7 7-3.13 7-7 7c-1.93 0-3.68-.79-4.94-2.06l-1.42 1.42A8.954 8.954 0 0013 21a9 9 0 000-18zm-1 5v5l4.28 2.54.72-1.21-3.5-2.08V8H12z"/>
                </svg>
                <span className="search-dropdown-history-text">{item}</span>
                <button
                  className="search-dropdown-history-delete"
                  onClick={(e) => { e.stopPropagation(); onClearHistoryItem(i); }}
                >
                  &times;
                </button>
              </div>
            ))}
          </>
        )}
      </div>
    );
  }

  return ReactDOM.createPortal(
    <div
      ref={dropdownRef}
      className="search-dropdown"
      style={{ top: pos.top, left: pos.left, width: pos.width }}
    >
      {content}
    </div>,
    document.body
  );
};

export default SearchDropdown;
