import {
  ChangeDetectionStrategy,
  Component,
  computed,
  inject,
} from '@angular/core';
import { NavigateBackButtonComponent } from '@isa/core/tabs';
import { CheckoutCustomerRewardCardComponent } from './customer-reward-card/customer-reward-card.component';
import { BillingAndShippingAddressCardComponent } from './billing-and-shipping-address-card/billing-and-shipping-address-card.component';
import { RewardShoppingCartItemsComponent } from './reward-shopping-cart-items/reward-shopping-cart-items.component';
import {
  SelectedRewardShoppingCartResource,
  calculateTotalLoyaltyPoints,
} from '@isa/checkout/data-access';
import {
  SelectedCustomerResource,
  PrimaryCustomerCardResource,
} from '@isa/crm/data-access';
import { CompleteOrderButtonComponent } from './complete-order-button/complete-order-button.component';
import { RewardSelectionTriggerComponent } from '@isa/checkout/shared/reward-selection-dialog';
import { NgIconComponent, provideIcons } from '@ng-icons/core';
import { isaOtherInfo } from '@isa/icons';
import { EmptyStateComponent, EmptyStateAppearance } from '@isa/ui/empty-state';

@Component({
  selector: 'checkout-reward-shopping-cart',
  templateUrl: './reward-shopping-cart.component.html',
  styleUrls: ['./reward-shopping-cart.component.css'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [
    NavigateBackButtonComponent,
    CheckoutCustomerRewardCardComponent,
    BillingAndShippingAddressCardComponent,
    RewardShoppingCartItemsComponent,
    CompleteOrderButtonComponent,
    RewardSelectionTriggerComponent,
    NgIconComponent,
    EmptyStateComponent,
  ],
  providers: [provideIcons({ isaOtherInfo })],
})
export class RewardShoppingCartComponent {
  EmptyStateAppearance = EmptyStateAppearance;
  #shoppingCartResource = inject(SelectedRewardShoppingCartResource).resource;
  #primaryCustomerCardResource = inject(PrimaryCustomerCardResource);

  primaryBonusCardPoints = computed(
    () =>
      this.#primaryCustomerCardResource.primaryCustomerCard()?.totalPoints ?? 0,
  );

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

  insufficientPoints = computed(() => {
    return this.primaryBonusCardPoints() < this.totalPointsRequired();
  });

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

  constructor() {
    this.#shoppingCartResource.reload();
  }
}
