import { type FormEvent, useEffect, useRef, useState } from "react";
import { useNavigate } from "react-router";
import { t } from "@lingui/core/macro";

interface SearchBarProps {
  collapsible?: boolean;
}

export function SearchBar({ collapsible = false }: SearchBarProps) {
  const [value, setValue] = useState(
    () => new URLSearchParams(location.search).get("q") ?? "",
  );
  const [expanded, setExpanded] = useState(!collapsible);
  const inputRef = useRef<HTMLInputElement>(null);
  const navigate = useNavigate();

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

  function handleIconClick() {
    if (!collapsible) return;
    if (expanded) {
      setExpanded(false);
      setValue("");
    } else {
      setExpanded(true);
    }
  }

  function handleSubmit(e: FormEvent) {
    e.preventDefault();
    const q = value.trim();
    if (!q) return;
    navigate(`/search?q=${encodeURIComponent(q)}&tab=dumps`);
    if (collapsible) {
      setExpanded(false);
      setValue("");
    }
  }

  function handleKeyDown(e: React.KeyboardEvent) {
    if (e.key === "Escape" && collapsible) {
      setExpanded(false);
      setValue("");
    }
  }

  return (
    <form
      className={`search-bar${collapsible ? " search-bar--collapsible" : ""}${
        expanded ? " search-bar--expanded" : ""
      }`}
      onSubmit={handleSubmit}
      role="search"
    >
      <input
        ref={inputRef}
        type="search"
        className="search-bar-input"
        placeholder={t`Search dumps, users, playlists…`}
        value={value}
        onChange={(e) => setValue(e.target.value)}
        onKeyDown={handleKeyDown}
        aria-label={t`Search`}
        tabIndex={expanded ? 0 : -1}
      />
      <button
        type={expanded && !collapsible ? "submit" : "button"}
        className="search-bar-btn"
        aria-label={expanded ? t`Submit search` : t`Open search`}
        onClick={collapsible ? handleIconClick : undefined}
      >
        🔍
      </button>
    </form>
  );
}
