import { demoFunc } from './dees-form-submit.demo.js';
import {
  customElement,
  html,
  DeesElement,
  css,
  cssManager,
  property,
} from '@design.estate/dees-element';
import type { DeesForm } from '../dees-form/dees-form.js';
import { themeDefaultStyles } from '../../00theme.js';

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

@customElement('dees-form-submit')
export class DeesFormSubmit extends DeesElement {
  public static demo = demoFunc;
  public static demoGroup = 'Form';

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

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

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

  constructor() {
    super();
  }
  
  public static styles = [themeDefaultStyles, cssManager.defaultStyles, css`
      /* TODO: Migrate hardcoded values to --dees-* CSS variables */
    `];

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

  public async submit() {
    if (this.disabled) {
      return;
    }
    // Walk up the DOM tree to find the nearest dees-form element
    const parentFormElement = this.closest('dees-form') as DeesForm;
    if (parentFormElement && parentFormElement.gatherAndDispatch) {
      parentFormElement.gatherAndDispatch();
    }
  }

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