import { html, nothing, TemplateResult } from 'lit'
import { state } from 'lit/decorators.js'
import { Authorization } from './Authorization.js'
import { Events } from '../../../events/Events.js'
import '../../../md/dropdown-list/ui-dropdown-list.js'
import '../../../md/button/ui-button.js'
import '../../../md/icon-button/ui-icon-button.js'
import '../../../md/icons/ui-icon.js'
import type { ICCAuthorization } from '@api-client/core/models/Authorization.js'
import type { IFile } from '@api-client/core/models/store/File.js'
import { Events as CoreEvents } from '@api-client/core/events/Events.js'
import type { HttpCertificate, ICertificate } from '@api-client/core/models/ClientCertificate.js'
import { CertificateFileKind } from '@api-client/core/models/kinds.js'
// import '../../../define/store/file-picker.js'

export default class CcAuthorization extends Authorization {
  @state() accessor selectorRendered = false

  get config(): ICCAuthorization {
    const { authorization } = this
    if (!authorization) {
      return {}
    }
    if (!authorization.config) {
      authorization.config = {} as ICCAuthorization
    }
    return authorization.config as ICCAuthorization
  }

  protected handleClose(e: CustomEvent<{ canceled: boolean; file: IFile }>): void {
    const { canceled, file } = e.detail
    if (canceled) {
      return
    }
    this.setCertificate((file as IFile).key)
    CoreEvents.Telemetry.event(
      {
        category: 'Certificates',
        action: 'Authorization',
        label: 'selected-certificate',
      },
      this
    )
  }

  async setCertificate(key: string): Promise<void> {
    let result: unknown
    try {
      result = await Events.Store.File.read(key, true, this)
    } catch {
      return
    }
    const { config } = this
    config.certificate = result as ICertificate
    this.requestUpdate()
    this.notifyChange()
  }

  protected handleDropDownOpen(): void {
    this.selectorRendered = true
    if (this.isUpdatePending) {
      this.scheduleUpdate()
    }
  }

  protected handleClearCertificate(): void {
    const { config } = this
    delete config.certificate
    this.requestUpdate()
    this.notifyChange()
  }

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

  protected renderEditor(): TemplateResult | typeof nothing {
    const { config } = this
    const { certificate } = config
    // Note, the <form> element is required by the Authorization class for validation.
    return html`
      <form autocomplete="on" class="auth-form cc-auth"></form>
      ${this.renderSelector()} ${certificate ? this.renderSelection(certificate) : nothing}
    `
  }

  protected renderSelector(): TemplateResult {
    const { selectorRendered } = this
    const kinds: (typeof CertificateFileKind)[] = [CertificateFileKind]
    return html`
      <div class="selector">
        <ui-dropdown-list @open="${this.handleDropDownOpen}">
          <ui-button color="tonal" class="dropdown-trigger">Select a certificate</ui-button>
          ${selectorRendered
            ? html`<file-picker slot="dropdown" .kinds="${kinds}" @close="${this.handleClose}"></file-picker>`
            : nothing}
        </ui-dropdown-list>
      </div>
    `
  }

  protected renderSelection(certificate: HttpCertificate): TemplateResult {
    return html`
      <div class="certificate-info body-medium">
        Current certificate: ${certificate.name}
        <ui-icon-button
          aria-label="Remove certificate from authorization"
          title="Remove certificate from authorization"
          @click="${this.handleClearCertificate}"
        >
          <ui-icon role="presentation" icon="deleteOutline"></ui-icon>
        </ui-icon-button>
      </div>
    `
  }
}
