defmodule LaxWeb.UserRegistrationLive do
  use LaxWeb, {:live_view, layout: :chat}
  use LaxNative, :live_view

  alias Lax.Users
  alias Lax.Users.User

  def render(assigns) do
    ~H"""
    <div class="mx-auto max-w-sm py-32">
      <.header class="text-center">
        Register for an account
        <:subtitle>
          Already registered?
          <.link navigate={~p"/users/sign-in"} class="font-semibold text-brand hover:underline">
            Sign in
          </.link>
          to your account now.
        </:subtitle>
      </.header>

      <.simple_form
        for={@form}
        id="registration_form"
        phx-submit="save"
        phx-change="validate"
        phx-trigger-action={@trigger_submit}
        action={~p"/users/sign-in?_action=registered"}
        method="post"
      >
        <.error :if={@check_errors}>
          Oops, something went wrong! Please check the errors below.
        </.error>

        <.input field={@form[:email]} type="email" label="Email" required />
        <.input field={@form[:username]} label="Username" required />
        <.input field={@form[:password]} type="password" label="Password" required />

        <.input
          field={@form[:terms_of_service]}
          type="checkbox"
          label={
            ~H|<span>I agree to the <.link href="https://github.com/jtormey/lax/blob/main/native/swiftui/TERMS.md" target="_blank" class="underline">Terms of Service</.link></span>|
          }
          required
        />

        <input
          type="hidden"
          id={@form[:time_zone].id}
          name={@form[:time_zone].name}
          phx-hook="SetTimeZoneValue"
          phx-update="ignore"
        />

        <:actions>
          <.button phx-disable-with="Creating account..." class="w-full">Create an account</.button>
        </:actions>
      </.simple_form>
    </div>
    """
  end

  def mount(_params, _session, socket) do
    changeset = Users.change_user_registration(%User{})

    socket =
      socket
      |> assign(:domain, :user)
      |> assign(trigger_submit: false, check_errors: false)
      |> assign_form(changeset)
      # SwiftUI
      |> assign(:user_params, %{})

    {:ok, socket, temporary_assigns: [form: nil]}
  end

  def handle_event("save", %{"user" => user_params}, socket) do
    # SwiftUI
    socket = update(socket, :user_params, &Map.merge(&1, user_params))
    user_params = socket.assigns.user_params
    # /SwiftUI

    case Users.register_user(user_params) do
      {:ok, user} ->
        {:ok, _} =
          Users.deliver_user_confirmation_instructions(
            user,
            &url(~p"/users/confirm/#{&1}")
          )

        changeset = Users.change_user_registration(user)
        {:noreply, socket |> assign(trigger_submit: true) |> assign_form(changeset)}

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

  def handle_event("validate", %{"user" => user_params}, socket) do
    # SwiftUI
    socket = update(socket, :user_params, &Map.merge(&1, user_params))
    user_params = socket.assigns.user_params
    # /SwiftUI

    changeset = Users.change_user_registration(%User{}, user_params)
    {:noreply, assign_form(socket, Map.put(changeset, :action, :validate))}
  end

  defp assign_form(socket, %Ecto.Changeset{} = changeset) do
    form = to_form(changeset, as: "user")

    if changeset.valid? do
      assign(socket, form: form, check_errors: false)
    else
      assign(socket, form: form)
    end
  end
end
