import { Page } from 'playwright';
import { AbstractLocator } from '../AbstractWidget';
import { DataTableWidget } from '../DataTableWidget';
import { TableWidget } from '../TableWidget';
import { widgetStep } from '@/core/utils';

export type TableSingleActionFindOptions = {
  label?: string;
  variant?: string;
  icon?: string;
};

export class TableSingleAction extends AbstractLocator {
  protected testId = 'table-action-single';

  constructor(
    protected readonly findOptions: TableSingleActionFindOptions,
    protected readonly dataTable: DataTableWidget | TableWidget,
    page: Page
  ) {
    super(page);
  }
  find() {
    const { label, variant, icon } = this.findOptions;

    const selectorArr = [`[data-testid="${this.testId}"]`];
    if (label) selectorArr.push(`[label="${label}"]`);
    if (variant) selectorArr.push(`.btn-${variant}`);

    const action = this.page.locator(
      `[data-role="actions"] ${selectorArr.join('')}`,
      {
        has: icon ? this.page.locator(`svg[data-icon="${icon}"]`) : undefined,
      }
    );

    return action;
  }

  @widgetStep
  async click() {
    try {
      await this.l.waitFor({ state: 'visible' });
      await this.l.click();
    } catch (e) {
      throw new Error(
        `Table Single action click failed for options ${JSON.stringify(this.findOptions)}.\nOriginal error: ${e}`
      );
    }
    return this;
  }
}

export class TableModalAction extends TableSingleAction {
  protected readonly testId = 'table-action-modal';
}
