import { expect, type Locator, type Page } from '@playwright/test';
import { IVehicleDetails } from 'safelite-playwright-core';
import { InsuranceBasePage } from './InsuranceBasePage';
import { ITestData } from 'framework/TestData';
import { step } from 'framework/localTypes/Step';

export class PolicyVehiclesPage extends InsuranceBasePage {
    readonly page: Page;

    constructor(page: Page) {
        super(page);
        this.page = page;
    }

    async validateVehicleIsOnPolicy(vehicleDetails: IVehicleDetails) {
        const vehicleRegExp = new RegExp(`${vehicleDetails.year} .+ ${vehicleDetails.model}`, 'i');
        await expect.soft(this.page.getByRole('radio', {name: vehicleRegExp})).toBeAttached();
    }

    async selectVehicle(vehicleDetails: IVehicleDetails){
        const baseModel = vehicleDetails.model.split(' ').pop() || vehicleDetails.model;
        const vehicleRegExp = new RegExp(`${vehicleDetails.year}.*?${vehicleDetails.make}.*?${baseModel}`, 'i');
        await this.page.getByRole('radio', {name: vehicleRegExp}).click();
    }

    async selectVehicleNotListed(){
        await this.page.getByText('Vehicle not listed').click();
    }

    @step("PolicyVehiclesPage >> Select Vehicle: ")
    async handlePolicyVehiclesPage(testCase: Partial<ITestData>) {

        const { vehicleDetails, otherVehiclesOnPolicy, isUseVehicleOnPolicy } = testCase;
        
        // Validate other vehicles on policy
        if (otherVehiclesOnPolicy && otherVehiclesOnPolicy.length > 0) {
            for (const vehicle of otherVehiclesOnPolicy) {
                await this.validateVehicleIsOnPolicy(vehicle);
            }
        }

        // If vehicle is not on the policy, select new vehicle
        if (!(isUseVehicleOnPolicy ?? true)) {
            await this.selectVehicleNotListed();
            await this.nextPage();
            await this.selectVehicle(vehicleDetails!);
            await this.nextPage();
        } else {
            // Otherwise, select the vehicle entered in Safelite.com
            await this.selectVehicle(vehicleDetails!);
            await this.nextPage();
        }
    }
}