import { useEffect, useRef, useState } from "react";
import { useNavigate } from "react-router-dom";
import { useTranslation } from "react-i18n-lite";
import { booksApi } from "../../api/books";
import { useDebounce } from "../../hooks/useDebounce";
import type { BookListItem } from "../../types/book";
import styles from "./SearchSuggestions.module.css";

interface SearchSuggestionsProps {
  query: string;
  visible: boolean;
  onClose: () => void;
  onSelectSuggestion: () => void;
}

export function SearchSuggestions({ query, visible, onClose, onSelectSuggestion }: SearchSuggestionsProps) {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const [suggestions, setSuggestions] = useState<BookListItem[]>([]);
  const [loading, setLoading] = useState(false);
  const containerRef = useRef<HTMLDivElement>(null);
  const debouncedQuery = useDebounce(query, 200);

  useEffect(() => {
    if (!debouncedQuery.trim()) {
      setSuggestions([]);
      return;
    }
    let cancelled = false;
    setLoading(true);
    void booksApi.searchBooks({ q: debouncedQuery.trim(), page_size: 5 }).then(
      (res) => {
        if (!cancelled) {
          setSuggestions(res.results);
          setLoading(false);
        }
      },
      () => {
        if (!cancelled) {
          setSuggestions([]);
          setLoading(false);
        }
      },
    );
    return () => {
      cancelled = true;
    };
  }, [debouncedQuery]);

  useEffect(() => {
    if (!visible) return;
    const handler = (e: MouseEvent) => {
      if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
        onClose();
      }
    };
    const timer = setTimeout(() => document.addEventListener("click", handler), 0);
    return () => {
      clearTimeout(timer);
      document.removeEventListener("click", handler);
    };
  }, [visible, onClose]);

  useEffect(() => {
    if (!visible) return;
    const handler = (e: KeyboardEvent) => {
      if (e.key === "Escape") onClose();
    };
    document.addEventListener("keydown", handler);
    return () => document.removeEventListener("keydown", handler);
  }, [visible, onClose]);

  if (!visible || !query.trim()) return null;

  return (
    <div ref={containerRef} className={styles.container}>
      {loading && (
        <div className={styles.infoText}>
          {t("search.searching")}
        </div>
      )}
      {!loading && suggestions.length === 0 && debouncedQuery.trim() && (
        <div className={styles.infoText}>
          {t("search.noSuggestions")}
        </div>
      )}
      {suggestions.map((book) => (
        <div
          key={book.id}
          className={styles.suggestionItem}
          onClick={() => {
            onSelectSuggestion();
            navigate(`/books/${book.id}`);
          }}
        >
          <span className={styles.coverPlaceholder}>
            {book.cover_image ? (
              <img
                src={book.cover_image}
                alt=""
                className={styles.coverImage}
              />
            ) : (
              "📖"
            )}
          </span>
          <div className={styles.bookInfo}>
            <div className={styles.bookTitle}>
              {book.title}
            </div>
            <div className={styles.bookAuthor}>
              {book.author || t("common.unknownAuthor")}
            </div>
          </div>
        </div>
      ))}
    </div>
  );
}
