import { useState, useMemo, useRef, useEffect } from "preact/hooks";
import type { LinearIssue } from "../../lib/types";

interface Props {
  issues: LinearIssue[];
  onSelect: (issueId: string) => void;
}

export default function AttachDropdown({ issues, onSelect }: Props) {
  const [filter, setFilter] = useState("");
  const inputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    inputRef.current?.focus();
  }, []);

  const filtered = useMemo(() => {
    const fl = filter.toLowerCase();
    return issues
      .filter((i) => i.bucket !== "inactive-done")
      .filter((i) => !fl || i.identifier.toLowerCase().includes(fl) || i.title.toLowerCase().includes(fl))
      .slice(0, 10);
  }, [issues, filter]);

  return (
    <div class="attach-dd">
      <input
        ref={inputRef}
        class="attach-search"
        placeholder="Search issues..."
        onInput={(e) => setFilter((e.target as HTMLInputElement).value)}
      />
      <div class="issue-list">
        {filtered.length === 0 ? (
          <div class="no-issues">No matching issues</div>
        ) : (
          filtered.map((i) => (
            <div class="issue-opt" key={i.identifier} onClick={() => onSelect(i.identifier)}>
              <span class="issue-id">{i.identifier}</span>
              <span class="issue-title">{i.title}</span>
            </div>
          ))
        )}
      </div>
    </div>
  );
}
