import { IBookingCreateUnitTypeBilling } from '@/apps/portal/modules/booking/types/booking-entity-types';
import { BaseComponent } from '@/shared/modules/base/components/BaseComponent';
import { formatBillingPeriod } from '@/shared/utils/format-utils';
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: IBookingCreateUnitTypeBilling): 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}"))`
    );
  }
}
