import {
  ChangeDetectionStrategy,
  Component,
  computed,
  inject,
} from '@angular/core';
import { SelectedRewardShoppingCartResource, calculateTotalLoyaltyPoints } from '@isa/checkout/data-access';
import {
  SelectedCustomerResource,
  PrimaryCustomerCardResource,
} from '@isa/crm/data-access';

@Component({
  selector: 'checkout-customer-reward-card',
  templateUrl: './customer-reward-card.component.html',
  styleUrls: ['./customer-reward-card.component.css'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [],
})
export class CheckoutCustomerRewardCardComponent {
  #shoppingCartResource = inject(SelectedRewardShoppingCartResource).resource;
  #customerResource = inject(SelectedCustomerResource).resource;
  #primaryCustomerCardResource = inject(PrimaryCustomerCardResource);

  customerLoading = this.#customerResource.isLoading;

  customerName = computed(() => {
    const customer = this.#customerResource.value();
    if (!customer) {
      return 'Kein Kunde ausgewählt';
    }

    return `${customer.firstName} ${customer.lastName}`;
  });

  shoppingCartLoading = this.#shoppingCartResource.isLoading;

  selectedItems = computed(() => {
    const cart = this.#shoppingCartResource.value();
    return cart?.items?.length ?? 0;
  });

  totalPointsRequired = computed(() => {
    const cart = this.#shoppingCartResource.value();
    return calculateTotalLoyaltyPoints(cart?.items);
  });

  bonusCardsLoading = this.#primaryCustomerCardResource.loading;

  readonly primaryCustomerCardValue =
      this.#primaryCustomerCardResource.primaryCustomerCard;

    primaryBonusCardPoints = computed(
      () => this.primaryCustomerCardValue()?.totalPoints ?? 0,
    );

  hasInsufficientPoints = computed(() => {
    const available = this.primaryBonusCardPoints();
    const required = this.totalPointsRequired();
    return available < required;
  });
}
