import { TemplateResult, html } from 'lit'
import { property, state } from 'lit/decorators.js'
import { ClassInfo, classMap } from 'lit/directives/class-map.js'
import { live } from 'lit/directives/live.js'
import UiDialog from '../../../md/dialog/internals/Dialog.js'
import type Input from '../../../md/input/Input.js'

import '../../../md/button/ui-button.js'
import '../../../md/icons/ui-icon.js'
import '../../../md/text-field/ui-filled-text-field.js'

/**
 * A dialog that requests the user for the new name.
 *
 * Listen to the `closed` on the dialog. The CustomEvent has the `detail`
 * object with the `closingReason` retails:
 * - canceled: whether the dialog was cancelled (ESC, outside click, dismiss button)
 * - confirmed: whether the dialog was confirmed by the user
 * - value: The entered name value
 *
 * The application should handle the event and trigger name change flow.
 *
 * ```javascript
 * const dialog = document.createElement('rename-dialog');
 * dialog.name = 'old name';
 * document.body.appendChild(dialog);
 * dialog.open = true;
 * dialog.addEventListener('closed', (ev: Event) => {
 *   document.body.removeChild(dialog);
 *   const event = ev as CustomEvent<UiDialogClosingReason>;
 *   const { cancelled, value } = event.detail;
 *   if (!cancelled && value) {
 *     // trigger the flow, value is the new value
 *   }
 * });
 * ```
 */
export default class RenameDialogElement extends UiDialog {
  /**
   * The previous name
   * @attribute
   */
  @property({ type: String }) accessor name: string | undefined

  @state() accessor newValue: string | undefined

  private get hasValue(): boolean {
    const { newValue } = this
    if (!newValue) {
      return false
    }
    return newValue.trim().length > 0
  }

  protected handleInput(e: Event): void {
    const input = e.target as Input
    this.newValue = input.value
  }

  protected handleInputKeyDown(e: KeyboardEvent): void {
    const confirm = (e.ctrlKey || e.metaKey) && e.key === 'Enter'
    if (!confirm || !this.hasValue) {
      return
    }
    this.handleInteraction('confirm')
  }

  protected override handleInteraction(value: 'dismiss' | 'confirm'): void {
    if (value === 'confirm') {
      this.dialogValue = this.newValue
    } else {
      this.dialogValue = undefined
    }
    super.handleInteraction(value)
  }

  override renderIcon(): TemplateResult {
    const classes: ClassInfo = {
      'icon': true,
      'with-icon': true,
    }
    return html` <div class="${classMap(classes)}" part="icon"><ui-icon icon="rename"></ui-icon></div> `
  }

  override renderTitle(): TemplateResult {
    const classes: ClassInfo = {
      'title': true,
      'with-title': true,
    }
    return html` <div class="${classMap(classes)}" part="title"><span>Rename</span></div> `
  }

  override renderBody(): TemplateResult {
    const value = this.newValue || this.name || ''
    return html`
      <div class="content">
        <ui-filled-text-field
          class="file-name"
          type="text"
          name="name"
          required
          invalidText="The name is required. Please, enter the name."
          @input="${this.handleInput}"
          @keydown="${this.handleInputKeyDown}"
          .value="${live(value)}"
          label="Enter new name"
        ></ui-filled-text-field>
      </div>
    `
  }

  override renderButtons(): TemplateResult {
    const { confirmLabel = 'Rename', dismissLabel = 'Cancel' } = this
    const classes: ClassInfo = {
      'buttons': true,
      'with-buttons': true,
    }
    return html`
      <div class="${classMap(classes)}" part="button">
        <ui-button color="text" value="dismiss" class="internal-button" @click="${this.handleDismiss}"
          >${dismissLabel}</ui-button
        >
        <ui-button
          color="text"
          value="confirm"
          class="internal-button"
          ?disabled="${!this.hasValue}"
          @click="${this.handleConfirm}"
          >${confirmLabel}</ui-button
        >
      </div>
    `
  }
}
