import { Hotels } from '@hotel-lib/search';
import { LocationUtility } from '@utility-lib/location';
import { HotelSearchResults } from '@hotel-lib/search_results';
import { HotelCheckout, hotelCheckoutSelector } from '@hotel-lib/checkout';
import { Random } from '@utility-lib/random';
import { FlightBookingUtility } from '@flight-modal/flight_booking_utility';
import { flightSearchSelector, FlightTripType } from '@flight-lib/search';
import { Utility, utilitySelector } from '@utility-lib/utility';
import { FlightUtility } from '@flight-modal/flight_utility';
import { FlightCheckout } from '@flight-lib/checkout';
import { Timeouts } from '@utility-lib/constants';
import { Itinerary } from './itinerary';
import { FlightSearchResults } from '@flight-lib/search_results';
import { RentalCar, rentalCarSelector } from '@rentalCar-lib/search';
import { RentalCarSearchResults } from '@rentalCar-lib/search_results';
import { RentalCarCheckout } from '@rentalCar-lib/checkout';
import { RentalCarItinerary } from '@rentalCar-lib/itinerary';
import { BlackCar, blackCarSelector, BlackCarTripType } from '@blackCar-lib/search';
import { BlackCarSearchResults } from '@blackCar-lib/search_results';
import { blackCarsProvider } from '@fixtures/black_car';
import { BlackCarCheckout } from '@blackCar-lib/checkout';
import { ContactModal } from '@profile-lib/contact-info';
import { GuestTravelInfo } from '@profile-lib/guest-travel-info';
import { TravelerModal } from '@profile-lib/traveler-info';
import { PaymentMethods } from '@profile-lib/payment-method';

const PersonalHomeScreenSelector = {
  themeSelectorToggle: '.search-form-container-minimized__tabs',
  personalTripSelector:
    '[class^="theme-selector__tabs theme-selector__compact ng-star-inserted"] [aria-label="Personal travel"]',
  groupTravelTab: '[data-testid="groupTravelSubtab"]',
  personalHomeEducation: '.personal-home-education',
  tripSwitcherDropdown: '[data-qaid="PLATFORM_SWITCHER-button"]',
  personalTripSearchLanding:
    '[class^="ta-tabs__item ng-star-inserted"][aria-label="Personal travel"]',
  bookTravelItem: '.ta-menu-item--text',
  hotelLocationV2: '.ta-location-search-v2',
  specialTripCard: '.special-trip-card',
  extendButton: '.ta-button__content'
};

export class PersonalHomeScreen {
  static themeSelectorPresent(): void {
    cy.allure().logStep('verify theme selector is shown on homepage');
    cy.get(PersonalHomeScreenSelector.themeSelectorToggle).should('be.visible');
  }

  static switchToPersonalTravel(): void {
    cy.allure().logStep('switch to personal travel screen from homepage');
    cy.get(PersonalHomeScreenSelector.personalTripSelector).eq(0).click();
  }

  static verifyGroupEventTile(): void {
    cy.allure().logStep('verify group event tile shown on business travel screen');
    cy.get(PersonalHomeScreenSelector.groupTravelTab).should('be.visible');
  }
  static verifyPersonalHomeEducationShown(): void {
    cy.allure().logStep('verify personal home education is shown');
    cy.get(PersonalHomeScreenSelector.personalHomeEducation).should('be.visible');
  }

  static verifyBusinessTravelDropdown(): void {
    cy.allure().logStep('verify business travel dropdown is shown');
    cy.get(PersonalHomeScreenSelector.tripSwitcherDropdown).contains('Business Travel');
  }

  static switchToPersonalSearchLanding(): void {
    cy.allure().logStep('switch to personal travel search landing page');
    cy.get(PersonalHomeScreenSelector.personalTripSearchLanding).eq(1).click();
  }
  static verifyPersonalTravelDropdown(): void {
    cy.allure().logStep('verify personal travel dropdown is shown');
    cy.get(PersonalHomeScreenSelector.tripSwitcherDropdown).contains('Personal Travel');
  }

  static clickBusinessTravelDropdown(): void {
    cy.allure().logStep('click business travel dropdown from homepage');
    cy.get(PersonalHomeScreenSelector.tripSwitcherDropdown).click();
    cy.get(PersonalHomeScreenSelector.bookTravelItem)
      .contains('Book business travel')
      .click();
  }

  static clickPersonalTravelDropdown(): void {
    cy.allure().logStep('click business travel dropdown from homepage');
    cy.get(PersonalHomeScreenSelector.tripSwitcherDropdown).click();
    cy.get(PersonalHomeScreenSelector.bookTravelItem)
      .contains('Book personal travel')
      .click();
  }

  static setHotelLocation(location: string) {
    cy.get(PersonalHomeScreenSelector.hotelLocationV2).type('Seattle, WA, USA');
    cy.wait('@waitForLocation');
    cy.wait(Timeouts.SHORT_TIMEOUT_3_SEC.timeout);
    Utility.selectLocationFromDropdown(location);
  }
  static bookPersonalHotel(): void {
    Hotels.setCheckInCheckOutDate();
    PersonalHomeScreen.setHotelLocation('Seattle, WA, USA');
    Hotels.searchHotel();
    HotelSearchResults.selectHotel(0);
    HotelSearchResults.selectRoomOption();
    HotelCheckout.waitToBeLoaded();
    HotelCheckout.createNewTripInfo();
    HotelCheckout.hotelCancellationAndChargePolicy();
    HotelCheckout.updateEmailDetails(
      'personal-' + Random.randomString(12) + '@staging-prime.tripactions.xyz'
    );
    HotelCheckout.setPhoneNumber();
    HotelCheckout.acceptAcknowledgement();
    HotelCheckout.bookNow();
    Itinerary.dismissBookingModal();
  }
  static setFlightLocation(location: string, index: number) {
    cy.get(flightSearchSelector.locationInput)
      .eq(index)
      .then((ele) => {
        cy.wrap(ele).type(`${location}`, { force: true });
        cy.wait(Timeouts.SHORT_TIMEOUT_3_SEC.timeout);
      });
    cy.get(utilitySelector.bodySelector).then(() => {
      cy.get(utilitySelector.ariaLabel(location.substring(0, 3))).trigger('click', {
        force: true
      });
    });
  }
  static setFlightOrigin(location: string) {
    cy.allure().logStep(`select origin - ${location}`);
    this.setFlightLocation(`${location}`, 0);
  }

  static setFlightDestination(location: string) {
    cy.allure().logStep(`select destination - ${location}`);
    this.setFlightLocation(`${location}`, 1);
  }

  static bookPersonalFlight(): void {
    const flightBookingParams = FlightBookingUtility.initFlightBookingParams({
      locations: LocationUtility.getPairOfOriginAndDestinationAirportsUS(),
      flightTripType: FlightTripType.ROUNDTRIP,
      tripTileType: 'Personal',
      flightConfirmText: 'Your flight is booked!',
      checkInType: ' Continue without EarlyBird Check-In® '
    });
    FlightSearchResults.selectFutureFlightDate();
    PersonalHomeScreen.setFlightOrigin('SFO');
    PersonalHomeScreen.setFlightDestination('MIA');
    FlightSearchResults.searchFlight();
    FlightSearchResults.roundtripSearchResult(flightBookingParams);

    FlightCheckout.waitToPageBeLoaded();

    FlightCheckout.createTripInformation();

    FlightCheckout.checkCancellationPolicy();
    FlightCheckout.acceptOutOfPolicyFlight();
    FlightCheckout.updateContactDetails();
    if (flightBookingParams.tripTileType === 'Personal') {
      FlightCheckout.skipSeatSelection();
    }

    if (flightBookingParams.tripTileType === 'Personal') {
      FlightCheckout.updateEmailDetails(
        'personal-' + Random.randomString(12) + '@staging-prime.tripactions.xyz'
      );
    }
    FlightCheckout.validateIfPassportAndVisaInfoRequired();
    FlightCheckout.expectBookingSummary(
      flightBookingParams.checkOutConfirmText
        ? flightBookingParams.checkOutConfirmText
        : FlightUtility.getNameByType(flightBookingParams.flightTripType)
    );

    FlightCheckout.storeBookingData();
    FlightCheckout.storeCreditCardLastDigits();

    if (flightBookingParams.insurance) {
      cy.wait('@waitForInsurances');
      FlightCheckout.addInsurance();
    }
    FlightCheckout.bookAndPay(flightBookingParams);
    flightBookingParams.insurance && cy.wait('@waitForPostInsurances');
  }

  static cancelBooking(vertical: string) {
    Utility.cancelTrip(vertical);
    Utility.selectCancellationReason('Change of plans');
    Utility.confirmCancellation();
    Utility.expectCancelledLabelIsPresent();
  }
  static specialTripCardVisible(): void {
    cy.allure().logStep('verify special trip card is shown on homescreen');
    cy.get(PersonalHomeScreenSelector.specialTripCard).should('be.visible');
  }

  static clickExtendTripButton(): void {
    cy.allure().logStep('click extend trip button from special trip card');
    cy.get(PersonalHomeScreenSelector.extendButton).contains('Extend hotel stay').click();
  }

  static setCarLocation(location: string) {
    cy.allure().logStep(`set rental car pickup location: ${location}`);
    cy.get(rentalCarSelector.location).type(`${location}`, { force: true });
    cy.wait('@waitForLocation');
    cy.get(rentalCarSelector.popoverContentLocation(location)).eq(0).trigger('click', {
      force: true
    });
  }
  static bookRentalCar() {
    cy.allure().logStep('book car');
    cy.get(hotelCheckoutSelector.bookNow).last().click();
    cy.wait('@waitForBooking');
  }
  static bookPersonalCar(): void {
    Utility.selectVertical('car');
    RentalCar.setPickUpAndDropOffDate();
    PersonalHomeScreen.setCarLocation('SFO');
    RentalCar.searchRentalCar();
    RentalCarSearchResults.selectCar();
    RentalCarCheckout.waitToBeLoaded();
    HotelCheckout.createNewTripInfo();
    RentalCarCheckout.setAcknowledgement();
    PersonalHomeScreen.bookRentalCar();
    Itinerary.dismissBookingModal();
    RentalCarItinerary.cancelCar();
  }

  static setBlackCarLocation(location: string) {
    cy.allure().logStep(`set black car pickup location: ${location}`);
    cy.get(blackCarSelector.location).type(`${location}`, { force: true });
    cy.wait('@waitForLocation');
    cy.get(blackCarSelector.popoverLocation(location)).eq(0).trigger('click', {
      force: true
    });
  }

  static bookBlackCar() {
    cy.allure().logStep('book car');
    cy.get(hotelCheckoutSelector.bookNow).last().click();
    cy.wait('@waitForCheckout');
  }
  static cancelBlackCar() {
    Utility.cancelTrip('BlackCar');
    Utility.confirmCancellation();
    Utility.expectCancelledLabelIsPresent();
  }
  static bookPersonalBlackCar(hours: number, pickUpLocation: string): void {
    Utility.selectVertical('blackCar');
    BlackCar.selectTripTileType(BlackCarTripType.HOURLY);
    BlackCar.selectDuration(hours);
    PersonalHomeScreen.setBlackCarLocation(pickUpLocation);
    BlackCar.setPickUpAndDropOffDate();
    BlackCar.searchBlackCar();
    BlackCarSearchResults.selectCar(blackCarsProvider);
    BlackCarCheckout.waitToBeLoaded();
    HotelCheckout.createNewTripInfo();
    PersonalHomeScreen.bookBlackCar();
    Itinerary.dismissBookingModal();
    PersonalHomeScreen.cancelBlackCar();
  }
  static viewProfile(): void {
    ContactModal.visitPage();
    GuestTravelInfo.visitPage();
    TravelerModal.visitPage();
    PaymentMethods.visitPage();
  }
}
