import {
  ChangeDetectionStrategy,
  Component,
  computed,
  inject,
  OnInit,
  OnDestroy,
} from '@angular/core';
import { OpenRewardTasksResource } from '@isa/oms/data-access';
import { CarouselComponent } from '@isa/ui/carousel';
import { OpenTaskCardComponent } from './open-task-card.component';

/**
 * Carousel component displaying open reward distribution tasks (Prämienausgabe).
 *
 * Shows a horizontal scrollable list of unfinished reward orders at the top of the
 * reward catalog. Hidden when no open tasks exist.
 *
 * Features:
 * - Keyboard navigation (Arrow Left/Right)
 * - Automatic visibility based on task availability
 * - Shared global resource for consistent data across app
 * - Deduplicates tasks to show only one card per orderId
 */
@Component({
  selector: 'reward-catalog-open-tasks-carousel',
  standalone: true,
  imports: [CarouselComponent, OpenTaskCardComponent],
  template: `
    @if (openTasksResource.hasOpenTasks()) {
      <div class="mb-4" data-what="open-tasks-carousel">
        <ui-carousel [gap]="'1rem'" [arrowAutoHide]="true">
          @for (task of uniqueTasks(); track task.orderId) {
            <reward-catalog-open-task-card [task]="task" />
          }
        </ui-carousel>
      </div>
    }
  `,
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class OpenTasksCarouselComponent implements OnInit, OnDestroy {
  /**
   * Global resource managing open reward tasks data
   */
  readonly openTasksResource = inject(OpenRewardTasksResource);

  /**
   * Deduplicated tasks - shows only one task per orderId.
   * When multiple order items exist for the same order, only the first one is displayed.
   *
   * @returns Array of unique tasks filtered by orderId
   */
  readonly uniqueTasks = computed(() => {
    const tasks = this.openTasksResource.tasks();
    const seenOrderIds = new Set<number>();

    return tasks.filter((task) => {
      if (!task.orderId || seenOrderIds.has(task.orderId)) {
        return false;
      }
      seenOrderIds.add(task.orderId);
      return true;
    });
  });

  /**
   * Initializes the component by loading open tasks and starting auto-refresh.
   * Ensures the carousel displays current data when mounted.
   */
  ngOnInit(): void {
    this.openTasksResource.refresh();
    this.openTasksResource.startAutoRefresh();
  }

  /**
   * Cleanup lifecycle hook that stops auto-refresh polling.
   * Prevents memory leaks by clearing the refresh interval.
   */
  ngOnDestroy(): void {
    this.openTasksResource.stopAutoRefresh();
  }
}
