import { useState, useRef, useEffect } from "react";
import { Search, X, Package, Loader2 } from "lucide-react";
import { cn } from "../../lib/utils";
import { get } from "../../lib/api";
import { RARITY_BADGE, inputCls } from "./ItemStudioTypes";

// ===== Item Search Picker =====

interface ItemResult {
  id: number;
  name: string;
  rarity: string;
  iconUrl: string;
}

export function ItemSearchPicker({
  value,
  onChange,
}: {
  value: { id: number; name: string; rarity: string } | null;
  onChange: (item: { id: number; name: string; rarity: string } | null) => void;
}) {
  const [query, setQuery] = useState("");
  const [results, setResults] = useState<ItemResult[]>([]);
  const [loading, setLoading] = useState(false);
  const [open, setOpen] = useState(false);
  const containerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!query.trim()) {
      setResults([]);
      setOpen(false);
      return;
    }
    const t = setTimeout(async () => {
      setLoading(true);
      try {
        const data = await get<{ items: ItemResult[] }>(
          `/api/items?search=${encodeURIComponent(query)}&limit=8`
        );
        setResults(data.items);
        setOpen(data.items.length > 0);
      } catch {
        // silently fail -- network error shouldn't break the form
      } finally {
        setLoading(false);
      }
    }, 300);
    return () => clearTimeout(t);
  }, [query]);

  useEffect(() => {
    function onOutsideClick(e: MouseEvent) {
      if (
        containerRef.current &&
        !containerRef.current.contains(e.target as Node)
      ) {
        setOpen(false);
      }
    }
    document.addEventListener("mousedown", onOutsideClick);
    return () => document.removeEventListener("mousedown", onOutsideClick);
  }, []);

  if (value) {
    return (
      <div className="flex items-center gap-2 p-2 bg-raised/50 rounded-md border border-border">
        <span
          className={cn(
            "text-xs px-1.5 py-0.5 rounded font-bold shrink-0",
            RARITY_BADGE[value.rarity] ?? "bg-gray-500/20 text-gray-400"
          )}
        >
          {value.rarity}
        </span>
        <span className="text-sm flex-1 text-foreground truncate">
          {value.name}
        </span>
        <span className="text-xs text-text-tertiary font-mono shrink-0">
          #{value.id}
        </span>
        <button
          onClick={() => onChange(null)}
          className="p-0.5 text-text-tertiary hover:text-destructive transition-colors shrink-0"
        >
          <X className="w-3.5 h-3.5" />
        </button>
      </div>
    );
  }

  return (
    <div className="relative" ref={containerRef}>
      <div className="relative">
        <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-text-tertiary pointer-events-none" />
        <input
          type="text"
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          placeholder="Search items by name..."
          className={cn(inputCls, "pl-9 pr-9")}
        />
        {loading && (
          <Loader2 className="absolute right-3 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-text-tertiary animate-spin pointer-events-none" />
        )}
      </div>
      {open && results.length > 0 && (
        <div className="absolute top-full left-0 right-0 z-50 mt-1 bg-card border border-border rounded-lg shadow-xl overflow-hidden">
          {results.map((item) => (
            <button
              key={item.id}
              onMouseDown={(e) => e.preventDefault()}
              onClick={() => {
                onChange({ id: item.id, name: item.name, rarity: item.rarity });
                setQuery("");
                setOpen(false);
              }}
              className="w-full flex items-center gap-2.5 px-3 py-2 hover:bg-raised text-left transition-colors"
            >
              {item.iconUrl ? (
                <img
                  src={item.iconUrl}
                  alt=""
                  className="w-6 h-6 rounded object-cover bg-raised shrink-0"
                  onError={(e) => {
                    e.currentTarget.style.display = "none";
                  }}
                />
              ) : (
                <Package className="w-6 h-6 text-text-tertiary shrink-0" />
              )}
              <span className="text-sm text-foreground flex-1 truncate">
                {item.name}
              </span>
              <span
                className={cn(
                  "text-xs px-1.5 py-0.5 rounded font-bold shrink-0",
                  RARITY_BADGE[item.rarity] ?? "bg-gray-500/20 text-gray-400"
                )}
              >
                {item.rarity}
              </span>
              <span className="text-xs text-text-tertiary font-mono shrink-0">
                #{item.id}
              </span>
            </button>
          ))}
        </div>
      )}
    </div>
  );
}
