import {
  ChangeDetectionStrategy,
  Component,
  computed,
  inject,
  input,
  model,
} from '@angular/core';
import {
  SelectedRewardShoppingCartResource,
  ShoppingCartFacade,
  ShoppingCartItem,
} from '@isa/checkout/data-access';
import { IconButtonComponent } from '@isa/ui/buttons';
import { provideIcons } from '@ng-icons/core';
import { isaActionClose } from '@isa/icons';
import { logger } from '@isa/core/logging';

// TODO: [Next Sprint - Medium Priority] Create test file
// - Test remove button click handling
// - Test busy state management
// - Test shopping cart facade integration
// - Test guard conditions (busy, missing IDs)
// - Test error handling during removal
// - Verify E2E attributes are correctly applied
@Component({
  selector: 'checkout-reward-shopping-cart-item-remove-button',
  templateUrl: './reward-shopping-cart-item-remove-button.component.html',
  styleUrls: ['./reward-shopping-cart-item-remove-button.component.css'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [IconButtonComponent],
  providers: [provideIcons({ isaActionClose })],
})
export class RewardShoppingCartItemRemoveButtonComponent {
  #logger = logger(() => ({
    component: 'RewardShoppingCartItemRemoveButtonComponent',
  }));

  #rewardShoppingCartResource = inject(SelectedRewardShoppingCartResource)
    .resource;
  #shoppingCartFacade = inject(ShoppingCartFacade);

  isBusy = model.required<boolean>();

  item = input.required<ShoppingCartItem>();

  itemId = computed(() => this.item().id);

  shoppingCartId = computed(() => this.#rewardShoppingCartResource.value()?.id);

  async remove() {
    const shoppingCartItemId = this.itemId();
    const shoppingCartId = this.shoppingCartId();

    if (this.isBusy() || !shoppingCartId || !shoppingCartItemId) {
      return;
    }
    this.isBusy.set(true);

    try {
      await this.#shoppingCartFacade.removeItem({
        shoppingCartId,
        shoppingCartItemId,
      });

      this.#rewardShoppingCartResource.reload();
    } catch (error) {
      this.#logger.error('Error removing item from shopping cart', error);
    }

    this.isBusy.set(false);
  }
}
