import {
  ChangeDetectionStrategy,
  Component,
  inject,
  linkedSignal,
  model,
} from '@angular/core';
import { FilterService, SearchTrigger } from '@isa/shared/filter';
import { ButtonComponent, IconButtonComponent } from '@isa/ui/buttons';
import { EmptyStateComponent } from '@isa/ui/empty-state';
import { createRewardCatalogResource } from '../resources';
import { RewardListItemComponent } from './reward-list-item/reward-list-item.component';
import { InViewportDirective } from '@isa/ui/layout';
import { RewardCatalogStore } from '@isa/checkout/data-access';
import { ScrollTopButtonComponent } from '@isa/utils/scroll-position';

@Component({
  selector: 'reward-list',
  templateUrl: './reward-list.component.html',
  styleUrl: './reward-list.component.css',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [
    ButtonComponent,
    IconButtonComponent,
    EmptyStateComponent,
    RewardListItemComponent,
    InViewportDirective,
    ScrollTopButtonComponent,
  ],
  host: {
    '[class]': '"w-full flex flex-col gap-4"',
  },
})
export class RewardListComponent {
  searchTrigger = model<SearchTrigger | 'reload' | 'initial'>('initial');

  /**
   * FilterService instance for managing filter state and queries.
   * @private
   */
  #filterService = inject(FilterService);

  /**
   * RewardCatalogStore instance for managing reward catalog state.
   * @private
   */
  #rewardCatalogStore = inject(RewardCatalogStore);

  /**
   * Resource for fetching and managing the reward catalog data.
   * Uses the FilterService to get the current query token and reacts to search triggers.
   * @private
   * @returns The reward catalog resource.
   */
  rewardCatalogResource = createRewardCatalogResource(() => {
    return {
      queryToken: this.#filterService.query(),
      searchTrigger: this.searchTrigger(),
    };
  });

  /**
   * LinkedSignal indicating whether the reward catalog resource is currently fetching data.
   * @returns True if fetching, false otherwise.
   */
  listFetching = linkedSignal(
    () => this.rewardCatalogResource.status() === 'loading',
  );

  items = linkedSignal(() => this.#rewardCatalogStore.items());

  itemsLength = linkedSignal(() => this.items().length);

  hits = linkedSignal(() => this.#rewardCatalogStore.hits());

  renderSearchLoader = linkedSignal(() => {
    return this.listFetching() && this.itemsLength() === 0;
  });

  renderPageTrigger = linkedSignal(() => {
    if (this.listFetching()) return false;
    return this.hits() > this.itemsLength();
  });

  paging(inViewport: boolean) {
    if (!inViewport) {
      return;
    }

    if (this.itemsLength() !== this.hits()) {
      this.#reload();
    }
  }

  resetFilter() {
    this.#filterService.reset({ commit: true });
  }

  #reload() {
    this.searchTrigger.set('reload');
    this.rewardCatalogResource.reload();
  }
}
