import {
  ChangeDetectionStrategy,
  Component,
  inject,
  computed,
} from '@angular/core';
import { RewardSelectionItemComponent } from '../reward-selection-item.component';
import { RewardSelectionStore } from '../../../store/reward-selection-dialog.store';
import {
  OrderTypeFeature,
  calculatePriceValue,
  calculateLoyaltyPointsValue,
  hasOrderTypeFeature,
} from '@isa/checkout/data-access';
import { QuantityControlComponent } from '@isa/shared/quantity-control';
import { FormsModule } from '@angular/forms';

@Component({
  selector: 'lib-reward-selection-inputs',
  templateUrl: './reward-selection-inputs.component.html',
  styleUrl: './reward-selection-inputs.component.css',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [FormsModule, QuantityControlComponent],
})
export class RewardSelectionInputsComponent {
  store = inject(RewardSelectionStore);
  rewardSelectionItem = inject(RewardSelectionItemComponent, { host: true })
    .rewardSelectionItem;

  loyaltyValue = computed(() =>
    calculateLoyaltyPointsValue(this.rewardSelectionItem()),
  );

  priceValue = computed(() => calculatePriceValue(this.rewardSelectionItem()));

  rewardCartQuantity = computed(
    () => this.rewardSelectionItem()?.rewardCartQuantity ?? 0,
  );

  cartQuantity = computed(() => this.rewardSelectionItem()?.cartQuantity ?? 0);

  hasCorrectOrderType = computed(() => {
    const item = this.rewardSelectionItem().item;
    return hasOrderTypeFeature(item.features, [OrderTypeFeature.InStore]);
  });

  hasStock = computed(() => {
    const item = this.rewardSelectionItem().item;
    if (this.hasCorrectOrderType()) {
      return !!item?.availability?.inStock && item.availability.inStock > 0;
    }
    return true;
  });

  maxQuantity = computed(() => {
    const item = this.rewardSelectionItem().item;
    if (this.hasCorrectOrderType()) {
      return item?.availability?.inStock;
    }
    return undefined;
  });

  changeCartQuantity(quantity: number) {
    this.store.updateItemCartQuantity(
      this.rewardSelectionItem().item.id!,
      quantity,
    );
  }

  changeRewardCartQuantity(quantity: number) {
    this.store.updateItemRewardCartQuantity(
      this.rewardSelectionItem().item.id!,
      quantity,
    );
  }
}
