import { Timeouts, currencyType, InvoiceCorrectionURL } from '@utility-lib/constants';
import { transactionType } from '@commerce-lib/constants';
const adminCredentials = Cypress.env('superAdmin').SUPER_ADMIN_PASSWORD;
const editPriceAmount = '8000';
const airlineFee = '1000';
const creditCardFee = '2000';
const ticketNumber = '087654_Exchange';
const exchangeAmount = '80.00';
const refundAmount = '2.00';
const resortFee = '10.00';
const dailyRate = '100.00';
const voided = '200.00';

const invoiceCorrectionToolSelectors = {
  //ToDo: we have ticket for changing the locators once it is done we will update the locators here: CM2-8851
  editInvoiceButton: 'button.MuiButton-root:contains("Edit invoice")',
  email: 'input[name="email"]',
  continue: 'button.MuiButton-root:contains("Continue")',
  textInput: '.MuiOutlinedInput-input-gNAmOY',
  searchInput: 'input[name="searchInvoiceNumber"]',
  reSyncButton: '.MuiButton-secondaryPrimary',
  reSyncSuccessMessage: 'Successfully resynced invoice',
  price: 'tbody.MuiTableBody-root tr.MuiTableRow-root td.price-col input',
  tax: 'tbody.MuiTableBody-root tr.MuiTableRow-root td.tax-col input',
  reviewAndSave:
    'div.MuiPaper-root div.MuiCardContent-root button.MuiButton-root.MuiButton-primary',
  publishButton:
    'button.MuiButton-root.MuiButton-primary.MuiButton-primaryPrimary.MuiButton-sizeMedium.MuiButton-primarySizeMedium',
  publishMessage: 'Your changes have been saved',
  root: 'tr.MuiTableRow-root td.MuiTableCell-root button.MuiButtonBase-root',
  addFee: 'Add fee',
  addTransactions: 'Add transaction',
  airlineFee: 'li.MuiMenuItem-root.MuiMenuItem-gutters:nth-child(1)',
  creditCardFee: 'li.MuiMenuItem-root.MuiMenuItem-gutters:nth-child(2)',
  airlineFeeInput:
    'tbody.MuiTableBody-root tr:nth-child(2) td.price-col input.MuiInputBase-input',
  creditCardFeeInput:
    'tbody.MuiTableBody-root tr:nth-child(3) td.price-col input.MuiInputBase-input',
  exchangeInput:
    'tbody.MuiTableBody-root tr:nth-child(4) td.price-col input.MuiInputBase-input',
  transactionType: 'div#mui-component-select-ticket_type',
  transactionList: 'ul.MuiMenu-list',
  ticketNumber: 'input[name="ticket_number"]',
  save: 'button[type="submit"]',
  close: '.MuiPaper-root .MuiCardContent-root button',
  delete: '.delete-col button',
  trainRefundRoot: 'tbody.sc-ivtrNa.gcQLFK',
  trainRefund: 'input.sc-iKOlBE.sc-hsaIhh.gVfLSa.MuiInputBase-input.MuiInput-input',
  trainTransactionSubmit: 'button[type="submit"]',
  hotelDailyRate: ' Add Daily Rate',
  hotelInputs: 'input[type="text"].MuiInputBase-input',
  hotelAddTransaction: 'Add transaction',
  hotelDropDown: 'div[id="mui-component-select-ticket_type"]',
  hotelDropDownList: 'ul.MuiList-root'
};
export class InvoiceCorrectionToolValidation {
  static clickOnEditButton() {
    cy.get(invoiceCorrectionToolSelectors.editInvoiceButton).should('be.visible').click();
  }
  static loginCorrectionTool(email: string) {
    cy.allure().logStep('Login page for correction tool');
    cy.get(invoiceCorrectionToolSelectors.email).type(email);
    cy.get(invoiceCorrectionToolSelectors.continue).click();
    cy.get(invoiceCorrectionToolSelectors.textInput).eq(1).type(adminCredentials);
    cy.get(invoiceCorrectionToolSelectors.continue).click();
  }
  static passBookingID() {
    cy.allure().logStep('Passing Booking ID');
    cy.task<string>('getDataFromCache', 'bookingID').then((flightBookingId) => {
      cy.get(invoiceCorrectionToolSelectors.searchInput).type(flightBookingId);
    });
  }
  static searchBookingForEdit() {
    cy.allure().logStep('Search booking for Edit');
    InvoiceCorrectionToolValidation.passBookingID();
    InvoiceCorrectionToolValidation.clickOnEditButton();
  }
  static shouldSeeFlightTicketNumber() {
    cy.allure().logStep('Should see flight ticket number');
    cy.task<string>('getDataFromCache', 'ticketNumber').then((ticketNumber) => {
      cy.log('Ticket Number:', ticketNumber);
      cy.contains(ticketNumber.trim());
    });
  }
  static reSyncInvoice() {
    cy.allure().logStep('Re-sync invoice');
    cy.get(invoiceCorrectionToolSelectors.reSyncButton).click();
    cy.contains(invoiceCorrectionToolSelectors.reSyncSuccessMessage);
  }
  static totalPrice() {
    cy.allure().logStep('Should see Total price');
    cy.task<string>('getDataFromCache', 'flightBookingTotalCharges').then(
      (total: any) => {
        cy.task<string>('getDataFromCache', 'tripFee').then((tripFee: any) => {
          const strippedAmount = total.replace(/[^0-9]/g, '').trim();
          const strippedTripFee = tripFee.replace(/[^0-9]/g, '').trim();
          cy.log('Total:', strippedAmount.trim());
          cy.log('Trip Fee:', strippedTripFee.trim());
          const totalCharges = strippedAmount - strippedTripFee;
          cy.log('Total Charges:', totalCharges);
          cy.contains(totalCharges);
        });
      }
    );
  }
  static editPrice() {
    cy.allure().logStep('Edit the booking price');
    cy.get(invoiceCorrectionToolSelectors.price).clear();
    cy.get(invoiceCorrectionToolSelectors.price)
      .invoke('val', '{home}{rightarrow}')
      .type(editPriceAmount);
  }
  static updatedTotalPrice() {
    cy.allure().logStep('updated Total price');
    return new Cypress.Promise((resolve) => {
      let priceAmount: any;
      let taxAmount: any;

      cy.get(invoiceCorrectionToolSelectors.price)
        .invoke('val')
        .then((price) => {
          if (price) {
            const priceWithoutCurrency = String(price).replace(
              new RegExp(`[${currencyType.join('')}]`, 'g'),
              ''
            );
            priceAmount = parseFloat(priceWithoutCurrency);
            cy.log('Updated Price:', price);
          } else {
            priceAmount = 0;
            cy.log('Price is undefined. Setting it to 0.');
          }
        });

      cy.get(invoiceCorrectionToolSelectors.tax)
        .invoke('val')
        .then((tax) => {
          if (tax) {
            const taxWithoutCurrency = String(tax).replace(
              new RegExp(`[${currencyType.join('')}]`, 'g'),
              ''
            );
            taxAmount = parseFloat(taxWithoutCurrency);
            cy.log('Updated Tax:', tax);
          } else {
            taxAmount = 0;
            cy.log('Tax is undefined. Setting it to 0.');
          }
        });

      cy.then(() => {
        if (priceAmount !== undefined && taxAmount !== undefined) {
          const totalPrice = priceAmount + taxAmount;
          cy.log('Updated Total Price:', totalPrice);
          resolve(totalPrice); // Resolving the promise with totalPrice value
          cy.contains(totalPrice);
        } else {
          cy.log(
            'One or both values are undefined. Unable to calculate the updated total price.'
          );
          resolve(null); // Resolving the promise with null value
        }
      });
    });
  }
  static SaveChanges() {
    cy.allure().logStep('Publishing the changes made');
    cy.get(invoiceCorrectionToolSelectors.reviewAndSave).click();
    cy.get(invoiceCorrectionToolSelectors.publishButton).click();
    cy.contains(invoiceCorrectionToolSelectors.publishMessage);
  }
  static addFeeTransaction() {
    cy.allure().logStep('Adding fee transaction');
    cy.get(invoiceCorrectionToolSelectors.root)
      .contains(invoiceCorrectionToolSelectors.addFee)
      .click();
    cy.get(invoiceCorrectionToolSelectors.airlineFee).click();
    cy.get(invoiceCorrectionToolSelectors.airlineFeeInput).clear();
    cy.get(invoiceCorrectionToolSelectors.airlineFeeInput)
      .invoke('val', '{home}{rightarrow}')
      .type(airlineFee);
  }
  static addCreditCardFeeTransaction() {
    cy.allure().logStep('adding credit card fee transaction');
    cy.get(invoiceCorrectionToolSelectors.root)
      .contains(invoiceCorrectionToolSelectors.addFee)
      .click();
    cy.get(invoiceCorrectionToolSelectors.airlineFee).click();
    cy.get(invoiceCorrectionToolSelectors.creditCardFeeInput).clear();
    cy.get(invoiceCorrectionToolSelectors.creditCardFeeInput)
      .invoke('val', '{home}{rightarrow}')
      .type(creditCardFee);
  }
  static addExchangeTransaction() {
    cy.allure().logStep('adding exchange transaction');
    cy.get(invoiceCorrectionToolSelectors.root)
      .contains(invoiceCorrectionToolSelectors.addTransactions)
      .click();
    cy.get(invoiceCorrectionToolSelectors.transactionType).click();
    cy.get(invoiceCorrectionToolSelectors.transactionList)
      .contains('li', 'EXCHANGE')
      .click();
    cy.get(invoiceCorrectionToolSelectors.ticketNumber).type(ticketNumber);
    cy.get('button[type="submit"]').contains(transactionType.Save).click();
    cy.get(invoiceCorrectionToolSelectors.exchangeInput).clear();
    cy.get(invoiceCorrectionToolSelectors.exchangeInput)
      .invoke('val', '{home}{rightarrow}')
      .type(exchangeAmount);
  }
  static addTrainRefundTransaction() {
    cy.allure().logStep('adding Train Refund transaction');
    cy.get(invoiceCorrectionToolSelectors.root)
      .contains(invoiceCorrectionToolSelectors.addTransactions)
      .click();
    cy.get(invoiceCorrectionToolSelectors.transactionType).click();
    cy.get(invoiceCorrectionToolSelectors.transactionList)
      .contains('li', transactionType.REFUND)
      .click();
    cy.get(invoiceCorrectionToolSelectors.ticketNumber).type(ticketNumber);
    cy.get(invoiceCorrectionToolSelectors.trainTransactionSubmit)
      .contains(transactionType.Save)
      .click();
    cy.get(invoiceCorrectionToolSelectors.trainRefundRoot)
      .find(invoiceCorrectionToolSelectors.trainRefund)
      .eq(2)
      .type('{home}{rightarrow}' + refundAmount);
  }
  static deleteTransaction() {
    cy.allure().logStep('deleting transaction');
    cy.get(invoiceCorrectionToolSelectors.close).contains('Close').click();
    InvoiceCorrectionToolValidation.searchBookingForEdit();
    cy.get(invoiceCorrectionToolSelectors.delete).eq(1).click();
    InvoiceCorrectionToolValidation.SaveChanges();
  }
  static editResortFee() {
    cy.allure().logStep('edit resort fee');
    cy.get(invoiceCorrectionToolSelectors.hotelInputs)
      .eq(0)
      .type('{home}{rightarrow}' + resortFee);
  }
  static editHotelPriceAmount() {
    cy.allure().logStep('edit hotel price amount');
    cy.get(invoiceCorrectionToolSelectors.hotelInputs).eq(1).clear();
    cy.get(invoiceCorrectionToolSelectors.hotelInputs)
      .eq(1)
      .type('{home}{rightarrow}' + dailyRate);
  }
  static addDailyRateTransaction() {
    cy.allure().logStep('add daily rate transaction');
    cy.contains(invoiceCorrectionToolSelectors.hotelDailyRate).click();
    cy.get(invoiceCorrectionToolSelectors.hotelInputs)
      .last()
      .type('{home}{rightarrow}' + dailyRate);
  }
  static checkTotalPrice() {
    cy.allure().logStep('Check total price:');
    cy.task<string>('getDataFromCache', 'totalPrice').then((totalPrice) => {
      const priceWithoutDecimals = totalPrice.split('.')[0];
      const priceWithoutCommas = priceWithoutDecimals.replace(/,/g, '');
      const regex = new RegExp(`^\\${priceWithoutCommas}`);
      cy.contains(regex).should('exist');
    });
  }
  static addHotelChargeTransaction() {
    cy.allure().logStep('add daily rate transaction');
    cy.contains(invoiceCorrectionToolSelectors.hotelAddTransaction).click();
    cy.get(invoiceCorrectionToolSelectors.hotelDropDown).click();
    cy.get(invoiceCorrectionToolSelectors.hotelDropDownList)
      .contains('li', transactionType.CHARGE)
      .click();
    cy.get(invoiceCorrectionToolSelectors.save).contains(transactionType.Save).click();
    cy.get(invoiceCorrectionToolSelectors.hotelInputs)
      .last()
      .type('{home}{rightarrow}' + dailyRate);
  }
  static addHotelVoidedTransaction() {
    cy.allure().logStep('add Voided transaction');
    cy.contains(invoiceCorrectionToolSelectors.hotelAddTransaction).click();
    cy.get(invoiceCorrectionToolSelectors.hotelDropDown).click();
    cy.get(invoiceCorrectionToolSelectors.hotelDropDownList)
      .contains('li', transactionType.VOIDED)
      .click();
    cy.get(invoiceCorrectionToolSelectors.save).contains(transactionType.Save).click();
    cy.get(invoiceCorrectionToolSelectors.hotelInputs)
      .last()
      .type('{home}{rightarrow}' + voided);
  }
  static addHotelResortFeeTransaction() {
    cy.allure().logStep('add Voided transaction');
    cy.contains(invoiceCorrectionToolSelectors.hotelAddTransaction).click();
    cy.get(invoiceCorrectionToolSelectors.hotelDropDown).click();
    cy.get(invoiceCorrectionToolSelectors.hotelDropDownList)
      .contains('li', transactionType.RESORT_FEE)
      .click();
    cy.get(invoiceCorrectionToolSelectors.save).contains(transactionType.Save).click();
    cy.get(invoiceCorrectionToolSelectors.hotelInputs)
      .last()
      .type('{home}{rightarrow}' + resortFee);
  }
}
export const visitInvoiceCorrectionTool = () => {
  cy.allure().logStep('visit invoice correction tool');
  cy.visit(InvoiceCorrectionURL);
  cy.wait(Timeouts.SHORT_TIMEOUT_3_SEC.timeout);
};
