import {
  ChangeDetectionStrategy,
  Component,
  computed,
  inject,
} from '@angular/core';

import { OrderConfirmationItemListItemComponent } from './order-confirmation-item-list-item/order-confirmation-item-list-item.component';

import {
  groupItemsByDeliveryDestination,
  type OrderItemGroup,
} from '@isa/checkout/data-access';
import { NgIcon, provideIcons } from '@ng-icons/core';
import {
  isaDeliveryVersand,
  isaDeliveryRuecklage2,
  isaDeliveryRuecklage1,
  isaDeliveryB2BVersand1,
} from '@isa/icons';
import { OrderConfiramtionStore } from '../reward-order-confirmation.store';

@Component({
  selector: 'checkout-order-confirmation-item-list',
  templateUrl: './order-confirmation-item-list.component.html',
  styleUrls: ['./order-confirmation-item-list.component.css'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [OrderConfirmationItemListItemComponent, NgIcon],
  providers: [
    provideIcons({
      isaDeliveryVersand,
      isaDeliveryRuecklage2,
      isaDeliveryRuecklage1,
      isaDeliveryB2BVersand1,
    }),
  ],
})
export class OrderConfirmationItemListComponent {
  #store = inject(OrderConfiramtionStore);

  /**
   * Track function for @for to optimize rendering.
   * Generates a unique key for each group based on order type and destination.
   */
  trackByGroupedItems = (group: OrderItemGroup): string => {
    let key = group.orderType;

    if (group.shippingAddress) {
      key += `-shippingAddress-${JSON.stringify(group.shippingAddress)}`;
    }

    if (group.targetBranch) {
      key += `-targetBranch-${group.targetBranch.id}`;
    }

    return key;
  };

  /**
   * Groups order items by delivery type and destination.
   * Uses the helper function for efficient Map-based grouping.
   */
  groupedItems = computed(() => {
    const orders = this.#store.orders();
    return groupItemsByDeliveryDestination(orders ?? []);
  });
}
