import type { DomainAssociation } from '@api-client/core/modeling/DomainAssociation.js'
import { type TagsConfig, DEFAULT_TAGS_CONFIG } from '@api-client/core/modeling/definitions/Tags.js'
import { bound } from '../../decorators/bound.js'
import { html, TemplateResult } from 'lit'
import { SemanticType } from '@api-client/core/modeling/Semantics.js'
import { renderHelp } from '../../help/render.js'
import { TaxonomyDialog } from './TaxonomyDialog.js'

import '../../md/chip/ui-chip-set.js'
import '../../md/chip/ui-chip.js'

/**
 * A class that generates a dialog that allows the user to configure the taxonomy of a Tags annotated association.
 */
export class TagsTaxonomy extends TaxonomyDialog<TagsConfig> {
  static override title = `Configure Tags Taxonomy`

  constructor(public domainElement: DomainAssociation) {
    let config: TagsConfig
    const semantic = domainElement.semantics.find((s) => s.id === SemanticType.Tags)
    if (semantic && semantic.config) {
      config = structuredClone(semantic.config)
    } else {
      config = {}
    }
    super(config)
  }

  protected override formCallback(event: Event): Promise<void> {
    const semantic = this.domainElement.semantics.find((s) => s.id === SemanticType.Tags)
    if (semantic) {
      semantic.config = this.config
    } else {
      this.domainElement.semantics.push({
        id: SemanticType.Tags,
        config: this.config,
      })
    }
    this.domainElement.domain.notifyChange()
    return super.formCallback(event)
  }

  @bound
  protected handleAllowedTagsChange(event: Event): void {
    const input = event.target as HTMLInputElement
    const value = input.value.trim()
    if (value) {
      const tags = this.config?.allowedTags ?? DEFAULT_TAGS_CONFIG.allowedTags ?? []
      if (!tags.includes(value)) {
        tags.push(value)
        this.config = { ...this.config, allowedTags: tags }
        this.requestUpdate()
      }
      input.value = ''
    }
  }

  @bound
  protected handleRemoveTag(event: Event): void {
    const chip = event.currentTarget as HTMLElement
    const index = parseInt(chip.dataset.index || '-1', 10)
    if (index >= 0 && this.config?.allowedTags) {
      this.config.allowedTags.splice(index, 1)
      this.requestUpdate()
    }
  }

  @bound
  render(): TemplateResult {
    return html`
      <div class="input-group">${this.renderAllowedTagsInput()}</div>
      <div class="checkbox-group">
        ${this.renderAllowCustomTags()} ${this.renderCaseSensitive()} ${this.renderAllowUnicode()}
      </div>
    `
  }

  protected renderAllowCustomTags(): TemplateResult {
    const enabled = this.config?.allowCustomTags ?? DEFAULT_TAGS_CONFIG.allowCustomTags
    return html`
      <div class="row">
        <div class="input checkbox metadata">
          <ui-checkbox
            id="allow-custom-tags"
            .checked="${enabled}"
            name="allowCustomTags"
            @change="${this.handleBooleanChange}"
          ></ui-checkbox>
          <div class="label">
            <label for="allow-custom-tags" class="body-medium">Allow Custom Tags</label>
            <span class="body-small meta">Users are allowed to add custom tags not in the allowed tags list.</span>
          </div>
        </div>
        ${renderHelp('taxonomy', 'tags:allowCustomTags')}
      </div>
    `
  }

  protected renderCaseSensitive(): TemplateResult {
    const enabled = this.config?.caseSensitive ?? DEFAULT_TAGS_CONFIG.caseSensitive
    return html`
      <div class="row">
        <div class="input checkbox metadata">
          <ui-checkbox
            id="case-sensitive"
            .checked="${enabled}"
            name="caseSensitive"
            @change="${this.handleBooleanChange}"
          ></ui-checkbox>
          <div class="label">
            <label for="case-sensitive" class="body-medium">Case Sensitive</label>
            <span class="body-small meta">Whether tags are case sensitive.</span>
          </div>
        </div>
        ${renderHelp('taxonomy', 'tags:caseSensitive')}
      </div>
    `
  }

  protected renderAllowUnicode(): TemplateResult {
    const enabled = this.config?.allowUnicode ?? DEFAULT_TAGS_CONFIG.allowUnicode
    return html`
      <div class="row">
        <div class="input checkbox metadata">
          <ui-checkbox
            id="allow-unicode"
            .checked="${enabled}"
            name="allowUnicode"
            @change="${this.handleBooleanChange}"
          ></ui-checkbox>
          <div class="label">
            <label for="allow-unicode" class="body-medium">Allow Unicode</label>
            <span class="body-small meta">Users are allowed to add unicode characters in tags.</span>
          </div>
        </div>
        ${renderHelp('taxonomy', 'tags:allowUnicode')}
      </div>
    `
  }

  protected renderAllowedTagsInput(): TemplateResult {
    const value = this.config?.allowedTags ?? DEFAULT_TAGS_CONFIG.allowedTags
    const chips = (value || []).map(
      (tag, index) =>
        html`<ui-chip type="input" removable data-index="${index}" @remove="${this.handleRemoveTag}">${tag}</ui-chip>`
    )
    return html`
      <div class="row input-row">
        <div class="input chips-input">
          <ui-outlined-text-field
            class="input"
            name="allowedTags"
            label="Allowed Tags"
            @change="${this.handleAllowedTagsChange}"
            supportingText="Add a tag and press Enter to add it to the list."
          ></ui-outlined-text-field>
          <ui-chip-set>${chips}</ui-chip-set>
        </div>
        ${renderHelp('taxonomy', 'tags:allowedTags')}
      </div>
    `
  }
}
