import { guidRegex, TripTileType, utilitySelector, Timeouts } from '@utility-lib/index';
import { ContactModal } from '@profile-lib/contact-info';

const selectors = {
  travelerTypeButton: 'ta-select[formcontrolname="travelerType"]',
  popover: '[class^="popover-content"]',
  dropdownOption: 'ta-select-option',
  givenNameInput: 'input[formcontrolname="givenName"]',
  familyNameInput: 'input[formcontrolname="familyName"]',
  genderInput: 'ta-select[formcontrolname="gender"]',
  emailInput: 'input[formcontrolname="email"]',
  alternateEmailInput: 'input[formcontrolname="alternateEmail"]',
  phoneInput: 'ta-phone-input[formcontrolname="mobilePhone"]',
  mobilePhoneInput: `ta-phone-input[formcontrolname="phoneNumber"]`,
  workPhoneInput: 'ta-phone-input[formcontrolname="workPhoneNumber"]',
  useMyInfoCheckbox: '[class="ta-checkbox"]',
  billTo: '[formcontrolname="billTo"]',
  department: '[formcontrolname="department"]',
  subsidiary: '[formcontrolname="subsidiary"]',
  region: '[formcontrolname="region"]',
  saveButton: '[data-testid="user-modal-save"]',
  dropDownContainer: '[class="popover ta-select-dropdown enter"]',
  birtdateInput: 'ta-date-input[formcontrolname="birthdate"] input',
  saveChanges: '[data-testid="stickyPrimaryButton"]'
};

export class UserModal {
  static interceptApis(): void {
    cy.intercept('POST', new RegExp('/api/user/guests')).as('waitForCreateTraveler');
    cy.intercept('PUT', new RegExp(`/api/user/guests/${guidRegex}`)).as(
      'waitForEditTraveler'
    );
    cy.intercept('GET', new RegExp(`/api/user/company/userFields`), {
      billTo: ['ABC', '123'],
      department: ['dep1', 'dep2'],
      region: ['region 1', 'region 2'],
      subsidiary: ['sub1', 'sub2']
    });
  }

  static fillTravelerType(type: TripTileType): void {
    cy.allure().logStep(`Fill traveler type: ${type}`);
    cy.get(selectors.travelerTypeButton).click();
    cy.get(selectors.popover).within(() => {
      cy.get(selectors.dropdownOption).contains(type).click();
    });
  }

  static fillTravelerName(givenName: string, familyName: string): void {
    cy.allure().logStep(`Fill traveler name: ${givenName} ${familyName}`);
    cy.clearInputAndType(selectors.givenNameInput, givenName);
    cy.clearInputAndType(selectors.familyNameInput, familyName);
  }

  static fillBirthday(age: number): void {
    cy.allure().logStep(`Fill traveler age: ${age}`);
    const birthdate = new Date();
    birthdate.setUTCFullYear(birthdate.getUTCFullYear() - age);

    const day = birthdate.getDate();
    const month = birthdate.getMonth() + 1;
    const year = birthdate.getUTCFullYear();

    let input = '';
    input += month < 10 ? `0${month}` : month;
    input += day < 10 ? `0${day}` : day;
    input += year;

    cy.get(selectors.birtdateInput).type(input);
  }

  static fillGender(gender: 'MALE' | 'FEMALE'): void {
    cy.allure().logStep(`Fill traveler gender: ${gender}`);
    const genderIndex = gender === 'FEMALE' ? 0 : 1;
    cy.get(selectors.genderInput).click();
    cy.get(selectors.dropDownContainer).within(() => {
      cy.get(selectors.dropdownOption).eq(genderIndex).click();
    });
  }

  static fillEmail(email: string): void {
    cy.allure().logStep(`Fill traveler email: ${email}`);
    cy.clearInputAndType(selectors.emailInput, email);
  }

  static fillAltEmail(email: string): void {
    cy.allure().logStep(`Fill contact email: ${email}`);
    cy.clearInputAndType(selectors.alternateEmailInput, email);
  }

  static fillPhoneNumber(phone: string): void {
    cy.allure().logStep(`Fill traveler phone: ${phone}`);
    cy.clearInputAndType(selectors.phoneInput, `{backspace}${phone}`);
  }

  static fillMobilePhoneNumber(phone: string): void {
    cy.allure().logStep(`Fill contact mobile phone: ${phone}`);
    cy.get(selectors.mobilePhoneInput).first().clear();
    cy.get(selectors.mobilePhoneInput).first().type(`{backspace}${phone}`);
  }

  static fillWorkPhoneNumber(phone: string): void {
    cy.allure().logStep(`Fill contact mobile phone: ${phone}`);
    cy.get(selectors.workPhoneInput).first().clear();
    cy.get(selectors.workPhoneInput).first().type(`{backspace}${phone}`);
  }

  static checkCostFields(): void {
    cy.get(utilitySelector.bodySelector).then((body) => {
      if (body.find(selectors.useMyInfoCheckbox).length > 0) {
        this.clickUseMyInfoCheckbox();
        this.fillBillTo();
        this.fillDepartment();
        this.fillSubsidiary();
        this.fillRegion();
      }
    });
  }

  static clickUseMyInfoCheckbox(): void {
    cy.allure().logStep('Check the Use my information checkbox');
    cy.get(selectors.useMyInfoCheckbox).click();
  }

  static fillBillTo(): void {
    cy.allure().logStep(`Fill traveler bill to`);
    cy.get(utilitySelector.bodySelector).then((body) => {
      if (body.find(selectors.billTo).length) {
        cy.get(selectors.billTo).click();
        cy.get(selectors.dropDownContainer).within(() => {
          cy.get(selectors.dropdownOption).eq(0).click();
        });
      }
    });
  }

  static fillDepartment(): void {
    cy.allure().logStep(`Fill traveler department`);
    cy.get(utilitySelector.bodySelector).then((body) => {
      if (body.find(selectors.department).length) {
        cy.get(selectors.department).click();
        cy.get(selectors.dropDownContainer).within(() => {
          cy.get(selectors.dropdownOption).eq(0).click();
        });
      }
    });
  }
  static fillSubsidiary(): void {
    cy.allure().logStep(`Fill subsidiary`);
    cy.get(utilitySelector.bodySelector).then((body) => {
      if (body.find(selectors.subsidiary).length) {
        cy.get(selectors.subsidiary).click();
        cy.get(selectors.dropDownContainer).within(() => {
          cy.get(selectors.dropdownOption).eq(0).click();
        });
      }
    });
  }

  static fillRegion(): void {
    cy.allure().logStep(`Fill traveler department`);
    cy.get(utilitySelector.bodySelector).then((body) => {
      if (body.find(selectors.region).length) {
        cy.get(selectors.region).click();
        cy.get(selectors.dropDownContainer).within(() => {
          cy.get(selectors.dropdownOption).eq(0).click();
        });
      }
    });
  }

  static save(): void {
    this.clickOnSaveButton();
    cy.wait('@waitForCreateTraveler', Timeouts.MAX_TIMEOUT_120_SEC).then((xhr) => {
      expect(xhr.response?.statusCode, 'Created Traveler').to.equal(200);
    });
  }

  static edit(): void {
    this.clickOnSaveButton();
    cy.wait('@waitForEditTraveler', Timeouts.MAX_TIMEOUT_120_SEC).then((xhr) => {
      expect(xhr.response?.statusCode, 'Created Traveler').to.equal(200);
    });
  }

  private static clickOnSaveButton(): void {
    cy.get(selectors.saveButton).click();
    cy.get(selectors.saveButton).should('have.attr', 'aria-busy', 'true');
  }
  static addPhoneNumber(number: number) {
    ContactModal.visitPage();
    cy.allure().logStep(`Fill contact mobile phone: ${number}`);
    cy.get(selectors.mobilePhoneInput).first().type(`{selectall}{backspace}`);
    cy.get(selectors.mobilePhoneInput).first().type(`{backspace}${number}`);
    cy.get(selectors.saveChanges).click();
    cy.contains('Your Contact information was successfully updated');
  }
}
