import {
  ChangeDetectionStrategy,
  Component,
  computed,
  inject,
} from '@angular/core';
import { RewardSelectionItemComponent } from './reward-selection-item/reward-selection-item.component';
import { RewardSelectionStore } from '../store/reward-selection-dialog.store';
import { NgIcon, provideIcons } from '@ng-icons/core';
import {
  isaDeliveryVersand,
  isaDeliveryRuecklage2,
  isaDeliveryRuecklage1,
  isaDeliveryB2BVersand1,
} from '@isa/icons';
import {
  getOrderTypeIcon,
  groupByOrderType,
  groupByBranch,
  shouldShowGrouping,
} from '@isa/checkout/data-access';

@Component({
  selector: 'lib-reward-selection-items',
  templateUrl: './reward-selection-items.component.html',
  styleUrl: './reward-selection-items.component.css',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [RewardSelectionItemComponent, NgIcon],
  providers: [
    provideIcons({
      isaDeliveryVersand,
      isaDeliveryRuecklage2,
      isaDeliveryRuecklage1,
      isaDeliveryB2BVersand1,
    }),
  ],
})
export class RewardSelectionItemsComponent {
  store = inject(RewardSelectionStore);

  items = computed(() => Object.values(this.store.rewardSelectionItems()));
  showGrouping = computed(() => shouldShowGrouping(this.items()));

  groupedItems = computed(() => {
    if (!this.showGrouping()) return [];

    const groups = groupByOrderType(this.items());
    return Array.from(groups.entries()).map(([orderType, items]) => ({
      orderType,
      icon: getOrderTypeIcon(orderType),
      subGroups: groupByBranch(orderType, items),
    }));
  });
}
