import type { ArxInputChangeEvent } from '@components/General/Input';
import { LitElement, css, html } from 'lit';
import { customElement, property, state } from 'lit/decorators.js';
import { when } from 'lit/directives/when.js';

import '@components/General/Dialog';
import '@components/General/Input';

@customElement('arx-prompt')
export class EvePrompt extends LitElement {
  @property({ type: String }) promptText = 'Please provide input';
  @property({ type: String }) cancelText = 'Cancel';
  @property({ type: String }) saveText = 'Save';
  @property({ type: Boolean }) open = false;
  @property({ type: Boolean }) showInput = false;
  @property({ type: String }) placeholder = 'Enter your response';
  @property({ type: String }) defaultValue = '';

  @state() private _inputValue = '';

  static override styles = css`
    :host {
      display: block;
    }
  `;

  override updated(changedProps: Map<string, unknown>) {
    if (changedProps.has('open') && this.open) {
      this._inputValue = this.defaultValue;
    }
  }

  private _handleInputChange(e: ArxInputChangeEvent) {
    this._inputValue = e.detail.value;
  }

  private _handleCancel() {
    this.open = false;
    this.dispatchEvent(new CustomEvent('cancel'));
  }

  private _handleSave() {
    this.open = false;
    this.dispatchEvent(
      new CustomEvent('save', {
        detail: { value: this._inputValue },
      }),
    );
  }

  override render() {
    return html`
      <arx-dialog
        .title=${this.promptText}
        .open=${this.open}
        .closeOnOverlayClick=${false}
        .closeOnEscape=${false}
      >
        ${when(
          this.showInput,
          () => html`
            <arx-input
              type="text"
              class="input-field"
              .value=${this._inputValue}
              @change=${this._handleInputChange}
              placeholder=${this.placeholder}
            ></arx-input>
          `,
        )}
        <div slot="footer">
          <arx-button
            variant="accent"
            label=${this.cancelText}
            @click=${this._handleCancel}
          ></arx-button>
          <arx-button
            variant="secondary"
            label=${this.saveText}
            @click=${this._handleSave}
          ></arx-button>
        </div>
      </arx-dialog>
    `;
  }

  show() {
    this.open = true;
  }

  hide() {
    this.open = false;
  }

  getValue(): string {
    return this._inputValue;
  }
}
