import { useState, useMemo, useRef, useEffect } from "react";
import Fuse from "fuse.js";

interface ProductIndex {
  id: string;
  name: string;
  category: string;
}

interface Props {
  products: ProductIndex[];
  basePath: string;
}

export default function SearchBar({ products, basePath }: Props) {
  const [query, setQuery] = useState("");
  const [isOpen, setIsOpen] = useState(false);
  const wrapRef = useRef<HTMLDivElement>(null);

  const fuse = useMemo(
    () =>
      new Fuse(products, {
        keys: ["name", "category"],
        threshold: 0.3,
        includeScore: true,
      }),
    [products],
  );

  const results = query.length >= 2 ? fuse.search(query).slice(0, 8) : [];

  useEffect(() => {
    const handler = (e: MouseEvent) => {
      if (wrapRef.current && !wrapRef.current.contains(e.target as Node)) {
        setIsOpen(false);
      }
    };
    document.addEventListener("click", handler);
    return () => document.removeEventListener("click", handler);
  }, []);

  return (
    <div ref={wrapRef} style={{ position: "relative", marginBottom: "24px" }}>
      <div style={{ position: "relative" }}>
        <svg
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          strokeWidth="2"
          style={{
            position: "absolute",
            left: "14px",
            top: "50%",
            transform: "translateY(-50%)",
            color: "var(--text3)",
            width: "20px",
            height: "20px",
          }}
        >
          <circle cx="11" cy="11" r="8" />
          <path d="M21 21l-4.35-4.35" />
        </svg>
        <input
          type="text"
          value={query}
          onChange={(e) => {
            setQuery(e.target.value);
            setIsOpen(true);
          }}
          onFocus={() => setIsOpen(true)}
          placeholder="Search for a product..."
          style={{
            width: "100%",
            padding: "14px 16px 14px 44px",
            background: "var(--surface)",
            border: "1.5px solid var(--border)",
            borderRadius: "var(--radius)",
            fontSize: "1rem",
            color: "var(--text)",
            outline: "none",
          }}
        />
      </div>
      {isOpen && results.length > 0 && (
        <div
          style={{
            position: "absolute",
            top: "100%",
            left: 0,
            right: 0,
            background: "var(--surface)",
            border: "1px solid var(--border)",
            borderRadius: "var(--radius-sm)",
            marginTop: "4px",
            maxHeight: "300px",
            overflowY: "auto",
            zIndex: 100,
          }}
        >
          {results.map((r) => (
            <a
              key={r.item.id}
              href={`${basePath}product/${r.item.id}/`}
              style={{
                display: "flex",
                justifyContent: "space-between",
                alignItems: "center",
                padding: "10px 16px",
                fontSize: "0.9rem",
                borderBottom: "1px solid var(--border)",
                color: "var(--text)",
                textDecoration: "none",
              }}
              onMouseEnter={(e) => {
                (e.currentTarget as HTMLElement).style.background =
                  "var(--surface2)";
              }}
              onMouseLeave={(e) => {
                (e.currentTarget as HTMLElement).style.background = "transparent";
              }}
            >
              <span>{r.item.name}</span>
              <span style={{ color: "var(--text3)", fontSize: "0.75rem" }}>
                {r.item.category}
              </span>
            </a>
          ))}
        </div>
      )}
      {isOpen && query.length >= 2 && results.length === 0 && (
        <div
          style={{
            position: "absolute",
            top: "100%",
            left: 0,
            right: 0,
            background: "var(--surface)",
            border: "1px solid var(--border)",
            borderRadius: "var(--radius-sm)",
            marginTop: "4px",
            padding: "10px 16px",
            color: "var(--text3)",
            fontSize: "0.9rem",
          }}
        >
          No products found
        </div>
      )}
    </div>
  );
}
