import { ChangeDetectionStrategy, Component, input } from '@angular/core';
import { NgIcon, provideIcons } from '@ng-icons/core';
import { lucideArrowDown, lucideArrowUp, lucideArrowUpDown } from '@ng-icons/lucide';
import { HlmButtonImports } from '@spartan-ng/helm/button';
import { HlmIconImports } from '@spartan-ng/helm/icon';
import { type HeaderContext, injectFlexRenderContext } from '@tanstack/angular-table';

@Component({
  selector: 'au-sort-button',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [HlmButtonImports, HlmIconImports, NgIcon],
  providers: [provideIcons({ lucideArrowUpDown, lucideArrowUp, lucideArrowDown })],
  host: { class: 'flex' },
  template: `
    <button
      class="w-full !justify-start px-0"
      hlmBtn
      variant="ghost"
      size="sm"
      (click)="toggleSort()"
    >
      {{ label() }}
      <ng-icon
        class="ml-1"
        [name]="sortIcon()"
        hlm
        size="xs"
      />
    </button>
  `,
})
export class SortButton {
  readonly label = input.required<string>();
  private readonly context = injectFlexRenderContext<HeaderContext<unknown, unknown>>();
  protected readonly sortIcon = () => {
    const sort = this.context.column.getIsSorted();
    if (sort === 'asc') return 'lucideArrowUp';
    if (sort === 'desc') return 'lucideArrowDown';
    return 'lucideArrowUpDown';
  };

  toggleSort() {
    this.context.column.toggleSorting();
  }
}
