defmodule AppWeb.TypeaheadLive do
  use AppWeb, :live_view

  @impl true
  def mount(_params, _session, socket) do
    {:ok, assign(socket, selected_product: nil)}
  end

  @impl true
  def handle_params(params, _, socket) do
    {:noreply, apply_action(socket, socket.assigns.live_action, params)}
  end

  @impl true
  def handle_info({:search_product, value}, socket) do
    products =
      App.Inventory.search_product(value)
      |> Enum.map(fn product ->
        %{product | name: AppWeb.HighlightHelper.highlight(value, product.name)}
      end)

    send_update(AppWeb.TypeaheadLiveComponent,
      id: "search_product_typeahead",
      items: products
    )

    {:noreply, socket}
  end

  @impl true
  def handle_info({:product_selected, id}, socket) do
    selected_product = App.Inventory.get_product(id)

    socket = assign(socket, selected_product: selected_product)

    {:noreply, push_patch(socket, to: ~p"/typeahead")}
  end

  defp apply_action(socket, :index, _params) do
    assign(socket, :page_title, gettext("Inventory"))
  end

  defp apply_action(socket, :search, _params) do
    assign(socket, :page_title, gettext("Search Product"))
  end

  @impl true
  def render(assigns) do
    ~H"""
    <div class="space-y-8">
      <div class="font-semibold">
        Typeahead
      </div>

      <div class="flex justify-between items-center border-b dark:border-zinc-700 py-2">
        <div>
          Click on the "Search product" button to see how the component works
        </div>

        <div>
          <.button phx-click={JS.navigate(~p"/typeahead/search")}>
            {gettext("Search product")}
          </.button>
        </div>
      </div>

      <div :if={@selected_product} class="rounded border dark:border-zinc-700 p-2">
        {@selected_product.name} <span class="font-semibold">${@selected_product.price}</span>
      </div>
    </div>

    <.modal
      :if={@live_action == :search}
      id="search-product-modal"
      on_cancel={JS.patch(~p"/typeahead")}
      show
    >
      <.live_component
        module={AppWeb.TypeaheadLiveComponent}
        id="search_product_typeahead"
        title={gettext("Search Product")}
        subtitle={gettext("Type a product name, for example \"Laptop\" to see search results")}
        placeholder={gettext("Write a product...")}
        on_search={:search_product}
        on_select={:product_selected}
      >
        <:item :let={product}>
          <div class="flex justify-between px-2">
            <div>
              {product.name}
            </div>

            <div>
              ${product.price}
            </div>
          </div>
        </:item>
      </.live_component>
    </.modal>
    """
  end
end
