import { LitElement, html, nothing } from 'lit'
import { customElement, property } from 'lit/decorators.js'
import { WrappingMixin } from '../../WrappingMixin'
import { PlaceholderEditableMixin } from '../../PlaceholderEditableMixin'
import { EventEmitterMixin } from '../../EventEmitterMixin'

if (!window.BRIGHTSPOT?.ui.cms.enableV5UI) {
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  // @ts-ignore
  await import('./index.less')
}

@customElement('btu-input')
export default class Input extends PlaceholderEditableMixin(
  EventEmitterMixin(WrappingMixin(LitElement)),
) {
  static get tagName() {
    return 'btu-input'
  }

  @property({ type: Boolean, state: true })
  autofocusInput
  @property({ type: Boolean, state: true })
  passwordVisible
  @property({ reflect: true })
  type?: string

  private handleHidePassword(evt: Event) {
    if (this.input instanceof HTMLInputElement) {
      this.input.type = 'password'
      this.passwordVisible = false
      this.emit('btu-input-password-hide')
    }
  }

  private handleShowPassword(evt: Event) {
    if (this.input instanceof HTMLInputElement) {
      this.input.type = 'text'
      this.passwordVisible = true
      this.emit('btu-input-password-show')
    }
  }

  // Overrides #find in superclass.
  find() {
    return this.querySelector<HTMLInputElement>(':scope > input')
  }

  // Overrides #child setter in superclass.
  set child(_c: HTMLInputElement) {
    super._child = _c
    this.input = _c
  }

  constructor() {
    super()
    this.autofocusInput = false
    this.passwordVisible = false
  }

  createRenderRoot() {
    return this
  }

  passwordToggleTemplate() {
    return html`<button
      type="button"
      aria-label=${this.passwordVisible
        ? window.BRIGHTSPOT?.ui?.input?.secretHide ?? 'Hide'
        : window.BRIGHTSPOT?.ui?.input?.secretShow ?? 'Show'}
      @click=${this.passwordVisible
        ? this.handleHidePassword
        : this.handleShowPassword}
      class="ShowPassword-toggle ${this.passwordVisible ? 'off' : 'on'}"
    ></button>`
  }

  render() {
    if (this.autofocusInput) {
      this.input?.focus()
    }
    return html`${this.type === 'password'
      ? this.passwordToggleTemplate()
      : nothing}`
  }
}

declare global {
  interface HTMLElementTagNameMap {
    'btu-input': Input
  }
}
