defmodule Web.AdminDashboardLive do
  use Web, :live_view

  def mount(_params, _session, socket) do
    statuses = Core.Posts.get_all_recent_statuses()
    blogs = Core.Posts.get_all_recent_blogs()

    socket =
      socket
      |> stream(:statuses, statuses)
      |> stream(:blogs, blogs)

    {:ok, socket}
  end

  def render(assigns) do
    ~H"""
    <div class="flex flex-col gap-y-4">
      <h1 class="font-bold text-2xl">dashboard</h1>

      <section>
        <header class="flex flex-row justify-between">
          <h2 class="font-bold text-xl">recent statuses</h2>
          <.link navigate={~p"/admin/posts/new?kind=status"}>new status</.link>
        </header>
        <.post_list :let={status} id="recent-statuses" stream={@streams.statuses}>
          <.link navigate={~p"/admin/posts/#{status}"}>{status.body}</.link>
        </.post_list>
      </section>

      <section>
        <header class="flex flex-row justify-between">
          <h2 class="font-bold text-xl">recent blogs</h2>
          <.link navigate={~p"/admin/posts/new?kind=blog"}>new blog</.link>
        </header>
        <.post_list :let={blog} id="recent-blogs" stream={@streams.blogs}>
          <.link navigate={~p"/admin/posts/#{blog}"}>{blog.title}</.link>
        </.post_list>
      </section>
    </div>
    """
  end

  attr :id, :string, required: true
  attr :stream, :any, required: true

  slot :inner_block, required: true

  def post_list(assigns) do
    ~H"""
    <ol id={@id} phx-update="stream">
      <li :for={{dom_id, item} <- @stream} id={dom_id}>
        {render_slot(@inner_block, item)}
      </li>
    </ol>
    """
  end
end