defmodule WishWeb.HomeLive.Index do
  use WishWeb, :live_view

  alias Wish.Wishlist
  use Phoenix.Component

  @impl true
  def mount(_params, session, socket) do
    grid? =
      case Map.get(session, "user_display", "grid") do
        "grid" -> true
        _ -> false
      end

    items =
      if socket.assigns.current_user do
        Wishlist.list_visible_items()
      else
        Wishlist.list_available_items()
      end

    {:ok, assign(socket, :items, items) |> assign(:grid, grid?) |> assign(:hidden, false)}
  end

  @impl true
  def handle_event("toggle_view_state", _, socket) do
    {:noreply, assign(socket, :grid, !socket.assigns.grid)}
  end

  @impl true
  def handle_event("toggle_hidden_items", _, socket) do
    new_state = !socket.assigns.hidden

    items =
      if new_state do
        Wishlist.list_visible_items()
      else
        Wishlist.list_available_items()
      end

    {:noreply, assign(socket, :items, items) |> assign(:hidden, new_state)}
  end

  @impl true
  def handle_event("toggle_received", %{"id" => id}, socket) do
    item = Wishlist.get_item!(id)

    case Wishlist.toggle_received(item) do
      {:ok, updated_item} ->
        index = Enum.find_index(socket.assigns.items, &(&1.id == updated_item.id))
        updated_list = List.update_at(socket.assigns.items, index, fn _ -> updated_item end)
        {:noreply, assign(socket, :items, updated_list)}

      {:error, _} ->
        {:noreply, socket}
    end
  end

  attr :item, :any

  def dropdown(assigns) do
    ~H"""
    <div
      id={"dropdown-#{@item.id}"}
      class="absolute z-10 w-40 bg-purple-100 origin-top right-0 whitespace-nowrap border border-black"
      phx-click-away={JS.hide()}
      hidden
    >
      <.link href={@item.url} class="block p-2 w-full hover:bg-purple-300 select-none" target="_blank">
        Go to seller
      </.link>
      <div
        class="block p-2 w-full hover:bg-purple-300 select-none cursor-pointer"
        phx-click={
          JS.push("toggle_received", value: %{"id" => @item.id})
          |> JS.hide(to: "#dropdown-#{@item.id}")
        }
      >
        Mark as purchased
      </div>
    </div>
    """
  end
end
