defmodule CakeWeb.LayoutLive.FormComponent do
  use CakeWeb, :live_component

  alias Cake.Layouts

  @impl true
  def update(%{layout: layout} = assigns, socket) do
    changeset = Layouts.change_layout(layout)

    {:ok,
     socket
     |> assign(assigns)
     |> assign(:changeset, changeset)}
  end

  @impl true
  def handle_event("validate", %{"layout" => layout_params}, socket) do
    changeset =
      socket.assigns.layout
      |> Layouts.change_layout(layout_params)
      |> Map.put(:action, :validate)

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

  def handle_event("save", %{"layout" => layout_params}, socket) do
    save_layout(socket, socket.assigns.action, layout_params)
  end

  defp save_layout(socket, :edit, layout_params) do
    case Layouts.update_layout(socket.assigns.layout, layout_params) do
      {:ok, _layout} ->
        {:noreply,
         socket
         |> put_flash(:info, "Layout updated successfully")
         |> push_redirect(to: socket.assigns.return_to)}

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

  defp save_layout(socket, :new, layout_params) do
    case Layouts.create_layout(layout_params) do
      {:ok, _layout} ->
        {:noreply,
         socket
         |> put_flash(:info, "Layout created successfully")
         |> push_redirect(to: socket.assigns.return_to)}

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