defmodule ZoeyscomputerWeb.ApiKeyLive.FormComponent do
  use ZoeyscomputerWeb, :live_component

  alias Zoeyscomputer.ApiKeys

  @impl true
  def render(assigns) do
    ~H"""
    <div>
      <.header>
        <%= @title %>
        <:subtitle>Create an API key to access the API</:subtitle>
      </.header>

      <.simple_form
        for={@form}
        id="api-key-form"
        phx-target={@myself}
        phx-change="validate"
        phx-submit="save"
      >
        <.input field={@form[:name]} type="text" label="Name" />
        <:actions>
          <.button phx-disable-with="Saving...">Save Api key</.button>
        </:actions>
      </.simple_form>
    </div>
    """
  end

  @impl true
  def update(%{api_key: api_key} = assigns, socket) do
    changeset = ApiKeys.change_api_key(api_key)

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

  @impl true
  def handle_event("validate", %{"api_key" => api_key_params}, socket) do
    changeset =
      socket.assigns.api_key
      |> ApiKeys.change_api_key(api_key_params)
      |> Map.put(:action, :validate)

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

  def handle_event("save", %{"api_key" => api_key_params}, socket) do
    case ApiKeys.create_api_key(socket.assigns.current_user, api_key_params) do
      {:ok, api_key} ->
        notify_parent({:saved, api_key})

        {:noreply,
         socket
         |> put_flash(:info, "API key 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

  defp notify_parent(msg), do: send(self(), {__MODULE__, msg})
end
