import {
  ChangeDetectionStrategy,
  Component,
  computed,
  inject,
  input,
} from '@angular/core';
import { RouterLink } from '@angular/router';
import { DBHOrderItemListItemDTO } from '@generated/swagger/oms-api';
import { TabService } from '@isa/core/tabs';
import { IconButtonComponent } from '@isa/ui/buttons';
import { provideIcons } from '@ng-icons/core';
import { isaActionChevronRight } from '@isa/icons';

/**
 * Card component displaying a single open reward task (Prämienausgabe).
 *
 * Shows customer name and a chevron button for navigation to the order completion page.
 */

export type OpenTaskCardInput = Pick<
  DBHOrderItemListItemDTO,
  'orderId' | 'firstName' | 'lastName'
>;

@Component({
  selector: 'reward-catalog-open-task-card',
  standalone: true,
  imports: [IconButtonComponent, RouterLink],
  providers: [provideIcons({ isaActionChevronRight })],
  template: `
    <a
      class="bg-isa-white flex items-center justify-between px-[22px] py-[20px] rounded-2xl w-[334px] cursor-pointer no-underline"
      data-what="open-task-card"
      [attr.data-which]="task().orderId"
      [routerLink]="routePath()"
    >
      <div class="flex flex-col gap-1">
        <p class="isa-text-body-1-regular text-isa-neutral-900">
          Offene Prämienausgabe
        </p>
        <p class="isa-text-body-1-bold text-isa-neutral-900">
          {{ customerName() }}
        </p>
      </div>
      <ui-icon-button
        name="isaActionChevronRight"
        [color]="'secondary'"
        size="medium"
        data-what="open-task-card-button"
      />
    </a>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class OpenTaskCardComponent {
  readonly #tabService = inject(TabService);

  /**
   * The open task data to display
   */
  readonly task = input.required<OpenTaskCardInput>();

  /**
   * Computed customer name from first and last name
   */
  readonly customerName = (): string => {
    const t = this.task();
    const firstName = t.firstName || '';
    const lastName = t.lastName || '';
    return `${firstName} ${lastName}`.trim() || 'Unbekannt';
  };

  /**
   * Current tab ID for navigation
   */
  readonly #tabId = computed(
    () => this.#tabService.activatedTab()?.id ?? Date.now(),
  );

  /**
   * Route path to the reward order confirmation page.
   * Route: /:tabId/reward/order-confirmation/:orderId
   */
  readonly routePath = computed(() => {
    const orderId = this.task().orderId;
    if (!orderId) {
      console.warn('Missing orderId in task', this.task());
      return [];
    }
    return [
      '/',
      this.#tabId(),
      'reward',
      'order-confirmation',
      orderId.toString(),
    ];
  });
}
