import { html, nothing, TemplateResult } from "lit";
import {
  ICCAuthorization, HttpCertificate, Events as CoreEvents, CertificateFileKind, ICertificate, IFile,
} from '@api-client/core/build/browser.js';
import { state } from "lit/decorators.js";
import { Authorization } from "./Authorization.js";
import type { FilePickerClosingReason } from "../../store/FilePicker.element.js";
import { Events } from "../../../events/Events.js";
import '../../../define/ui/ui-dropdown-list.js';
import '../../../define/ui/ui-button.js';
import '../../../define/ui/ui-icon-button.js';
import '../../../define/ui/ui-icon.js';
import '../../../define/store/file-picker.js';

export default class CcAuthorization extends Authorization {
  @state() 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<FilePickerClosingReason>): 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 class="dropdown-trigger" type="tonal">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>
    `;
  }
}
