import { BaseDialog } from '@/manager/shared/base/BaseDialog';
import { InsuranceCreateBookingPortalFieldSet } from '@/manager/modules/insurance/components/InsuranceCreateBookingPortalFieldSet';
import { InsuranceCreateGeneralFieldSet } from '@/manager/modules/insurance/components/InsuranceCreateGeneralFieldSet';
import { InsuranceCreateData } from '@/manager/modules/insurance/insurance-types';
import { InsuranceDetailsPage } from '@/manager/modules/insurance/views/InsuranceDetailsPage';
import { BookingPlanFieldSet } from '@/manager/modules/ui/booking-plan/components/BookingPlanFieldSet';
import { TaxFieldSet } from '@/manager/modules/ui/tax/components/TaxFieldSet';
import { getSnackbarHost, getDialogErrorsHost } from '@/manager/shared/utils/locator-utils';
import { getDetailsPageRegExpUrl } from '@/manager/shared/utils/url-utils';
import { Page } from '@playwright/test';

export class InsuranceCreateDialog extends BaseDialog {
  readonly generalFieldSet = new InsuranceCreateGeneralFieldSet(this.main);
  readonly taxFieldSet = new TaxFieldSet(this.main);
  readonly bookingPortalFieldSet = new InsuranceCreateBookingPortalFieldSet(this.main);
  readonly bookingPlanFieldSet = new BookingPlanFieldSet(this.main);
  readonly errors = getDialogErrorsHost(this.main);
  readonly snackbar = getSnackbarHost(this.host, 'Protection plan created successfully');

  constructor(host: Page) {
    super(host, 'insurance-create-dialog');
  }

  async goto(): Promise<void> {
    await this.host.goto('/insurances/create');
  }

  async create(data: InsuranceCreateData): Promise<InsuranceDetailsPage> {
    await this.fill(data);
    await Promise.all([
      this.snackbar.waitFor(),
      this.host.waitForURL(getDetailsPageRegExpUrl('insurances')),
      this.submit(),
    ]);
    return new InsuranceDetailsPage(this.host);
  }

  async fill(data: InsuranceCreateData): Promise<void> {
    await this.generalFieldSet.nameTextField.fill(data.name);
    await this.generalFieldSet.locationAutocomplete.fill(data.location.name);

    await this.taxFieldSet.fill(data.taxes);

    if (data.shortDescription != null) {
      await this.bookingPortalFieldSet.shortDescriptionInput.fill(data.shortDescription);
    }

    await this.bookingPlanFieldSet.fill(data.bookingPlans);
  }

  async submit(): Promise<void> {
    await this.submitButton.click();
  }
}
