import { type ReactNode } from "react";
import { useTranslation } from "react-i18next";
import { Search, X } from "lucide-react";

// The floating search pill in the top header. One component for every module that searches
// (feed, Plex, channels, playlists): a glass rounded box with a search icon, the input, a
// clear button, and a "Go" trigger (Enter also fires it). The feed passes its live-YouTube
// escalation as the Go action; the other modules filter as you type and Go just commits/blurs.
export default function SearchBar({
  value,
  onChange,
  placeholder,
  onGo,
  goLabel,
  goIcon,
  goDisabled,
  goTitle,
}: {
  value: string;
  onChange: (q: string) => void;
  placeholder: string;
  // Enter / the Go button call this. Omit to hide the Go button entirely.
  onGo?: () => void;
  goLabel?: string;
  goIcon?: ReactNode;
  goDisabled?: boolean;
  goTitle?: string;
}) {
  const { t } = useTranslation();
  const fire = () => {
    if (onGo && !goDisabled) onGo();
  };
  return (
    <div className="pointer-events-auto flex-1 min-w-0 max-w-xl h-11 pl-3 pr-2 rounded-2xl glass-menu flex items-center gap-2">
      <Search className="w-4 h-4 shrink-0 text-muted" />
      <input
        value={value}
        onChange={(e) => onChange(e.target.value)}
        onKeyDown={(e) => {
          if (e.key === "Enter") fire();
        }}
        placeholder={placeholder}
        className="flex-1 min-w-0 bg-transparent outline-none text-sm placeholder:text-muted"
      />
      {value && (
        <button
          onClick={() => onChange("")}
          title={t("header.clearSearch")}
          aria-label={t("header.clearSearch")}
          className="shrink-0 p-0.5 rounded-full text-muted transition hover:text-fg hover:bg-border/60"
        >
          <X className="w-4 h-4" />
        </button>
      )}
      {onGo && (
        <button
          onClick={fire}
          disabled={goDisabled}
          title={goTitle ?? goLabel ?? t("header.goTip")}
          className="shrink-0 inline-flex items-center gap-1.5 rounded-xl bg-accent px-3 py-1.5 text-xs font-semibold text-accent-fg transition hover:opacity-90 disabled:opacity-40 disabled:pointer-events-none"
        >
          {goIcon}
          <span className={goIcon ? "hidden md:inline" : undefined}>
            {goLabel ?? t("header.go")}
          </span>
        </button>
      )}
    </div>
  );
}
