import { expect, type Locator, type Page } from '@playwright/test';
import { BasePage } from '../BasePage';
import { ICustomerDetails } from '@business-logic/types/CustomerDetails';
import { faker } from '@faker-js/faker/locale/en';

export class AddressForm extends BasePage {
    readonly page: Page;
    readonly streetAddressTextBox: Locator;
    readonly cityTextBox: Locator;
    readonly stateDrpDwn: Locator;
    readonly zipCodeTextBox: Locator;
    readonly firstNameTextBox: Locator;
    readonly lastNameTextBox: Locator;
    readonly addressNotFoundMsg: Locator;

    constructor(page: Page) {
        super(page);
        this.page = page;
        this.streetAddressTextBox = page.getByRole('textbox', { name: /Street (a|A)ddress$/ });
        this.cityTextBox = page.getByRole('textbox', { name: 'City' });
        this.stateDrpDwn = page.getByRole('combobox', { name: 'State' });
        this.zipCodeTextBox = page.getByRole('textbox', { name: 'ZIP code' });
        this.firstNameTextBox = page.getByRole('textbox', { name: 'First name' });
        this.lastNameTextBox = page.getByRole('textbox', { name: 'Last name' });
        this.addressNotFoundMsg = page.getByText('Address not found.');
    }

    async forceAddressFormToAppear() {
        await expect(async () => {
            await this.streetAddressTextBox.click();
            await this.streetAddressTextBox.pressSequentially('7400 Safelite Way');
            await this.streetAddressTextBox.press('Tab');
            await expect(this.zipCodeTextBox).toBeVisible({ timeout: 100 });
        }).toPass();
    }

    async populateAddress(customerDetails: Partial<ICustomerDetails>) {

        if (customerDetails.address) {
            // Force address form to appear
            await this.forceAddressFormToAppear();

            // Fill address
            await this.fillAndValidate(this.streetAddressTextBox, customerDetails.address.street);
            await this.fillAndValidate(this.zipCodeTextBox, customerDetails.address.postalCode)
            await this.fillAndValidate(this.cityTextBox, customerDetails.address.city);
            await this.stateDrpDwn.selectOption(customerDetails.address.state);
        }

        if (customerDetails.firstName) {
            await this.fillAndValidate(this.firstNameTextBox, customerDetails.firstName);
        }

        if (customerDetails.lastName) {
            await this.fillAndValidate(this.lastNameTextBox, customerDetails.lastName);
        }
    }
}