defmodule DerivantesWeb.UserForgotPasswordLive do
  use DerivantesWeb, :live_view

  alias Derivantes.Accounts

  def render(assigns) do
    ~H"""
    <div class="mx-auto max-w-sm pw_forgot">
      <.header_SA class="text-center text-white">
      <img src={~p"/images/sana_americano_logo.png"} alt="Sanatorio Americano Logo"/>
      <br>
        ¿Olvidó su contraseña?
        <:subtitle>Le enviaremos un link para reestablecerla.</:subtitle>
      </.header_SA>

      <.simple_form for={@form} id="reset_password_form" phx-submit="send_email">
        <.input field={@form[:email]} type="email" placeholder="Email" required />
        <br>
        <:actions>
          <.button phx-disable-with="Enviando..." class="w-full background-color-[#297177]">
            Enviar instrucciones de reestablecimiento de contraseña
          </.button>
        </:actions>
      </.simple_form>
      <p class="text-center text-sm mt-4">
        <.link href={~p"/derivantes/register"}>Registrarse</.link>
        | <.link href={~p"/derivantes/log_in"}>Ingresar</.link>
      </p>
    </div>
    """
  end

  def mount(_params, _session, socket) do
    {:ok, assign(socket, form: to_form(%{}, as: "user"))}
  end

  def handle_event("send_email", %{"user" => %{"email" => email}}, socket) do
    if user = Accounts.get_user_by_email(email) do
      Accounts.deliver_user_reset_password_instructions(
        user,
        &url(~p"/derivantes/reset_password/#{&1}")
      )
    end

    info =
      "Su su email está en nuestro sistema, recibirá instrucciones para reestablecer su contraseña en unos minutos"

    {:noreply,
     socket
     |> put_flash(:info, info)
     |> redirect(to: ~p"/")}
  end
end
