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

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

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

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

  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: DomainModel): 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="Model name"
              required
              ?disabled="${disabled}"
              @change="${this.handleValueChange}"
            ></ui-outlined-text-field>
            ${renderHelp('model', '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('model', 'description-input')}
          </div>
        </div>
      </form>
    `
  }
}
