import {
  ChangeDetectionStrategy,
  Component,
  computed,
  inject,
  input,
  signal,
} from '@angular/core';
import { breakpoint, Breakpoint } from '@isa/ui/layout';
import {
  hasOrderTypeFeature,
  SelectedRewardShoppingCartResource,
  ShoppingCartItem,
} from '@isa/checkout/data-access';
import {
  ProductInfoRedemptionComponent,
  DestinationInfoComponent,
} from '@isa/checkout/shared/product-info';
import { logger } from '@isa/core/logging';
import { PurchaseOptionsModalService } from 'apps/isa-app/src/modal/purchase-options/purchase-options-modal.service';
import { TabService } from '@isa/core/tabs';
import { firstValueFrom } from 'rxjs';
import { RewardShoppingCartItemQuantityControlComponent } from './reward-shopping-cart-item-quantity-control.component';
import { RewardShoppingCartItemRemoveButtonComponent } from './reward-shopping-cart-item-remove-button.component';
import { NgIcon, provideIcons } from '@ng-icons/core';
import { isaOtherInfo } from '@isa/icons';

// TODO: [Next Sprint - Medium Priority] Create test file
// - Test component creation and item input binding
// - Test busy state coordination between child components
// - Test purchase option update flow
// - Test integration with child components (quantity control and remove button)
@Component({
  selector: 'checkout-reward-shopping-cart-item',
  templateUrl: './reward-shopping-cart-item.component.html',
  styleUrls: ['./reward-shopping-cart-item.component.css'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [
    ProductInfoRedemptionComponent,
    DestinationInfoComponent,
    RewardShoppingCartItemQuantityControlComponent,
    RewardShoppingCartItemRemoveButtonComponent,
    NgIcon,
  ],
  providers: [provideIcons({ isaOtherInfo })],
})
export class RewardShoppingCartItemComponent {
  #logger = logger(() => ({ component: 'RewardShoppingCartItemComponent' }));

  #tabId = inject(TabService).activatedTab;

  #rewardShoppingCartResource = inject(SelectedRewardShoppingCartResource)
    .resource;

  #purchaseOptionsModalService = inject(PurchaseOptionsModalService);

  isBusy = signal(false);

  isHorizontal = breakpoint([
    Breakpoint.DesktopL,
    Breakpoint.DesktopL,
    Breakpoint.DesktopXL,
  ]);

  item = input.required<ShoppingCartItem>();

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

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

  isDownload = computed(() =>
    hasOrderTypeFeature(this.item().features, ['Download']),
  );

  isAbholung = computed(() =>
    hasOrderTypeFeature(this.item().features, ['Abholung']),
  );

  inStock = computed(() => this.item().availability?.inStock ?? 0);

  showLowStockMessage = computed(() => {
    return this.isAbholung() && this.inStock() < 2;
  });

  async updatePurchaseOption() {
    const shoppingCartItemId = this.itemId();
    const shoppingCartId = this.shoppingCartId();
    const branch = this.item().destination?.data?.targetBranch?.data;

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

    try {
      const ref = await this.#purchaseOptionsModalService.open({
        items: [this.item()],
        shoppingCartId: this.shoppingCartId()!,
        tabId: this.#tabId() as unknown as number,
        type: 'update',
        useRedemptionPoints: true,
        disabledPurchaseOptions: ['b2b-delivery'],
        hideDisabledPurchaseOptions: true,
        pickupBranch: branch,
        inStoreBranch: branch,
      });

      await firstValueFrom(ref.afterClosed$);

      this.#rewardShoppingCartResource.reload();
    } catch (error) {
      this.#logger.error('Error updating purchase options', error);
    }

    this.isBusy.set(false);
  }
}
