"use client";

import { useState, useEffect } from "react";
import { useTranslation } from "@/hooks/useTranslation";
import { useSearchParams } from "next/navigation";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import {
  searchContent,
  setQuery,
  clearSearch,
  selectSearchQuery,
  selectSearchType,
  selectSearchLoading,
  selectSearchTotal,
} from "@/store/slices/searchSlice";
import { getStoredUser } from "@/lib/utils/persistAuth";

export default function SearchHero() {
  const { t } = useTranslation("search");
  const dispatch = useAppDispatch();
  const searchParams = useSearchParams();

  const query   = useAppSelector(selectSearchQuery);
  const type    = useAppSelector(selectSearchType);
  const loading = useAppSelector(selectSearchLoading);
  const total   = useAppSelector(selectSearchTotal);

  const [localQuery, setLocalQuery] = useState(query || searchParams.get("q") || "");

  // Run search from URL ?q= param on first load
  useEffect(() => {
    const q = searchParams.get("q");
    if (q && q !== query) {
      setLocalQuery(q);
      dispatch(setQuery(q));
      dispatch(searchContent({ query: q, type, userId: getStoredUser()?.id ?? 0 }));
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  function doSearch(q: string) {
    const trimmed = q.trim();
    if (!trimmed) return;
    dispatch(setQuery(trimmed));
    dispatch(searchContent({ query: trimmed, type, userId: getStoredUser()?.id ?? 0 }));
  }

  function handleClear() {
    setLocalQuery("");
    dispatch(clearSearch());
  }

  return (
    <header className="search-hero">
      <div className="wrap">
        <div className="search-bigbox">
          <button
            aria-label="Search"
            onClick={() => doSearch(localQuery)}
            style={{ background: "none", border: "none", cursor: "pointer", padding: 0, display: "flex" }}
          >
            {loading ? (
              <svg viewBox="0 0 24 24" style={{ animation: "spin 0.8s linear infinite" }}>
                <circle cx="12" cy="12" r="9" fill="none" stroke="currentColor" strokeWidth="2.5" strokeDasharray="30 60" />
              </svg>
            ) : (
              <svg viewBox="0 0 24 24">
                <circle cx="11" cy="11" r="7" />
                <path d="m20 20-3-3" />
              </svg>
            )}
          </button>
          <input
            type="search"
            value={localQuery}
            onChange={(e) => setLocalQuery(e.target.value)}
            onKeyDown={(e) => e.key === "Enter" && doSearch(localQuery)}
            autoComplete="off"
            placeholder={t("placeholder")}
          />
          {localQuery && (
            <button className="clear" title={t("clear")} onClick={handleClear}>
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round">
                <path d="M6 6l12 12M18 6L6 18" />
              </svg>
            </button>
          )}
        </div>

        {query && !loading && (
          <p className="search-meta" style={{ marginTop: "0.75rem", fontSize: "0.875rem", color: "var(--text-secondary)" }}>
            {total > 0
              ? `${total.toLocaleString()} results for "${query}"`
              : `No results found for "${query}"`}
          </p>
        )}
      </div>
    </header>
  );
}
