defmodule BerrypodWeb.Shop.Search do
  use BerrypodWeb, :live_view

  alias Berrypod.{Pages, Search}

  @impl true
  def mount(_params, _session, socket) do
    page = Pages.get_page("search")
    {:ok, socket |> assign(:page_title, "Search") |> assign(:page, page)}
  end

  @impl true
  def handle_params(params, _uri, socket) do
    query = params["q"] || ""
    results = if query != "", do: Search.search(query), else: []

    {:noreply,
     socket
     |> assign(:search_page_query, query)
     |> assign(:search_page_results, results)}
  end

  @impl true
  def handle_event("search_submit", %{"q" => query}, socket) do
    {:noreply, push_patch(socket, to: ~p"/search?q=#{query}")}
  end

  @impl true
  def render(assigns) do
    ~H"""
    <BerrypodWeb.PageRenderer.render_page {assigns} />
    """
  end
end
