defmodule MvWeb.TableComponents do
  @moduledoc """
  TableComponents that can be used in tables as components (like a button for sorting, a filter...)
  """
  use Phoenix.Component
  import MvWeb.CoreComponents
  use Gettext, backend: MvWeb.Gettext

  attr :field, :atom, required: true
  attr :label, :string, required: true
  attr :sort_field, :atom, default: nil
  attr :sort_order, :atom, default: nil

  @doc """
  A sort button (with chevron icon) that can be used to sort a list of items
  """
  def sort_button(assigns) do
    ~H"""
    <button
      type="button"
      phx-click="sort"
      phx-value-field={@field}
      class="flex items-center gap-1 hover:underline focus:outline-none"
    >
      <span>{@label}</span>
      <%= if @sort_field == @field do %>
        <.icon name={if @sort_order == :asc, do: "hero-chevron-up", else: "hero-chevron-down"} />
        <span class="sr-only">
          ({(@sort_order == :asc && gettext("ascending")) || gettext("descending")})
        </span>
      <% end %>
    </button>
    """
  end
end
