import { LitElement, html, nothing } from 'lit'
import { customElement, property } from 'lit/decorators.js'
import { ComponentStatesMixin } from '../../ComponentStatesMixin'
import { v1 as uuid } from 'uuid'

@customElement('btu-search-input')
export default class SearchInput extends ComponentStatesMixin(LitElement) {
  private _id = `i${uuid()}`

  @property({ type: String })
  arialabel?: string

  @property({ type: String })
  label?: string

  @property({ type: String })
  name?: string

  @property({ type: String })
  placeholder?: string

  @property({ type: String })
  value?: string

  constructor() {
    super()
    this.states.add('btu-loading')
  }

  firstUpdated() {
    this.states.delete('btu-loading')

    // Focus on the input when a search opens in a popup.
    const popup = this.closest(
      '.Popup:not([data-popup-source-class*="edit"], [data-popup-source-class*="create"])',
    )
    const input = this.querySelector('input')
    if (input && popup) {
      input.focus()
      input.select()
    }

    // Don't submit a search when pressing <enter>.
    // Exception: if press occurs on a non-submitting button, allow default behavior.
    const form = this.closest('form')
    if (!form) return
    form.addEventListener('keydown', (evt) => {
      if (
        evt.target instanceof Element &&
        evt.target.matches('button[type="button"]')
      ) {
        return
      }

      if (evt.key === 'Enter') {
        evt.preventDefault()
      }
    })
  }

  createRenderRoot() {
    return this
  }

  render() {
    return html`<label for="${this._id}">${this.label}</label>
      <btu-input type="text">
        <input
          type="text"
          id="${this._id}"
          name="${this.name || nothing}"
          placeholder="${this.placeholder || this.label || nothing}"
          value="${this.value || nothing}"
          autocomplete="off"
          aria-label="${this.arialabel || nothing}"
          readonly
          @focus="${(e: Event) => {
            if (e.target instanceof HTMLInputElement) e.target.readOnly = false
          }}"
        />
      </btu-input>`
  }
}

declare global {
  interface HTMLElementTagNameMap {
    'btu-search-input': SearchInput
  }
}
