defmodule MvWeb.Components.SortHeaderComponent do
  @moduledoc """
  Sort Header that can be used as column header and sorts a table:
  Props:
    - field: atom()                     # Ash Field for sorting
    - label: string()                   # Column Heading (can be an heex template)
    - sort_field: atom() | nil             # current sort field from parent liveview
    - sort_order: :asc | :desc | nil      # current sorting order
  """
  use MvWeb, :live_component

  @impl true
  def update(assigns, socket) do
    {:ok, assign(socket, assigns)}
  end

  # Check if we can add the aria-sort label directly to the daisyUI header
  # aria-sort={aria_sort(@field, @sort_field, @sort_order)}
  @impl true
  def render(assigns) do
    ~H"""
    <div>
      <.tooltip content={aria_sort(@field, @sort_field, @sort_order)} position="bottom">
        <.button
          type="button"
          variant="ghost"
          aria-label={aria_sort(@field, @sort_field, @sort_order)}
          class="select-none"
          phx-click="sort"
          phx-value-field={@field}
          data-testid={@field}
        >
          {@label}
          <%= if @sort_field == @field do %>
            <.icon name={if @sort_order == :asc, do: "hero-chevron-up", else: "hero-chevron-down"} />
          <% else %>
            <.icon
              name="hero-chevron-up-down"
              class="opacity-40"
            />
          <% end %>
        </.button>
      </.tooltip>
    </div>
    """
  end

  # -------------------------------------------------
  # Hilfsfunktionen für ARIA Attribute & Icon SVG
  # -------------------------------------------------
  defp aria_sort(field, sort_field, dir) when field == sort_field do
    case dir do
      :asc -> gettext("ascending")
      :desc -> gettext("descending")
      nil -> gettext("Click to sort")
    end
  end

  defp aria_sort(_, _, _), do: gettext("Click to sort")
end
