import { utilitySelector, Timeouts, InputDelays } from '@utility-lib/index';
import {
  UnderWritingApplications,
  underWritingSubmittedApplicationsSelectors
} from '@lrm-lib/underwriting_applications';
import { stagingUsers } from '@fixtures/staging-users';

const liquidUpgradeSelectors = {
  UpgradeLiquidToSelfSellUser: '.testimonials',
  startApplication: '.footer button span',
  companyWebsite: '[data-testid="companyWebsiteInput"]',
  businessLegalName: '[data-testid="businessLegalNameInput"]',
  businessLegalNameInput: '[data-testid="businessLegalNameInput"] input',
  companyWebsiteInput: '[data-testid="companyWebsiteInput"] input',
  phoneNumberInput: '[data-testid=businessPhoneNumberInput] input',
  legalEntityOption: '[data-testid="legalEntityTypeInput"]',
  numberOfEmployees: '[formcontrolname="numberOfEmployees"]',
  numberOfEmployeesInput: '[data-testid=numberOfEmployeesInput] input',
  ein: '[data-testid=taxIdInput]',
  einInput: '[data-testid=einInput] input',
  configureCompanyState: '[data-testid="configureCompanyState"]',
  configureCompanyCountry: '[data-testid="configureCompanyCountry"] input',
  submitApplication: '.travel-form [data-testid="submitApplicationButton"]',
  formSavePrimary: '.form-save-buttons .primary',
  formSave: '.form-save-buttons',
  submitApplicationButton: '.app-section-content [data-testid="submitApplicationButton"]',
  ownershipSubmitApplication:
    '.app-section-content.ownership-info [data-testid="submitApplicationButton"]',
  submitExpenseAdditionalDetailButton:
    '[data-testid="submitExpenseAddionalDetailsButton"]',
  ownershipSubmitConfirmButton: '.tal-modal.mobile-info-modal button.primary',
  connectBankPlaidButton: '.expense-bank-info button.primary span',
  connectBankInstantlyButton: '.expense-bank-info button.primary span',
  connectBankManuallyButton: '.expense-bank-info button.secondary span',
  legalEntityTypeClick: '[data-testid=label-Legal-entity-type]',
  legalEntityTypeClickInput: '[data-testid=label-Legal-entity-type] input',
  legalEntityTypeClose:
    '.expense-additional-details__form [data-testid=legalEntityTypeInput] .icon-chevron-bottom',
  legalIndustryName: '[data-testid=industryNameInput]',
  legalIndustryNameInput: '[data-testid=industryNameInput] input',
  legalIndustryNameClose:
    '.expense-additional-details__form [data-testid=industryNameInput] .icon-chevron-bottom',
  annualRevenueName: '[data-testid=anualRevenueInput]',
  annualRevenueNameInput: '[data-testid=anualRevenueInput] input',
  annualRevenueNameClose:
    '.expense-additional-details__form [data-testid=anualRevenueInput] .icon-chevron-bottom',
  monthlyCardSpent: '[data-testid=averageMonthlyCardSpendInput]',
  monthlyCardSpentInput: '[data-testid=averageMonthlyCardSpendInput] input',
  verticalIndustry: '[data-testid="label-Vertical-or-industry"]',
  legalEntityTypeDropDown: '[data-testid=label-Legal-entity-type] > span > input',
  configureCompanyPhone: 'ta-phone-input-v2 input:first',
  termsAndConditionCheck: '[data-testid="termsAndConditionCheck"] input',
  configureCompanyAccount: '[data-testid="configureCompanyAccount"]',
  dropdownOption: '.ta-select-option',
  countrySelectOption: '.mat-option-text',
  accountHolderName: '[formcontrolname="accountHolderName"]',
  currencyForm: '[formcontrolname="currency"] .p-radiobutton',
  currencyFormButton: '.footer .primary',
  routingNumber: '[formcontrolname="routingNumber"]',
  accountNumber: '[formcontrolname="accountNumber"]',
  confirmAccountNumber: '[formcontrolname="confirmAccountNumber"]',
  browseBankStatements: '.browse',
  submitBankInformationButton: '.expense-bank-info .secondary',
  givenName: '[formcontrolname="givenName"]',
  familyName: '[formcontrolname="familyName"]',
  email: '[formcontrolname="email"]',
  title: '[formcontrolname="title"]',
  titleInput: '[formcontrolname="title"]',
  titleClose: '.app-section-content [formcontrolname="title"] .icon-chevron-bottom',
  addressLine: '.app-section-content [formcontrolname="line1"]',
  homeAddressaddressLine: '[formcontrolname="homeAddress"] [formcontrolname="line1"]',
  city: '.app-section-content [formcontrolname="city"]',
  homeAddresscity: '[formcontrolname="homeAddress"] [formcontrolname="city"]',
  addressState: '.app-section-content [data-testid="addressStateInput"]',
  homeAddressAddressState:
    '[formcontrolname="homeAddress"] [data-testid="addressStateInput"]',
  addressStateInput: '.app-section-content [formcontrolname="addressStateInput"]',
  homeAddressAaddressStateInput:
    '[formcontrolname="homeAddress"] [formcontrolname="addressStateInput"]',
  addressStateClose:
    '.app-section-content [data-testid="addressStateInput"] .icon-chevron-bottom',
  homeAddressaddressStateClose:
    '[formcontrolname="homeAddress"] [data-testid="addressStateInput"] .icon-chevron-bottom',
  addressPostalCodeInput: '.app-section-content [data-testid="addressPostalCodeInput"]',
  homeAddressaddressPostalCodeInput:
    '[formcontrolname="homeAddress"] [data-testid="addressPostalCodeInput"]',
  homeAddressstateDropDown: '[formcontrolname="homeAddress"] [data-testid="label-State"]',
  stateDropDown: '[data-testid="label-State"]',
  phoneNumber: '.app-section-content [formcontrolname="phoneNumber"]',
  dob: '.app-section-content [formcontrolname="dob"]',
  dobYearPicker: '.app-section-content .calendar-wrapper .p-datepicker-year',
  dobYearPickerLeftArrow: '.p-datepicker-prev',
  selectYearPicker: '.p-yearpicker span',
  selectMonthPicker: '.p-monthpicker span',
  selectDayPicker: '.p-datepicker-calendar .p-ripple',
  ssn: '.app-section-content [formcontrolname="ssnLast4"]',
  iframe: '[id="plaid-link-iframe-1"]',
  continueToPlaid: '[id="aut-button"]',
  bankOptions: '.SearchAndSelectPane-module__resultButton',
  userInfo: '#aut-input-0',
  passInfo: '#aut-input-1',
  checkingAccount: '#aut-selection-0',
  continue: '#aut-button',
  getCodeClickButton: '#submit-device',
  termCheckBox: '[data-testid=termsCheckbox]',
  authExecCheckbox: '[data-testid=isAuthorizedExecutive]',
  connectYourBankSubmitButton: '.submission-info__form .submit-button',
  submitButton: '[data-testid="submitButton"]',
  searchForUnderWritingCompanies:
    '.content-container .filter-container .search-input-wrapper input',
  dataFromTableUnderwritingResult: '.content-container .ng-star-inserted .company',
  confirmationTravelPage: '.approved-status-container .secondary',
  dropDownOptions: '.options-wrapper',
  rambleScript: '#rambleScript'
};
const { superAdmin } = stagingUsers;
const superAdminCredentials = Cypress.env('superAdmin').SUPER_ADMIN_PASSWORD;
const email = superAdmin.email;

export class UpgradeLiquidToSelfSellUser {
  static upgradeSelfSellValidationFlow(connectBankCheck: string, flow: string) {
    UnderWritingApplications.selectSubmittedApplication();
    if (connectBankCheck === 'instantly' || connectBankCheck === 'microdeposit') {
      UnderWritingApplications.validateSubmitDetails({
        liquidStatus: 'manual_review',
        requestedSpendLimit: '$15,000.00',
        monthlyCardSpent: '$10,000.00'
      });
    } else if (flow === 'approved') {
      UnderWritingApplications.validateApproveLiquidDetails(connectBankCheck);
      UnderWritingApplications.validateSubmitDetails({
        liquidStatus: 'approved',
        requestedSpendLimit: '$15,000.00',
        monthlyCardSpent: '$10,000.00'
      });
    } else if (flow === 'pending') {
      UnderWritingApplications.validateSubmitDetails({
        liquidStatus: 'pending',
        requestedSpendLimit: '$15,000.00',
        monthlyCardSpent: '$10,000.00'
      });
    } else {
      UnderWritingApplications.validateSubmitDetails({
        liquidStatus: 'declined',
        requestedSpendLimit: '$15,000.00',
        monthlyCardSpent: '$10,000.00'
      });
    }
  }

  static getTripUuidFromSearchUrlAndCache() {
    cy.url().then((url: string) => {
      expect(url, 'page url should include search part').include(
        '/underwriting/companies'
      );
      const match = url.match('companies/([^&]*)');
      const selfSellCompanyApplicationID = match && match[1];
      expect(selfSellCompanyApplicationID, 'tripUuid should be in url query').not.be.null;
      cy.task('putDataInCache', {
        key: 'selfSellCompanyApplicationID',
        data: selfSellCompanyApplicationID
      });
    });
  }

  static upgradeSelfSellConnectYourBank(connectBankCheck: string, flow: string) {
    this.visitSelfOnboardingLiquidUpgradePage();
    this.clickUpgradeLiquidToSelfSellUser();
    this.fillBusinessContactDetails();
    this.fillExecutiveLeadershipForm();
    this.submitOwnerShipApplication();
    if (connectBankCheck === 'plaid') {
      this.connectToBank();
      this.loginToPlaid();
      this.selectBankAccount();
    } else {
      this.submitYourManualApplication();
    }
    this.connectWithYourBankSuccessfully();
    this.loginToUWDashboardAndValidate(connectBankCheck, flow);
  }

  static loginToUWDashboardAndValidate(connectBankCheck: string, flow: string) {
    UnderWritingApplications.loginToUnderWritingAndValidateCompanyStatus(
      email,
      superAdminCredentials
    );
    UpgradeLiquidToSelfSellUser.upgradeSelfSellValidationFlow(connectBankCheck, flow);
  }

  static visitSelfOnboardingLiquidUpgradePage() {
    cy.allure().logStep('Visit Self Onboarding Liquid Upgrade Page');
    cy.visit('app/self-onboarding/liquid_upgrade');
    cy.url().should('include', '/liquid_upgrade');
  }

  static clickUpgradeLiquidToSelfSellUser(): void {
    cy.allure().logStep('Liquid Upgrade To Self Sell Growth User ');
    cy.get(liquidUpgradeSelectors.UpgradeLiquidToSelfSellUser)
      .then((button) => {
        cy.wrap(button).find(utilitySelector.buttonSelector).should('be.visible').click();
      })
      .then(() => {
        cy.get(liquidUpgradeSelectors.startApplication).should('be.visible').click();
      });
    cy.url().should('include', 'app/self-onboarding/begin/upsell');
  }

  static fillBusinessContactDetails(): void {
    cy.get(liquidUpgradeSelectors.currencyForm).eq(0).click();
    cy.get(liquidUpgradeSelectors.currencyFormButton).click();
    cy.get(liquidUpgradeSelectors.legalEntityTypeClickInput).then((ele) => {
      cy.wrap(ele).wait(Timeouts.SHORT_TIMEOUT_3_SEC.timeout).clear({
        force: true
      });
      cy.wrap(ele).type('Partnerships{enter}');
    });
    cy.allure().logStep('Fill Business Contact Details');
    cy.task('getDataFromCache', 'companyDomain').then((companyDomain: any) => {
      cy.get(liquidUpgradeSelectors.companyWebsite)
        .then((button) => {
          cy.wrap(button).should('be.visible').click();
        })
        .then(() => {
          cy.get(liquidUpgradeSelectors.companyWebsiteInput).then((ele) => {
            cy.wrap(ele).should('be.visible');
            cy.wrap(ele).clear();
            cy.wrap(ele).type(
              companyDomain.toLowerCase(),
              InputDelays.INPUT_DELAY_100_MILLIS
            );
          });
        });
    });

    cy.task('getDataFromCache', 'companyName').then((companyName: any) => {
      cy.get(liquidUpgradeSelectors.businessLegalName)
        .then((button) => {
          cy.wrap(button).should('be.visible').click();
        })
        .then(() => {
          cy.get(liquidUpgradeSelectors.businessLegalNameInput).then((ele) => {
            cy.wrap(ele).should('be.visible');
            cy.wrap(ele).clear();
            cy.wrap(ele).type(companyName, InputDelays.INPUT_DELAY_100_MILLIS);
          });
        });
    });
    cy.get(liquidUpgradeSelectors.phoneNumberInput).then((ele) => {
      cy.wrap(ele).should('be.visible');
      cy.wrap(ele).clear();
      cy.wrap(ele).type('{backspace}4312312312', InputDelays.INPUT_DELAY_100_MILLIS);
    });

    cy.get(liquidUpgradeSelectors.addressLine).then((ele) => {
      cy.wrap(ele).should('be.visible').click();
      cy.wrap(ele).type('3045 Park Blvd{enter}', InputDelays.INPUT_DELAY_100_MILLIS);
    });

    cy.get(liquidUpgradeSelectors.city)
      .should('be.visible')
      .type('{backspace}Palo Alto', InputDelays.INPUT_DELAY_100_MILLIS);
    cy.get(liquidUpgradeSelectors.addressState)
      .then((ele) => {
        cy.wrap(ele).should('be.visible');
        cy.wrap(ele).click();
        cy.wait(Timeouts.SHORT_TIMEOUT_3_SEC.timeout);
      })

      .then(() => {
        cy.get(liquidUpgradeSelectors.stateDropDown)
          .should('be.visible')
          .contains('California')
          .click();
      });
    cy.get(liquidUpgradeSelectors.addressStateClose).should('be.visible').click();
    cy.get(liquidUpgradeSelectors.addressPostalCodeInput)
      .should('be.visible')
      .type('{backspace}94035');

    cy.get(liquidUpgradeSelectors.numberOfEmployees).type('10');
    cy.get(liquidUpgradeSelectors.ein).type(
      '123456789',
      InputDelays.INPUT_DELAY_100_MILLIS
    );
    cy.get(liquidUpgradeSelectors.legalIndustryNameInput).then((ele) => {
      cy.wrap(ele).wait(Timeouts.SHORT_TIMEOUT_3_SEC.timeout).clear({
        force: true
      });
      cy.wrap(ele).type('Construction{enter}');
    });
    cy.get(liquidUpgradeSelectors.annualRevenueNameInput).then((ele) => {
      cy.wrap(ele).wait(Timeouts.SHORT_TIMEOUT_3_SEC.timeout).clear({
        force: true
      });
      cy.wrap(ele).type('$1,000,000 - $10,000,000{enter}');
    });
    cy.get(liquidUpgradeSelectors.monthlyCardSpent)
      .then((ele) => {
        cy.wrap(ele).click();
      })
      .then(() => {
        cy.get(liquidUpgradeSelectors.monthlyCardSpentInput).type(
          '{backspace}10000',
          InputDelays.INPUT_DELAY_100_MILLIS
        );
      });
    cy.get(liquidUpgradeSelectors.formSavePrimary).click();
    // cy.get(liquidUpgradeSelectors.submitApplication).click();
    // cy.get(underWritingSubmittedApplicationsSelectors.toastSummaryMessageDetails)
    //   .should('be.visible')
    //   .contains('Your information was successfully saved');
  }

  static fillBusinessInformationForSelfSellUser(): void {
    cy.allure().logStep('Fill Business Information For Self SellUser');
    cy.get(liquidUpgradeSelectors.legalEntityTypeClickInput)
      .then((ele) => {
        cy.wrap(ele).wait(Timeouts.SHORT_TIMEOUT_3_SEC.timeout).clear({
          force: true
        });
        cy.wrap(ele).type('Partnerships');
      })

      .then(() => {
        cy.get(liquidUpgradeSelectors.dropDownOptions).click({ force: true });
      });
    cy.get(liquidUpgradeSelectors.submitExpenseAdditionalDetailButton).click();
    // cy.get(underWritingSubmittedApplicationsSelectors.toastSummaryMessageDetails)
    //   .should('be.visible')
    //   .contains('Your information was successfully saved');
  }

  static fillExecutiveLeadershipForm(): void {
    cy.allure().logStep('Fill Executive Leadership Form');
    cy.get(liquidUpgradeSelectors.authExecCheckbox).eq(0).click();
    cy.get(liquidUpgradeSelectors.givenName)
      .should('be.visible')
      .type('{backspace}Underwriting');
    cy.get(liquidUpgradeSelectors.familyName)
      .should('be.visible')
      .type('{backspace}Automation', InputDelays.INPUT_DELAY_100_MILLIS);
    cy.task('getDataFromCache', 'userEmail').then((userEmail) => {
      cy.get(liquidUpgradeSelectors.email)
        .should('be.visible')
        .type('{backspace}' + userEmail, InputDelays.INPUT_DELAY_100_MILLIS);
    });
    cy.get(liquidUpgradeSelectors.title).should('be.visible').click();
    cy.get(liquidUpgradeSelectors.dropDownOptions).contains('CEO').click();
    cy.wait(Timeouts.SHORT_TIMEOUT_3_SEC.timeout);

    cy.get(liquidUpgradeSelectors.homeAddressaddressLine).then((ele) => {
      cy.wrap(ele).should('be.visible').click();
      cy.wrap(ele).type('3045 Park Blvd{enter}', InputDelays.INPUT_DELAY_100_MILLIS);
    });

    cy.get(liquidUpgradeSelectors.homeAddresscity)
      .should('be.visible')
      .type('{backspace}Palo Alto', InputDelays.INPUT_DELAY_100_MILLIS);
    cy.get(liquidUpgradeSelectors.homeAddressAddressState)
      .then((ele) => {
        cy.wrap(ele).should('be.visible');
        cy.wrap(ele).click();
        cy.wait(Timeouts.SHORT_TIMEOUT_3_SEC.timeout);
      })

      .then(() => {
        cy.get(liquidUpgradeSelectors.homeAddressstateDropDown)
          .should('be.visible')
          .contains('California')
          .click();
      });
    cy.get(liquidUpgradeSelectors.homeAddressaddressStateClose)
      .should('be.visible')
      .click();
    cy.get(liquidUpgradeSelectors.homeAddressaddressPostalCodeInput)
      .should('be.visible')
      .type('{backspace}94035');
    cy.get(liquidUpgradeSelectors.phoneNumber)
      .should('be.visible')
      .type('{backspace}4088884848');
    cy.get(liquidUpgradeSelectors.dob).then((ele) => {
      cy.wrap(ele).should('be.visible').click();
      cy.wait(Timeouts.SHORT_TIMEOUT_3_SEC.timeout);
    });
    cy.get(liquidUpgradeSelectors.dobYearPicker).should('be.visible').click();
    cy.get(liquidUpgradeSelectors.dob).should('be.visible').click();
    const leftArrowSelector = liquidUpgradeSelectors.dobYearPickerLeftArrow;
    for (let i = 0; i < 4; i++) {
      cy.get(leftArrowSelector).should('be.visible').click();
      cy.get(leftArrowSelector).should('be.visible');
    }
    cy.get(liquidUpgradeSelectors.selectYearPicker).should('be.visible').eq(2).click();
    cy.get(liquidUpgradeSelectors.selectMonthPicker).should('be.visible').eq(2).click();
    cy.wait(Timeouts.SHORT_TIMEOUT_3_SEC.timeout);
    cy.get(liquidUpgradeSelectors.selectDayPicker).should('be.visible').eq(15).click();
    cy.get(liquidUpgradeSelectors.ssn)
      .should('be.visible')
      .type('{backspace}3321', InputDelays.INPUT_DELAY_100_MILLIS);
    cy.get(liquidUpgradeSelectors.submitApplicationButton).should('be.visible').click();
    // cy.get(underWritingSubmittedApplicationsSelectors.toastSummaryMessageDetails) // it's an issue need to uncomment after its resolved
    //     .should('be.visible')
    //     .contains('Your information was successfully saved');
  }

  static connectWithYourBankSuccessfully() {
    cy.allure().logStep('connect With Your Bank Successfully');
    cy.get(liquidUpgradeSelectors.termCheckBox).last().should('be.visible').click();
    cy.get(liquidUpgradeSelectors.connectYourBankSubmitButton)
      .should('be.visible')
      .click();
    cy.get(liquidUpgradeSelectors.confirmationTravelPage)
      .should('be.visible')
      .contains('Go back to Navan');
    cy.wait('@upsellLiquidApplication');
    cy.wait(Timeouts.MEDIUM_TIMEOUT_20_SEC.timeout);
  }

  static submitOwnerShipApplication() {
    cy.allure().logStep('Submit OwnerShip Application');
    cy.get(liquidUpgradeSelectors.ownershipSubmitApplication)
      .should('be.visible')
      .click();
    cy.get(liquidUpgradeSelectors.ownershipSubmitConfirmButton)
      .should('be.visible')
      .click();
    cy.wait('@ownerShipInfoApplication');
    cy.log('@ownerShipInfoApplication');
  }

  static loginToPlaid() {
    cy.allure().logStep('login To Plaid');
    this.getIframeBody()
      .find(liquidUpgradeSelectors.userInfo)
      .should('be.visible')
      .type('user_good');
    this.getIframeBody()
      .find(liquidUpgradeSelectors.passInfo)
      .should('be.visible')
      .type('pass_good');
    this.getIframeBody()
      .find(liquidUpgradeSelectors.continue)
      .should('be.visible')
      .click();
  }

  static selectBankAccount() {
    cy.allure().logStep('select Bank Account');
    this.getIframeBody()
      .find(liquidUpgradeSelectors.checkingAccount)
      .should('be.visible')
      .click();
    this.getIframeBody()
      .find(liquidUpgradeSelectors.continue)
      .should('be.visible')
      .click();
  }

  static submitYourManualApplication() {
    cy.allure().logStep('submit Your Manual Application');
    cy.get(liquidUpgradeSelectors.connectBankManuallyButton).should('be.visible').click();
    cy.get(liquidUpgradeSelectors.accountHolderName)
      .should('be.visible')
      .type('{backspace}TestAccount');
    cy.get(liquidUpgradeSelectors.routingNumber)
      .should('be.visible')
      .type('{backspace}052001633');
    cy.get(liquidUpgradeSelectors.accountNumber).type('{backspace}000123456789');
    cy.get(liquidUpgradeSelectors.confirmAccountNumber).type('{backspace}000123456789');
    this.uploadReceiptToBankManualFlow('cypress/fixtures/lrm/BankStatementPDF1.pdf');
    this.uploadReceiptToBankManualFlow('cypress/fixtures/lrm/BankStatementPDF2.pdf');
    this.uploadReceiptToBankManualFlow('cypress/fixtures/lrm/BankStatementPDF3.pdf');
    cy.get(liquidUpgradeSelectors.submitBankInformationButton)
      .should('be.visible')
      .click();
    cy.wait(Timeouts.MEDIUM_TIMEOUT_10_SEC.timeout);
  }

  static uploadReceiptToBankManualFlow(receiptFilePath: string) {
    cy.allure().logStep('ReceiptFilePath' + receiptFilePath);
    cy.get(liquidUpgradeSelectors.browseBankStatements)
      .should('be.visible')
      .selectFile(receiptFilePath, {
        action: 'drag-drop'
      });
  }

  static connectToBank() {
    cy.allure().logStep('Connect To Bank');
    cy.wait(Timeouts.SHORT_TIMEOUT_3_SEC.timeout);
    cy.get(liquidUpgradeSelectors.connectBankPlaidButton).should('be.visible').click();
    cy.log('@waitForLRMToken');
    cy.wait('@waitForLRMToken');
    this.getIframeBody()
      .find(liquidUpgradeSelectors.continueToPlaid)
      .click({ force: true });
    this.getIframeBody()
      .find(liquidUpgradeSelectors.continueToPlaid)
      .click({ force: true });
    this.getIframeBody()
      .find(liquidUpgradeSelectors.bankOptions)
      .should('be.visible')
      .contains('TD Bank')
      .scrollIntoView()
      .click();
  }

  static getIframeDocument() {
    return cy.get(liquidUpgradeSelectors.iframe).its('0.contentDocument').should('exist');
  }

  static getIframeBody() {
    return this.getIframeDocument()
      .its(utilitySelector.bodySelector)
      .should('not.be.undefined')
      .then(cy.wrap);
  }
}
