import { useEffect, useMemo, useRef, useState } from 'react';
import { getPosts } from '../../lib/api';
import { type SiteMode, copy } from '../../lib/siteMode';

interface Post {
  slug: string;
  date: string;
  title?: string;
  excerpt?: string;
  tags: string[];
  draft: boolean;
  reading_time: number;
}

function formatSlug(slug: string) {
  if (!slug) return '';
  return slug
    .split('-')
    .map(w => w.charAt(0).toUpperCase() + w.slice(1))
    .join(' ');
}

function formatDate(date: string) {
  return new Date(date).toLocaleDateString('en-US', {
    year: 'numeric',
    month: 'short',
    day: 'numeric',
  });
}

export default function Search({ mode = 'atelier' }: { mode?: SiteMode }) {
  const c = copy(mode);
  const [open, setOpen] = useState(false);
  const [query, setQuery] = useState('');
  const [posts, setPosts] = useState<Post[] | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [activeIdx, setActiveIdx] = useState(0);
  const [isMac, setIsMac] = useState(false);
  const inputRef = useRef<HTMLInputElement>(null);
  const listRef = useRef<HTMLUListElement>(null);

  useEffect(() => {
    setIsMac(/Mac|iPhone|iPad|iPod/i.test(navigator.userAgent));
  }, []);

  // Global Cmd/Ctrl+K + Esc listener
  useEffect(() => {
    function onKey(e: KeyboardEvent) {
      const mod = isMac ? e.metaKey : e.ctrlKey;
      if (mod && e.key.toLowerCase() === 'k') {
        e.preventDefault();
        setOpen(o => !o);
      } else if (e.key === 'Escape' && open) {
        setOpen(false);
      }
    }
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open, isMac]);

  // Lazy fetch posts on first open
  useEffect(() => {
    if (!open || posts !== null || loading) return;
    setLoading(true);
    getPosts()
      .then(p => setPosts(p as Post[]))
      .catch(e => setError(e instanceof Error ? e.message : 'Failed to load'))
      .finally(() => setLoading(false));
  }, [open, posts, loading]);

  // Focus input on open
  useEffect(() => {
    if (open) {
      setQuery('');
      setActiveIdx(0);
      requestAnimationFrame(() => inputRef.current?.focus());
    }
  }, [open]);

  // Lock body scroll when open
  useEffect(() => {
    if (!open) return;
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => { document.body.style.overflow = prev; };
  }, [open]);

  const results = useMemo(() => {
    if (!posts) return [];
    const q = query.trim().toLowerCase();
    if (!q) return posts;
    return posts.filter(p => {
      const hay = `${p.title || formatSlug(p.slug)} ${p.excerpt || ''} ${p.tags?.join(' ') || ''}`.toLowerCase();
      return hay.includes(q);
    });
  }, [posts, query]);

  // Reset active index when results change
  useEffect(() => {
    setActiveIdx(0);
  }, [query, posts]);

  function navigate(slug: string) {
    window.location.href = `/posts/${encodeURIComponent(slug)}`;
  }

  function onInputKey(e: React.KeyboardEvent<HTMLInputElement>) {
    if (e.key === 'ArrowDown') {
      e.preventDefault();
      setActiveIdx(i => Math.min(i + 1, Math.max(0, results.length - 1)));
    } else if (e.key === 'ArrowUp') {
      e.preventDefault();
      setActiveIdx(i => Math.max(i - 1, 0));
    } else if (e.key === 'Enter' && results[activeIdx]) {
      e.preventDefault();
      navigate(results[activeIdx].slug);
    }
  }

  // Scroll active result into view
  useEffect(() => {
    if (!open || !listRef.current) return;
    const el = listRef.current.children[activeIdx] as HTMLElement | undefined;
    el?.scrollIntoView({ block: 'nearest' });
  }, [activeIdx, open]);

  return (
    <>
      <button
        type="button"
        onClick={() => setOpen(true)}
        aria-label={`${c.searchAria} (${isMac ? '⌘' : 'Ctrl'}+K)`}
        className="topbar-control tc-collapse-md kbd-tip-host"
      >
        <svg
          xmlns="http://www.w3.org/2000/svg"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          strokeWidth="2"
          strokeLinecap="round"
          strokeLinejoin="round"
          aria-hidden="true"
        >
          <circle cx="11" cy="11" r="8" />
          <path d="m21 21-4.3-4.3" />
        </svg>
        <span className="tc-label">Search</span>
        <span className="kbd-tip" aria-hidden="true">
          <kbd>{isMac ? '⌘' : 'Ctrl'}</kbd>
          <kbd>K</kbd>
        </span>
      </button>

      {open && (
        <div
          className="search-overlay fixed inset-0 z-[200] flex items-start justify-center pt-[10vh] md:pt-[15vh] px-4"
          role="dialog"
          aria-modal="true"
          aria-label={c.searchAria}
          onClick={() => setOpen(false)}
        >
          <div
            className="search-backdrop absolute inset-0 bg-[var(--crust)]/55 backdrop-blur-md"
            aria-hidden="true"
          />
          <div
            className="search-panel relative w-full max-w-xl bg-[var(--base)] text-[var(--text)] border border-[var(--surface2)] overflow-hidden flex flex-col max-h-[70vh] animate-in fade-in slide-in-from-top-4 duration-200"
            style={{
              borderRadius: 2,
              boxShadow: '0 30px 60px -20px rgba(0,0,0,0.55), 0 8px 20px -8px rgba(0,0,0,0.3), inset 0 0 0 1px color-mix(in srgb, var(--surface1) 50%, transparent)',
            }}
            onClick={e => e.stopPropagation()}
          >
            <div className="search-bar flex items-center gap-3 px-4 py-3 border-b border-[var(--surface2)]/60 bg-[var(--surface0)]/40">
              <svg
                xmlns="http://www.w3.org/2000/svg"
                width="18"
                height="18"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
                strokeLinecap="round"
                strokeLinejoin="round"
                className="text-[var(--mauve)] shrink-0"
                aria-hidden="true"
              >
                <circle cx="11" cy="11" r="8" />
                <path d="m21 21-4.3-4.3" />
              </svg>
              <input
                ref={inputRef}
                type="search"
                value={query}
                onChange={e => setQuery(e.target.value)}
                onKeyDown={onInputKey}
                placeholder={`${c.searchPlaceholder}`}
                aria-label="Search query"
                className="search-input flex-1 bg-transparent outline-none text-base text-[var(--text)] placeholder:text-[var(--subtext0)] font-display italic"
              />
              <kbd className="text-[10px] font-mono text-[var(--subtext0)] px-1.5 py-0.5 border border-[var(--surface2)] bg-[var(--surface0)]/60" style={{ borderRadius: 1 }}>
                Esc
              </kbd>
            </div>

            <div className="flex-1 overflow-y-auto">
              {loading && (
                <div className="px-4 py-10 text-center font-display italic text-[var(--subtext0)]">{c.searchFetching}</div>
              )}
              {error && (
                <div className="px-4 py-8 text-center text-sm text-[var(--red)] font-display italic">{error}</div>
              )}
              {!loading && !error && posts && results.length === 0 && (
                <div className="px-4 py-10 text-center font-display italic text-[var(--subtext0)]">
                  {query ? c.searchNoMatch : c.searchEmpty}
                </div>
              )}
              {!loading && !error && results.length > 0 && (
                <ul ref={listRef} className="search-list py-1">
                  {results.map((p, i) => {
                    const title = p.title || formatSlug(p.slug);
                    const active = i === activeIdx;
                    return (
                      <li
                        key={p.slug}
                        onMouseEnter={() => setActiveIdx(i)}
                        onClick={() => navigate(p.slug)}
                        className={`search-result px-4 py-3 cursor-pointer border-l-2 transition-colors ${
                          active
                            ? 'search-result--active bg-[var(--surface0)] border-[var(--mauve)]'
                            : 'border-transparent hover:bg-[var(--surface0)]/60'
                        }`}
                      >
                        <div className="flex items-baseline justify-between gap-3">
                          <div className={`font-display italic truncate text-lg leading-tight pr-2 flex items-baseline gap-2 ${active ? 'text-[var(--mauve)]' : 'text-[var(--text)]'}`} style={{ paddingInlineEnd: '0.35em' }}>
                            <span className="truncate">{title}</span>
                            {p.draft && (
                              <span className="chip chip-draft shrink-0 !text-[0.62rem] !py-0">
                                {c.draftShort}
                              </span>
                            )}
                          </div>
                          <time className="text-[10px] font-sans uppercase tracking-[0.18em] text-[var(--subtext0)] shrink-0" dateTime={p.date}>
                            {formatDate(p.date)}
                          </time>
                        </div>
                        {p.excerpt && (
                          <div className="text-xs text-[var(--subtext1)] line-clamp-1 mt-0.5 font-sans italic">{p.excerpt}</div>
                        )}
                      </li>
                    );
                  })}
                </ul>
              )}
            </div>

            <div className="search-foot flex items-center justify-between px-4 py-2 border-t border-[var(--surface2)]/60 text-[10px] text-[var(--subtext0)] bg-[var(--surface0)]/40 font-display italic">
              <div className="flex items-center gap-3">
                <span className="flex items-center gap-1">
                  <kbd className="font-mono px-1 border border-[var(--surface2)] bg-[var(--surface0)]/60 not-italic" style={{ borderRadius: 1 }}>↑↓</kbd>
                  navigate
                </span>
                <span className="flex items-center gap-1">
                  <kbd className="font-mono px-1 border border-[var(--surface2)] bg-[var(--surface0)]/60 not-italic" style={{ borderRadius: 1 }}>↵</kbd>
                  open
                </span>
              </div>
              <span>{results.length} {results.length === 1 ? 'result' : 'results'}</span>
            </div>
          </div>
        </div>
      )}
    </>
  );
}
