defmodule PrymnWeb.AppIndexLive do
  use PrymnWeb, :live_view

  alias Prymn.Apps

  @impl true
  def mount(_, _, socket) do
    apps = Apps.list_apps()

    for %Apps.App{} = app <- apps do
      Phoenix.PubSub.subscribe(Prymn.PubSub, "app:#{app.id}")
    end

    {:ok, assign(socket, :apps, apps)}
  end

  @impl true
  def render(assigns) do
    ~H"""
    <%= cond do %>
      <% assigns.live_action == :new -> %>
        <.back navigate={~p"/apps"}>Go back</.back>
        <.live_component id={:new} module={PrymnWeb.CreateApp} app_type={assigns[:app_type]} />
      <% assigns.apps == [] -> %>
        <.onboarding />
      <% true -> %>
        <div class="mx-auto max-w-2xl">
          <.header>
            Live Apps
            <:subtitle>
              All of your apps accross all projects.
            </:subtitle>
            <:actions>
              <Button.primary patch={~p"/apps/new"}>Create app</Button.primary>
            </:actions>
          </.header>
          <div :for={app <- @apps} class="mt-5 bg-violet-100 p-5">
            <p>App: <%= app.name %></p>
            <p>Server: <%= app.server.name %></p>
          </div>
        </div>
    <% end %>
    """
  end

  @impl true
  def handle_info(msg, socket) do
    dbg(msg, label: "Incoming message from pubsub")
    {:noreply, socket}
  end

  @impl true
  def handle_params(%{"app_type" => app_type}, _, socket) do
    {:noreply, assign(socket, app_type: app_type)}
  end

  def handle_params(_, _, socket) do
    {:noreply,
     socket
     |> assign(:page_title, (socket.assigns.live_action == :new && "New App") || "Apps")}
  end

  defp onboarding(assigns) do
    ~H"""
    <div class="grid h-screen items-center">
      <div class="pb-64 text-center">
        <h1 class="text-3xl font-medium">You have no Apps.</h1>
        <h2 class="text-xl">Create your first App here!</h2>
        <Button.primary class="mt-10" size="lg" patch={~p"/apps/new"}>
          Create a new App
        </Button.primary>
      </div>
    </div>
    """
  end
end