import {
  customElement,
  html,
  DeesElement,
  css,
  cssManager,
  property,
  type CSSResult,
} from '@design.estate/dees-element';
import { DeesForm } from './dees-form.js';

declare global {
  interface HTMLElementTagNameMap {
    'dees-form-submit': DeesFormSubmit;
  }
}

@customElement('dees-form-submit')
export class DeesFormSubmit extends DeesElement {
  public static demo = () => html`<dees-form-submit>This is a sloted text</dees-form-submit>`;

  @property({
    type: Boolean,
    reflect: true,
  })
  public disabled = false;

  @property({
    type: String,
  })
  public text: string;

  @property({
    type: String,
  })
  public status: 'normal' | 'pending' | 'success' | 'error' = 'normal';

  constructor() {
    super();
  }

  public static styles = [cssManager.defaultStyles, css``];

  public render() {
    return html`
      <dees-button
        status=${this.status}
        @click=${this.submit}
        .disabled=${this.disabled}
        .text=${this.text ? this.text : this.textContent}
      >
      </dees-button>
    `;
  }

  public async submit() {
    if (this.disabled) {
      return;
    }
    const parentElement: DeesForm = this.parentElement as DeesForm;
    parentElement.gatherAndDispatch();
  }

  public async focus() {
    const domtools = await this.domtoolsPromise;
    if (!this.disabled) {
      domtools.convenience.smartdelay.delayFor(0);
      this.submit();
    }
  }
}