import { ChangeDetectionStrategy, Component, computed, input } from '@angular/core';
import { HlmIconImports } from '@spartan-ng/helm/icon';
import { HlmTooltipImports } from '@spartan-ng/helm/tooltip';

/**
 * Compact cell for a TanStack table column that represents a small collection
 * of relations (tenants, tags, scopes, etc.) as: icon + count badge + tooltip
 * with the joined names.
 *
 * The icon names are resolved against `provideIcons()` registered upstream
 * (typically by the list component that uses this cell via `flexRenderComponent`).
 *
 * @example
 * // in account.columns.ts:
 * cell: (info) =>
 *   flexRenderComponent(HlmBadgeIconCell, {
 *     inputs: {
 *       items: info.getValue<IamTenant[]>() ?? [],
 *       label: (t: IamTenant) => t.name,
 *       iconName: 'lucideBuilding2',
 *     },
 *   })
 */
@Component({
  selector: 'au-hlm-badge-icon-cell',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [HlmIconImports, HlmTooltipImports],
  host: { class: 'inline-flex items-center' },
  template: `
    <span
      class="relative inline-flex items-center"
      [hlmTooltip]="tooltipText()"
      [tooltipDisabled]="!hasItems()"
    >
      <ng-icon
        class="text-foreground/70"
        [name]="iconName()"
        hlm
        size="sm"
      />
      @if (hasItems()) {
        <span
          aria-hidden="true"
          class="bg-primary text-primary-foreground absolute -top-1 -right-1.5 inline-flex h-3.5 min-w-[0.875rem] items-center justify-center rounded-full px-1 text-[0.625rem] leading-none font-semibold"
        >
          {{ items().length }}
        </span>
      }
    </span>
  `,
})
export class HlmBadgeIconCell<T = unknown> {
  readonly items = input<T[]>([]);
  readonly label = input<(item: T) => string>((item) => String(item));
  readonly iconName = input.required<string>();

  protected readonly hasItems = computed(() => this.items().length > 0);

  protected readonly tooltipText = computed(() => {
    const items = this.items();
    if (items.length === 0) return '';
    const labelFn = this.label();
    return items.map(labelFn).join(', ');
  });
}

export const HlmBadgeIconCellImports = [HlmBadgeIconCell] as const;
