import { Locator, Page } from "@playwright/test";
import { BasePage } from "./BasePage";
import { IClaimDetails, IPaymentDetails } from "@business-logic/types/CustomerDetails";
import { ServicePackage } from "@business-logic/types/Enums";

export class AfterpayPage extends BasePage {
    readonly page: Page;
    
    readonly passwordTextBox: Locator;
    readonly submitButton: Locator;
    readonly confirmButton: Locator;

    readonly selectAfterpayWithInterestButton: Locator;
    readonly selectAfterpayWithoutInterestButton: Locator;
    readonly continueAfterpayButton: Locator;

    constructor(page: Page) {
        super(page);
        this.page = page;
        this.passwordTextBox = page.getByTestId('login-password-input');
        this.submitButton = page.getByRole('button', { name: 'Continue' });
        this.confirmButton = page.getByRole('button', { name: 'Confirm' });

        // Monthly with interest option
        this.selectAfterpayWithInterestButton = page.getByRole('radio', { name: /month/ });
        // Biweekly without interest option
        this.selectAfterpayWithoutInterestButton = page.getByTestId('payment-types-label').filter({ hasText: /every 2 weeks/ });
        this.continueAfterpayButton = page.getByRole('button', { name: 'Continue' });
    }

    async login(password: string) {
        await this.passwordTextBox.fill(password);
        await this.submitButton.click();
    }

    async executeAfterpayPayment(paymentDetails: IPaymentDetails, claimDetails: IClaimDetails, servicePackage: ServicePackage) {

        const confirmButtonOrPaymentOptions = this.confirmButton.or(this.selectAfterpayWithoutInterestButton);
        
        await this.login(paymentDetails.password!);

        await this.page.locator('div[data-testid=\'loading-icon-svg\']').filter({ visible: true}).first().waitFor({ state: 'hidden' });
        await confirmButtonOrPaymentOptions.waitFor({ state: 'visible' });

        if (await this.confirmButton.isVisible()) {
            await this.confirmButton.waitFor({ state: 'attached' });
            await this.confirmButton.click();
        } else {
        // For some orders, user will have 2 options to choose from: monthly with interest or biweekly without interest
        if (await this.selectAfterpayWithoutInterestButton.isVisible()) {
            await this.selectAfterpayWithoutInterestButton.click();
            await this.continueAfterpayButton.click();
        } else if (await this.selectAfterpayWithInterestButton.isVisible()) {
            await this.selectAfterpayWithInterestButton.click();
            await this.continueAfterpayButton.click();
        }
        await this.confirmButton.click();
    }
}
}