defmodule DerivantesWeb.UserRegistrationLive do
  use DerivantesWeb, :live_view

  alias Derivantes.Accounts
  alias Derivantes.Accounts.User

  def render(assigns) do
    ~H"""
    <div class="register_screen">
      <.header class="text-center mb-5 mt-5 text-xl">
        Registre su nueva cuenta
        <:subtitle>
          ¿Ya tiene una cuenta?
          <.link navigate={~p"/derivantes/log_in"} class="font-semibold text-[#297177] hover:underline">
            Ingrese
          </.link>
          ahora.
        </:subtitle>
      </.header>

      <.simple_form
        for={@form}
        id="registration_form"
        phx-submit="save"
        phx-change="validate"
        phx-trigger-action={@trigger_submit}
        action={~p"/derivantes/log_in?_action=registered"}
        method="post"
        class="reg_form"
      >
        <.error :if={@check_errors}>
          Hubo un error.
        </.error>
        <img src={~p"/images/sana_americano_logo.png"} alt="Sanatorio Americano Logo" style="margin-top: 30px; margin-bottom: 20px;"/>
        <.input class="imput_text w-40" field={@form[:matricula]} type="text" placeholder="Matrícula" required />
        <.input class="imput_text w-40" field={@form[:email]} type="email" placeholder="Email" required />
        <.input class="imput_text w-40" field={@form[:password]} type="password" placeholder="Contraseña" required />

        <:actions>
          <.button phx-disable-with="Creando cuenta..." class="submit_button" style="margin-top: 20px; margin-bottom: 25px;">Crear cuenta</.button>
        </:actions>
      </.simple_form>
    </div>
    """
  end

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

    socket =
      socket
      |> assign(trigger_submit: false, check_errors: false)
      |> assign_form(changeset)

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

  def handle_event("save", %{"user" => user_params}, socket) do
    case Accounts.register_user(user_params) do
      {:ok, user} ->
        {:ok, _} =
          Accounts.deliver_user_confirmation_instructions(
            user,
            &url(~p"/derivantes/confirm/#{&1}")
          )

        changeset = Accounts.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
    changeset = Accounts.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
