import { html, nothing, PropertyValues, TemplateResult } from 'lit'
import { live } from 'lit/directives/live.js'
import { ModelingElement } from './ModelingElement.js'
import type { DomainNamespace } from '@api-client/core/modeling/DomainNamespace.js'
import { cancelEvent } from '@api-client/core/lib/events/Utils.js'
import { renderHelp } from '../../help/render.js'

/**
 * An UI element that renders an editor for a DomainNamespace.
 */
export default class DomainNamespaceEditor extends ModelingElement {
  private domainElement: DomainNamespace | undefined

  protected override willUpdate(cp: PropertyValues<this>): void {
    if (cp.has('selected') || cp.has('root') || cp.has('namespace')) {
      this.computeNamespace()
    }
    super.willUpdate(cp)
  }

  protected computeNamespace(): void {
    const { root, selected, namespace } = this
    if (!root || !selected) {
      this.domainElement = undefined
      return
    }
    this.domainElement = root.findNamespace(selected, namespace)
  }

  protected handleValueChange(e: Event): void {
    const { domainElement } = this
    if (!domainElement) {
      return
    }
    const node = e.target as HTMLInputElement
    const { name, value } = node
    if (!['name', 'description'].includes(name as string)) {
      return
    }
    if (name === 'name' && !value) {
      return
    }
    domainElement.info[name as 'name' | 'description'] = value
    this.notifyChange()
  }

  protected override render(): TemplateResult | typeof nothing {
    const { domainElement } = this
    if (!domainElement) {
      return nothing
    }
    return html`${this.renderForm(domainElement)}`
  }

  protected renderForm(model: DomainNamespace): TemplateResult {
    const disabled = !this.canEdit
    return html`
      <form name="data-model" @submit="${cancelEvent}" data-key="${model.key}" class="modeling-form">
        <div class="editor-section">
          <div class="row input-row">
            <ui-outlined-text-field
              class="input"
              name="name"
              .value="${live(model.info.name || '')}"
              label="Namespace name"
              required
              ?disabled="${disabled}"
              @change="${this.handleValueChange}"
            ></ui-outlined-text-field>
            ${renderHelp('namespace', 'name-input')}
          </div>
          <div class="row input-row">
            <ui-outlined-text-field
              class="input"
              name="description"
              .value="${live(model.info.description || '')}"
              label="Description (optional)"
              ?disabled="${disabled}"
              @change="${this.handleValueChange}"
            ></ui-outlined-text-field>
            ${renderHelp('namespace', 'description-input')}
          </div>
        </div>
      </form>
    `
  }
}
