defmodule OutlookWeb.DeeplAccountLive.FormComponent do
  use OutlookWeb, :live_component

  alias Outlook.Translators

  @impl true
  def render(assigns) do
    ~H"""
    <div>
      <.header>
        <%= @title %>
        <:subtitle>Use this form to manage deepl_account records in your database.</:subtitle>
      </.header>

      <.simple_form
        :let={f}
        for={@changeset}
        id="deepl_account-form"
        phx-target={@myself}
        phx-change="validate"
        phx-submit="save"
      >
        <.input field={{f, :user_id}} type="hidden" />
        <.input field={{f, :name}} type="text" label="name" />
        <.input field={{f, :description}} type="text" label="description" />
        <.input field={{f, :auth_key}} type="text" label="auth_key" />
        <.input field={{f, :character_limit}} type="number" label="character_limit" />
        <.input field={{f, :character_count}} type="number" label="character_count" />
        <.input field={{f, :our_character_count}} type="number" label="our_character_count" />
        <:actions>
          <.button phx-disable-with="Saving...">Save Deepl account</.button>
        </:actions>
      </.simple_form>
    </div>
    """
  end

  @impl true
  def update(%{deepl_account: deepl_account} = assigns, socket) do
    changeset = Translators.change_deepl_account(deepl_account)

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

  @impl true
  def handle_event("validate", %{"deepl_account" => deepl_account_params}, socket) do
    changeset =
      socket.assigns.deepl_account
      |> Translators.change_deepl_account(deepl_account_params)
      |> Map.put(:action, :validate)

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

  def handle_event("save", %{"deepl_account" => deepl_account_params}, socket) do
    save_deepl_account(socket, socket.assigns.action, deepl_account_params)
  end

  defp save_deepl_account(socket, :edit, deepl_account_params) do
    case Translators.update_deepl_account(socket.assigns.deepl_account, deepl_account_params) do
      {:ok, _deepl_account} ->
        {:noreply,
         socket
         |> put_flash(:info, "Deepl account updated successfully")
         |> push_navigate(to: socket.assigns.navigate)}

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

  defp save_deepl_account(socket, :new, deepl_account_params) do
    case Translators.create_deepl_account(deepl_account_params) do
      {:ok, _deepl_account} ->
        {:noreply,
         socket
         |> put_flash(:info, "Deepl account created successfully")
         |> push_navigate(to: socket.assigns.navigate)}

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