import type { DomainProperty } from '@api-client/core/modeling/DomainProperty.js'
import { DEFAULT_MARKDOWN_CONFIG, type MarkdownConfig } from '@api-client/core/modeling/definitions/Markdown.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 markdown field.
 */
export class MarkdownTaxonomy extends TaxonomyDialog<MarkdownConfig> {
  static override title = `Configure Markdown Taxonomy`

  constructor(public domainElement: DomainProperty) {
    let config: MarkdownConfig
    const semantic = domainElement.semantics.find((s) => s.id === SemanticType.Markdown)
    if (semantic && semantic.config) {
      config = structuredClone(semantic.config) as MarkdownConfig
    } else {
      config = {}
    }
    super(config)
  }

  protected override formCallback(event: Event): Promise<void> {
    const semantic = this.domainElement.semantics.find((s) => s.id === SemanticType.Markdown)
    if (semantic) {
      semantic.config = this.config
    } else {
      this.domainElement.semantics.push({
        id: SemanticType.Markdown,
        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_MARKDOWN_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="checkbox-group">
        ${this.renderAllowImages()} ${this.renderAllowLinks()} ${this.renderAllowTables()} ${this.renderAllowHtml()}
        ${this.renderAllowFootnotes()} ${this.renderAllowTaskLists()} ${this.renderAllowStrikethrough()}
      </div>
      <div class="input-group">
        ${this.renderRenderModeSelect()} ${this.renderSanitizeLevelSelect()} ${this.renderAllowedTagsInput()}
      </div>
    `
  }

  protected renderAllowImages(): TemplateResult {
    const enabled = this.config?.allowImages ?? DEFAULT_MARKDOWN_CONFIG.allowImages
    return html`
      <div class="row">
        <div class="input checkbox metadata">
          <ui-checkbox
            id="allow-images"
            .checked="${enabled}"
            name="allowImages"
            @change="${this.handleBooleanChange}"
          ></ui-checkbox>
          <div class="label">
            <label for="allow-images" class="body-medium">Allow Images</label>
            <span class="body-small meta">Users are allowed to add images in their markdown content.</span>
          </div>
        </div>
        ${renderHelp('taxonomy', 'markdown:allowImages')}
      </div>
    `
  }

  protected renderAllowLinks(): TemplateResult {
    const enabled = this.config?.allowLinks ?? DEFAULT_MARKDOWN_CONFIG.allowLinks
    return html`
      <div class="row">
        <div class="input checkbox metadata">
          <ui-checkbox
            id="allow-links"
            .checked="${enabled}"
            name="allowLinks"
            @change="${this.handleBooleanChange}"
          ></ui-checkbox>
          <div class="label">
            <label for="allow-links" class="body-medium">Allow Links</label>
            <span class="body-small meta">Users are allowed to add links in their markdown content.</span>
          </div>
        </div>
        ${renderHelp('taxonomy', 'markdown:allowLinks')}
      </div>
    `
  }

  protected renderAllowTables(): TemplateResult {
    const enabled = this.config?.allowTables ?? DEFAULT_MARKDOWN_CONFIG.allowTables
    return html`
      <div class="row">
        <div class="input checkbox metadata">
          <ui-checkbox
            id="allow-tables"
            .checked="${enabled}"
            name="allowTables"
            @change="${this.handleBooleanChange}"
          ></ui-checkbox>
          <div class="label">
            <label for="allow-tables" class="body-medium">Allow Tables</label>
            <span class="body-small meta">Users are allowed to add tables in their markdown content.</span>
          </div>
        </div>
        ${renderHelp('taxonomy', 'markdown:allowTables')}
      </div>
    `
  }

  protected renderAllowHtml(): TemplateResult {
    const enabled = this.config?.allowHtml ?? DEFAULT_MARKDOWN_CONFIG.allowHtml
    return html`
      <div class="row">
        <div class="input checkbox metadata">
          <ui-checkbox
            id="allow-html"
            .checked="${enabled}"
            name="allowHtml"
            @change="${this.handleBooleanChange}"
          ></ui-checkbox>
          <div class="label">
            <label for="allow-html" class="body-medium">Allow HTML</label>
            <span class="body-small meta">Users are allowed to add raw HTML in their markdown content.</span>
          </div>
        </div>
        ${renderHelp('taxonomy', 'markdown:allowHtml')}
      </div>
    `
  }

  protected renderAllowFootnotes(): TemplateResult {
    const enabled = this.config?.allowFootnotes ?? DEFAULT_MARKDOWN_CONFIG.allowFootnotes
    return html`
      <div class="row">
        <div class="input checkbox metadata">
          <ui-checkbox
            id="allow-footnotes"
            .checked="${enabled}"
            name="allowFootnotes"
            @change="${this.handleBooleanChange}"
          ></ui-checkbox>
          <div class="label">
            <label for="allow-footnotes" class="body-medium">Allow Footnotes</label>
            <span class="body-small meta">Users are allowed to add footnotes in their markdown content.</span>
          </div>
        </div>
        ${renderHelp('taxonomy', 'markdown:allowFootnotes')}
      </div>
    `
  }

  protected renderAllowTaskLists(): TemplateResult {
    const enabled = this.config?.allowTaskLists ?? DEFAULT_MARKDOWN_CONFIG.allowTaskLists
    return html`
      <div class="row">
        <div class="input checkbox metadata">
          <ui-checkbox
            id="allow-task-lists"
            .checked="${enabled}"
            name="allowTaskLists"
            @change="${this.handleBooleanChange}"
          ></ui-checkbox>
          <div class="label">
            <label for="allow-task-lists" class="body-medium">Allow Task Lists</label>
            <span class="body-small meta">Users are allowed to add task lists in their markdown content.</span>
          </div>
        </div>
        ${renderHelp('taxonomy', 'markdown:allowTaskLists')}
      </div>
    `
  }

  protected renderAllowStrikethrough(): TemplateResult {
    const enabled = this.config?.allowStrikethrough ?? DEFAULT_MARKDOWN_CONFIG.allowStrikethrough
    return html`
      <div class="row">
        <div class="input checkbox metadata">
          <ui-checkbox
            id="allow-strikethrough"
            .checked="${enabled}"
            name="allowStrikethrough"
            @change="${this.handleBooleanChange}"
          ></ui-checkbox>
          <div class="label">
            <label for="allow-strikethrough" class="body-medium">Allow Strikethrough</label>
            <span class="body-small meta">Users are allowed to add strikethrough text in their markdown content.</span>
          </div>
        </div>
        ${renderHelp('taxonomy', 'markdown:allowStrikethrough')}
      </div>
    `
  }

  protected renderRenderModeSelect(): TemplateResult {
    const value = this.config?.renderMode ?? DEFAULT_MARKDOWN_CONFIG.renderMode
    return html`
      <div class="row input-row">
        <ui-select
          label="Render mode"
          class="input"
          name="renderMode"
          .value="${value as string}"
          @change="${this.handleSelectChange}"
        >
          <ui-option value="html">HTML</ui-option>
          <ui-option value="text">Text</ui-option>
          <ui-option value="both">Both</ui-option>
        </ui-select>
        ${renderHelp('taxonomy', 'markdown:renderMode')}
      </div>
    `
  }

  protected renderSanitizeLevelSelect(): TemplateResult {
    const value = this.config?.sanitizeLevel ?? DEFAULT_MARKDOWN_CONFIG.sanitizeLevel
    return html`
      <div class="row input-row">
        <ui-select
          label="Sanitize level"
          class="input"
          name="sanitizeLevel"
          .value="${value as string}"
          @change="${this.handleSelectChange}"
        >
          <ui-option value="strict">Strict</ui-option>
          <ui-option value="moderate">Moderate</ui-option>
          <ui-option value="none">None</ui-option>
        </ui-select>
        ${renderHelp('taxonomy', 'markdown:sanitizeLevel')}
      </div>
    `
  }

  protected renderAllowedTagsInput(): TemplateResult {
    const value = this.config?.allowedTags ?? DEFAULT_MARKDOWN_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', 'markdown:allowedTags')}
      </div>
    `
  }
}
