"use client";

import { useState, useCallback, useRef } from "react";

const TYPE_STYLES: Record<string, { color: string; bg: string }> = {
  Function: { color: "var(--accent)", bg: "var(--accent-glow)" },
  Class: { color: "var(--green)", bg: "var(--green-dim)" },
  Method: { color: "var(--yellow)", bg: "var(--yellow-dim)" },
};

interface Props {
  onSelect: (uid: string) => void;
}

export function SearchBar({ onSelect }: Props) {
  const [query, setQuery] = useState("");
  const [results, setResults] = useState<any[]>([]);
  const [open, setOpen] = useState(false);
  const requestIdRef = useRef(0);
  const debounceRef = useRef<ReturnType<typeof setTimeout>>();

  const search = useCallback((q: string) => {
    setQuery(q);
    if (q.length < 2) {
      setResults([]);
      setOpen(false);
      return;
    }

    clearTimeout(debounceRef.current);
    debounceRef.current = setTimeout(async () => {
      const id = ++requestIdRef.current;
      try {
        const res = await fetch(`/api/symbols?q=${encodeURIComponent(q)}&limit=10`);
        const data = await res.json();
        if (id === requestIdRef.current) {
          setResults(data.results || []);
          setOpen(true);
        }
      } catch {}
    }, 200);
  }, []);

  return (
    <div className="relative">
      <div className="relative">
        <svg className="absolute left-3 top-1/2 -translate-y-1/2 w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" style={{ color: "var(--text-muted)" }}>
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
        </svg>
        <input
          type="text"
          placeholder="Search symbols..."
          value={query}
          onChange={(e) => search(e.target.value)}
          onFocus={() => results.length > 0 && setOpen(true)}
          onBlur={() => setTimeout(() => setOpen(false), 200)}
          className="w-72 pl-9 pr-3 py-1.5 rounded-lg text-xs border outline-none focus:border-[var(--accent)]"
          style={{
            background: "var(--bg)",
            borderColor: "var(--border)",
            color: "var(--text)",
          }}
        />
      </div>
      {open && results.length > 0 && (
        <div
          className="absolute top-full right-0 mt-2 w-96 rounded-xl border z-50 max-h-80 overflow-y-auto fade-in"
          style={{ background: "var(--surface)", borderColor: "var(--border)", boxShadow: "var(--shadow-lg)" }}
        >
          {results.map((r, i) => {
            const style = TYPE_STYLES[r.node_type] || TYPE_STYLES.Function;
            return (
              <button
                key={r.uid}
                className="w-full text-left px-4 py-2.5 text-xs flex items-center gap-3 hover:opacity-80"
                style={{ borderBottom: i < results.length - 1 ? "1px solid var(--border)" : "none" }}
                onClick={() => {
                  onSelect(r.uid);
                  setOpen(false);
                  setQuery(r.name);
                }}
              >
                <span
                  className="px-1.5 py-0.5 rounded text-[10px] font-medium mono shrink-0"
                  style={{ color: style.color, background: style.bg }}
                >
                  {r.node_type}
                </span>
                <span className="font-medium mono" style={{ color: "var(--text)" }}>{r.name}</span>
                <span className="ml-auto text-[10px] truncate max-w-[140px]" style={{ color: "var(--text-muted)" }}>
                  {r.file_path}
                </span>
              </button>
            );
          })}
        </div>
      )}
    </div>
  );
}
