import React, { useEffect, useRef, useState } from 'react';
import { __ } from '@wordpress/i18n';
import { Modal, Input, Spin } from 'antd';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faMagnifyingGlass, faFileLines, faInbox, faGear, faArrowRight } from '@fortawesome/free-solid-svg-icons';
import * as api from '../services/api';
import { _pg } from './adminData';

/** Pages people jump to most, shown before they type. */
const PAGES = () => [
  { kind: 'page', title: __( 'All forms', 'formglut' ), url: _pg.all_forms },
  { kind: 'page', title: __( 'Entries', 'formglut' ), url: _pg.entries },
  { kind: 'page', title: __( 'Global Settings', 'formglut' ), url: _pg.settings },
  { kind: 'page', title: __( 'Data & Logs', 'formglut' ), url: _pg.tools },
].filter((p) => p.url);

const ICONS = { form: faFileLines, entry: faInbox, page: faGear };

/**
 * Search forms and entries from any FormGlut screen: press / (outside a text box), or the header button.
 * `button` shows the search button; without it only the shortcut opens the box.
 */
export default function GlobalSearch({ button = true }) {
  const [open, setOpen] = useState(false);
  const [q, setQ] = useState('');
  const [results, setResults] = useState(null);
  const [loading, setLoading] = useState(false);
  const [active, setActive] = useState(0);
  const timer = useRef(null);
  const seq = useRef(0);
  const inputRef = useRef(null);

  useEffect(() => {
    // "/" opens the search (not while typing). Ctrl / ⌘ + K is left to the WordPress command palette.
    const onKey = (e) => {
      const t = e.target;
      const typing = t && (t.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName));
      if (e.key === '/' && !typing && !e.metaKey && !e.ctrlKey && !e.altKey) {
        e.preventDefault();
        setOpen(true);
      }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, []);

  useEffect(() => {
    clearTimeout(timer.current);
    const term = q.trim();
    if (term.length < 2) { setResults(null); setLoading(false); return undefined; }
    setLoading(true);
    timer.current = setTimeout(() => {
      const mine = ++seq.current;
      api.request('formglut_global_search', { q: term }, 'GET')
        .then((d) => { if (mine === seq.current) { setResults([...(d.forms || []), ...(d.entries || [])]); setActive(0); } })
        .catch(() => { if (mine === seq.current) setResults([]); })
        .finally(() => { if (mine === seq.current) setLoading(false); });
    }, 250);
    return () => clearTimeout(timer.current);
  }, [q]);

  const term = q.trim().toLowerCase();
  const pages = PAGES().filter((p) => !term || p.title.toLowerCase().includes(term));
  const list = q.trim().length < 2 ? pages : [...(results || []), ...pages];
  const go = (item) => { if (item && item.url) window.location.href = item.url; };

  const onKeyDown = (e) => {
    if (e.key === 'ArrowDown') { e.preventDefault(); setActive((a) => Math.min(list.length - 1, a + 1)); }
    if (e.key === 'ArrowUp') { e.preventDefault(); setActive((a) => Math.max(0, a - 1)); }
    if (e.key === 'Enter') { e.preventDefault(); go(list[active]); }
  };

  const close = () => { setOpen(false); setQ(''); setResults(null); };

  return (
    <>
      {button && (
        <button type="button" className="fg-search-btn" onClick={() => setOpen(true)} title={__( 'Search forms and entries (press /)', 'formglut' )}>
          <FontAwesomeIcon icon={faMagnifyingGlass} />
          <span className="fg-search-btn-text">{__( 'Search', 'formglut' )}</span>
          <kbd>/</kbd>
        </button>
      )}
      <Modal open={open} onCancel={close} footer={null} closable={false} width={620} destroyOnClose className="fg-search-modal" styles={{ body: { padding: 0 } }} afterOpenChange={(o) => { if (o && inputRef.current) inputRef.current.focus(); }}>
        <Input
          ref={inputRef}
          autoFocus
          size="large"
          variant="borderless"
          prefix={<FontAwesomeIcon icon={faMagnifyingGlass} style={{ color: '#94a3b8', marginRight: 6 }} />}
          suffix={loading ? <Spin size="small" /> : <kbd className="fg-search-kbd">Esc</kbd>}
          placeholder={__( 'Search forms by name, entries by any answer…', 'formglut' )}
          value={q}
          onChange={(e) => setQ(e.target.value)}
          onKeyDown={onKeyDown}
          style={{ padding: '14px 16px', borderBottom: '1px solid #e2e8f0' }}
        />
        <div className="fg-search-results" role="listbox">
          {list.length === 0 && !loading && (
            <div className="fg-search-empty">{q.trim().length < 2 ? __( 'Type at least 2 characters.', 'formglut' ) : __( 'Nothing found.', 'formglut' )}</div>
          )}
          {list.map((item, i) => (
            <a
              key={item.kind + (item.id || item.title)}
              href={item.url}
              role="option"
              aria-selected={i === active}
              className={'fg-search-item' + (i === active ? ' is-active' : '')}
              onMouseEnter={() => setActive(i)}
            >
              <span className="fg-search-ic"><FontAwesomeIcon icon={ICONS[item.kind] || faGear} /></span>
              <span className="fg-search-main">
                <span className="fg-search-title">{item.title}</span>
                {item.subtitle && <span className="fg-search-sub">{item.subtitle}</span>}
              </span>
              <FontAwesomeIcon icon={faArrowRight} className="fg-search-go" />
            </a>
          ))}
        </div>
      </Modal>
    </>
  );
}
