import { html, nothing, TemplateResult } from 'lit'
import { live } from 'lit/directives/live.js'
import type { IBearerAuthorization } from '@api-client/core/models/Authorization.js'
import { Authorization } from './Authorization.js'
import Input from '../../../md/input/Input.js'
import '../../../md/text-field/ui-filled-text-field.js'

export default class BearerAuthorization extends Authorization {
  get config(): IBearerAuthorization {
    const { authorization } = this
    if (!authorization) {
      return { token: '' }
    }
    if (!authorization.config) {
      authorization.config = {} as IBearerAuthorization
    }
    return authorization.config as IBearerAuthorization
  }

  override checkValidity(): boolean {
    const { authorization } = this
    if (!authorization) {
      return true
    }

    const config = authorization.config as IBearerAuthorization
    return !!config && !!config.token
  }

  protected handleToken(e: Event): void {
    const { authorization } = this
    if (!authorization) {
      return
    }
    const input = e.target as Input
    const { value } = input
    if (!authorization.config) {
      authorization.config = {} as IBearerAuthorization
    }
    ;(authorization.config as IBearerAuthorization).token = value
    this.notifyChange()
  }

  override render(): TemplateResult {
    return html` ${this.renderHeader()} ${this.renderEditor()} `
  }

  protected renderEditor(): TemplateResult | typeof nothing {
    const { authorization } = this
    if (!authorization) {
      return nothing
    }
    const config = (authorization.config as IBearerAuthorization) || ({} as IBearerAuthorization)
    return html`
      <form autocomplete="on" class="auth-form basic-auth">${this.renderToken(config)}</form>
      ${this.renderAuthInfo()}
    `
  }

  protected renderToken(config: IBearerAuthorization): TemplateResult {
    return html`
      <div class="full-input">
        <ui-filled-text-field
          label="Token value"
          name="token"
          type="password"
          .value="${live(config.token || '')}"
          required
          invalidText="Token is required"
          ?disabled="${this.disabled}"
          ?readOnly="${this.readOnly}"
          @change="${this.handleToken}"
        ></ui-filled-text-field>
      </div>
    `
  }
}
