import { BookingCreateUnitTypeBilling } from '@/portal/modules/booking/booking-types';
import { BaseComponent } from '@/shared/base/BaseComponent';
import { formatBillingPeriod } from '@/shared/utils/formatters';
import { Locator } from '@playwright/test';

export class BookingBillingPeriodList extends BaseComponent {
  private readonly loadMoreButton = this.host.locator('[data-test-id=load-more-button]:not(:disabled)');

  async select(billingPeriod: BookingCreateUnitTypeBilling): Promise<void> {
    const periodStr = formatBillingPeriod(billingPeriod.type, billingPeriod.amount);
    const card = this.getBillingPeriodCard(billingPeriod.name ?? periodStr, periodStr);
    let cardClicked = false;

    do {
      try {
        await card.click({ timeout: 2500 });
        cardClicked = true;
      } catch (e) {
        await this.loadMoreButton.click();
      }
    } while (!cardClicked);
  }

  private getBillingPeriodCard(title: string, period: string): Locator {
    return this.host.locator(
      `[data-test-id=billing-period-card]:has([data-test-id=billing-period-card-title]:text-is("${title}")):has([data-test-id=billing-period-card-period]:text-is("Billing period: ${period}"))`
    );
  }
}
