defmodule WishWeb.ItemLive.Show do
  use WishWeb, :live_view

  alias Wish.Wishlist

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

  @impl true
  def handle_params(%{"id" => id}, _, socket) do
    item = Wishlist.get_item!(id)
    changeset = Wishlist.change_item(item)

    {:noreply,
     socket
     |> assign(:page_title, page_title(socket.assigns.live_action))
     |> assign(:item, item)
     |> assign_form(changeset)}
  end

  defp page_title(:show), do: "Show Item"
  defp page_title(:edit), do: "Edit Item"

  @impl true
  def handle_event("validate", %{"item" => item_params}, socket) do
    changeset =
      socket.assigns.item
      |> Wishlist.change_item(item_params)
      |> Map.put(:action, :validate)

    {:noreply, assign_form(socket, changeset)}
  end

  def handle_event("save", %{"item" => item_params}, socket) do
    save_item(socket, socket.assigns.live_action, item_params)
  end

  defp save_item(socket, :edit, item_params) do
    case Wishlist.update_item(socket.assigns.item, item_params) do
      {:ok, item} ->
        changeset = Wishlist.change_item(item)

        {:noreply,
         socket
         |> assign(:item, item)
         |> assign_form(changeset)
         |> put_flash(:info, "Item updated successfully")}

      {:error, %Ecto.Changeset{} = changeset} ->
        {:noreply, assign_form(socket, changeset)}
    end
  end

  defp save_item(socket, :new, item_params) do
    case Wishlist.create_item(item_params) do
      {:ok, item} ->
        {:noreply,
         socket
         |> assign(:item, item)
         |> put_flash(:info, "Item created successfully")}

      {:error, %Ecto.Changeset{} = changeset} ->
        {:noreply, assign_form(socket, changeset)}
    end
  end

  defp assign_form(socket, %Ecto.Changeset{} = changeset) do
    assign(socket, :form, to_form(changeset))
  end
end
