import { Timeouts } from '@utility-lib/index';
import { GuestInfoShort } from '@guest-invite-lib/interface';

const selectors = {
  newTravelerButton: 'ta-other-travelers .ta-button--primary-theme',
  newTravelerModal: 'ta-modal[class^="ta-user-modal"]',
  travelerRow: '.ta-other-travelers__traveler-row',
  listLoading: '.ta-other-travelers__list ta-spinner',
  editButton: '.ta-other-travelers__traveler-row__actions [icon="edit-small"]',
  deleteButton: '.ta-other-travelers__traveler-row__actions--action[color="secondary"]',
  removeTravelerModal: 'ta-modal[class^="ta-remove-other-traveler-modal"]',
  confirmRemoveButton: '.ta-remove-other-traveler-modal--remove',
  empty: '.ta-other-travelers__empty'
};

export class GuestTravelInfo {
  static visitPage(): void {
    cy.allure().logStep('Visit profile page on otherTraveler tab');
    cy.visit('app/user2/profile?tab=otherTraveler');
    cy.wait(Timeouts.SHORT_TIMEOUT_3_SEC.timeout);
  }

  static waitToBeLoaded(): void {
    cy.wait('@waitForTravelers');
  }

  static waitUpdateList(): void {
    cy.get(selectors.listLoading).should('not.exist');
  }

  static interceptApis(): void {
    cy.intercept('GET', new RegExp('/api/user/guests\\?.+')).as('waitForTravelers');
  }

  static openNewTravelerModal(): void {
    cy.get(selectors.newTravelerButton).click();
    cy.get(selectors.newTravelerModal).should('be.visible');
  }

  static openEditTravelerModal(givenName: string, familyName: string): void {
    cy.get(selectors.travelerRow).then(($rows) => {
      const userRow = $rows
        .get()
        .filter(($row: any) => $row.innerText.indexOf(`${givenName} ${familyName}`));
      cy.wrap(userRow).within(() => {
        cy.get(selectors.editButton).click();
      });
    });
    cy.get(selectors.newTravelerModal).should('be.visible');
  }

  static deleteTraveler(givenName: string, familyName: string): void {
    cy.get(selectors.travelerRow).then(($rows) => {
      const userRow = $rows
        .get()
        .filter(($row: any) => $row.innerText.indexOf(`${givenName} ${familyName}`));
      cy.wrap(userRow).within(() => {
        cy.get(selectors.deleteButton).click();
      });
    });

    cy.get(selectors.removeTravelerModal).should('be.visible');
    cy.get(selectors.confirmRemoveButton).click();
  }

  static expectGuestToExists(guestInfo: GuestInfoShort, index = 0): void {
    const { email, lastName, firstName } = guestInfo;
    cy.get(selectors.travelerRow)
      .eq(index)
      .contains(`${firstName} ${lastName} ${email}`)
      .should('be.visible');
  }

  static expectToHaveNoGuests(): void {
    cy.get(selectors.empty).should('be.visible');
  }
}
