import { expect, type Locator, type Page } from '@playwright/test';
import { BasePage } from './BasePage';
import { AddressForm } from './forms/AddressForm';
import { IAddress } from '@business-logic/types/IAddress';
import { ICustomerDetails } from '@business-logic/types/CustomerDetails';

export class AddressLookupPage extends BasePage {
    readonly page: Page;
    readonly addressForm: AddressForm;
    readonly addressNoMatchTextBox: Locator;
    readonly stateRestrictionsTextBox: Locator;
    issPageValue = 'address-lookup';

    constructor(page: Page) {
        super(page);
        this.page = page;
        this.addressForm = new AddressForm(page);
        this.addressNoMatchTextBox = page.getByText('Your address didn’t return a VIN matchPlease re-enter the information below or');
        this.stateRestrictionsTextBox = page.getByText('State restrictionsLooks like');
    }

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

    async populateAddress(fullAddress: IAddress) {
        if (fullAddress.street) {
            // Transform IAddress to CustomerDetails address format
            const customerAddress: Partial<ICustomerDetails> = {
                address: {
                    street: fullAddress.street,
                    city: fullAddress.city,
                    state: fullAddress.state,
                    postalCode: fullAddress.postalCode
                },
                lastName: fullAddress.lastName || '',
            };
            // Fill address using AddressForm methods
            await this.addressForm.populateAddress(customerAddress);
        }
    }

    async validateAddressLookupAlerts(addressSet: IAddress[]) {
        await this.populateAddress(addressSet[0]);
        await this.continueButton.click();
        await expect(this.addressNoMatchTextBox).toBeVisible();

        await this.populateAddress(addressSet[1]);
        await this.continueButton.click();
        await expect(this.stateRestrictionsTextBox).toBeVisible();

        await this.populateAddress(addressSet[2]);
    }
}