import { Locator } from '@playwright/test';
import { BaseComponent } from '@/shared/base/BaseComponent';
import { CardPaymentSection } from '@/shared/modules/payment-method/components/CardPaymentSection';
import { SepaPaymentSection } from '@/shared/modules/payment-method/components/SepaPaymentSection';
import { StripeSelect } from '@/shared/modules/payment-method/components/StripeSelect';
import { CardPayment, SepaPayment } from '@/shared/modules/payment-method/payment-method-types';

export class BookingStripePaymentElement extends BaseComponent {
  private readonly cardId = 'card';
  private readonly cardPaymentSection = new CardPaymentSection(this.getPanel(this.cardId));
  private readonly sepaId = 'sepa_debit';
  private readonly sepaPaymentSection = new SepaPaymentSection(this.getPanel(this.sepaId));
  private readonly additionalPaymentMethodsSelect = new StripeSelect(this.host.locator('.p-AdditionalPaymentMethods'));
  private readonly tablist = this.host.getByRole('tablist');

  async fillCardInfo(data: CardPayment): Promise<void> {
    await this.selectTab(this.cardId);
    await this.cardPaymentSection.fill(data);
  }

  async fillSepaInfo(data: SepaPayment): Promise<void> {
    await this.selectTab(this.sepaId);
    await this.sepaPaymentSection.fill(data);
  }

  private async selectTab(id: string): Promise<void> {
    await this.tablist.click({ trial: true });

    try {
      await this.getTab(id).click({ timeout: 2500 });
    } catch (e) {
      await this.additionalPaymentMethodsSelect.select(id);
    }
  }

  private getTab(id: string): Locator {
    return this.host.locator(`[data-testid=${id}]`);
  }

  private getPanel(id: string): Locator {
    return this.host.locator(`#${id}-panel`).locator('.p-Tabs-group:not(.is-exiting):not(.is-entering)');
  }
}
