import {
  ChangeDetectionStrategy,
  Component,
  inject,
  computed,
  signal,
} from '@angular/core';
import { ButtonComponent } from '@isa/ui/buttons';
import { RewardSelectionStore } from '../store/reward-selection-dialog.store';
import { RewardSelectionDialogComponent } from '../reward-selection-dialog.component';
import { RewardSelectionFacade } from '@isa/checkout/data-access';
import { injectTabId } from '@isa/core/tabs';

@Component({
  selector: 'lib-reward-selection-actions',
  templateUrl: './reward-selection-actions.component.html',
  styleUrl: './reward-selection-actions.component.css',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [ButtonComponent],
})
export class RewardSelectionActionsComponent {
  host = inject(RewardSelectionDialogComponent, { host: true });
  #tabId = injectTabId();
  #store = inject(RewardSelectionStore);
  #rewardSelectionFacade = inject(RewardSelectionFacade);

  insufficientLoyaltyPoints = computed(
    () =>
      this.#store.totalLoyaltyPointsNeeded() >
      this.#store.customerRewardPoints(),
  );

  completeRewardSelectionLoading = signal(false);

  onContinue() {
    this.host.close(undefined);
  }

  async onSave() {
    const tabId = this.#tabId();
    if (
      !tabId ||
      this.insufficientLoyaltyPoints() ||
      this.completeRewardSelectionLoading()
    ) {
      return;
    }

    this.completeRewardSelectionLoading.set(true);
    const rewardSelectionItems = Object.values(
      this.#store.rewardSelectionItems(),
    );
    await this.#rewardSelectionFacade.completeRewardSelection({
      tabId,
      rewardSelectionItems,
    });
    this.completeRewardSelectionLoading.set(false);

    this.host.close({ rewardSelectionItems });
  }
}
