import {
  ChangeDetectionStrategy,
  Component,
  computed,
  inject,
  signal,
} from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import {
  provideFilter,
  withQuerySettingsFactory,
  withQueryParamsSync,
  FilterControlsPanelComponent,
  SearchTrigger,
  FilterService,
  FilterInput,
  SwitchMenuButtonComponent,
} from '@isa/shared/filter';
import { RewardHeaderComponent } from './reward-header/reward-header.component';
import { RewardListComponent } from './reward-list/reward-list.component';
import { injectRestoreScrollPosition } from '@isa/utils/scroll-position';
import { RewardActionComponent } from './reward-action/reward-action.component';
import { SelectedRewardShoppingCartResource } from '@isa/checkout/data-access';
import { SelectedBranchDropdownComponent } from '@isa/checkout/feature/select-branch-dropdown';
import { SelectedCustomerResource } from '@isa/crm/data-access';
import { OpenTasksCarouselComponent } from './open-tasks-carousel/open-tasks-carousel.component';
import { injectTabId } from '@isa/core/tabs';
import { Role, RoleService } from '@isa/core/auth';

/**
 * Factory function to retrieve query settings from the activated route data.
 * @returns The query settings from the activated route data.
 */
function querySettingsFactory() {
  return inject(ActivatedRoute).snapshot.data['querySettings'];
}

@Component({
  selector: 'reward-catalog',
  templateUrl: './reward-catalog.component.html',
  styleUrl: './reward-catalog.component.css',
  changeDetection: ChangeDetectionStrategy.OnPush,
  providers: [
    SelectedRewardShoppingCartResource,
    SelectedCustomerResource,
    provideFilter(
      withQuerySettingsFactory(querySettingsFactory),
      withQueryParamsSync(),
    ),
  ],
  imports: [
    FilterControlsPanelComponent,
    OpenTasksCarouselComponent,
    RewardHeaderComponent,
    RewardListComponent,
    RewardActionComponent,
    SelectedBranchDropdownComponent,
  ],
  host: {
    '[class]':
      '"w-full flex flex-col gap-4 mt-5 isa-desktop:mt-6 overflow-x-hidden"',
  },
})
export class RewardCatalogComponent {
  readonly tabId = injectTabId();

  readonly isCallCenter = inject(RoleService).hasRole(Role.CallCenter);

  restoreScrollPosition = injectRestoreScrollPosition();

  searchTrigger = signal<SearchTrigger | 'reload' | 'initial'>('initial');

  #filterService = inject(FilterService);

  displayStockFilterSwitch = computed(() => {
    const stockInput = this.#filterService
      .inputs()
      ?.filter((input) => input.target === 'filter')
      ?.find((input) => input.key === 'stock') as FilterInput | undefined;
    return stockInput
      ? [
          {
            filter: stockInput,
            icon: 'isaFiliale',
          },
        ]
      : [];
  });

  search(trigger: SearchTrigger): void {
    this.searchTrigger.set(trigger); // Ist entweder 'scan', 'input', 'filter' oder 'orderBy'
    this.#filterService.commit();
  }
}
