import type { DomainProperty } from '@api-client/core/modeling/DomainProperty.js'
import { type PostalCodeConfig, DEFAULT_POSTAL_CODE_CONFIG } from '@api-client/core/modeling/definitions/PostalCode.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 PostalCode annotated association.
 */
export class PostalCodeTaxonomy extends TaxonomyDialog<PostalCodeConfig> {
  static override title = `Configure Postal Code Taxonomy`

  constructor(public domainElement: DomainProperty) {
    let config: PostalCodeConfig
    const semantic = domainElement.semantics.find((s) => s.id === SemanticType.PostalCode)
    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.PostalCode)
    if (semantic) {
      semantic.config = this.config
    } else {
      this.domainElement.semantics.push({
        id: SemanticType.PostalCode,
        config: this.config,
      })
    }
    this.domainElement.domain.notifyChange()
    return super.formCallback(event)
  }

  protected handleAllowedPostalCodesChange(event: Event): void {
    const input = event.target as HTMLInputElement
    const value = input.value.trim()
    if (value) {
      const postalCodes = this.config?.allowedPostalCodes ?? DEFAULT_POSTAL_CODE_CONFIG.allowedPostalCodes ?? []
      if (!postalCodes.includes(value)) {
        postalCodes.push(value)
        this.config = { ...this.config, allowedPostalCodes: postalCodes }
        this.requestUpdate()
      }
      input.value = ''
    }
  }

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

  protected handleDisallowedPostalCodesChange(event: Event): void {
    const input = event.target as HTMLInputElement
    const value = input.value.trim()
    if (value) {
      const postalCodes = this.config?.disallowedPostalCodes ?? DEFAULT_POSTAL_CODE_CONFIG.disallowedPostalCodes ?? []
      if (!postalCodes.includes(value)) {
        postalCodes.push(value)
        this.config = { ...this.config, disallowedPostalCodes: postalCodes }
        this.requestUpdate()
      }
      input.value = ''
    }
  }

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

  @bound
  render(): TemplateResult {
    return html`
      <div class="checkbox-group">${this.renderValidate()}</div>
      <div class="input-group">${this.renderAllowedPostalCodes()} ${this.renderDisallowedPostalCodes()}</div>
    `
  }

  protected renderValidate(): TemplateResult {
    const enabled = this.config?.validate ?? DEFAULT_POSTAL_CODE_CONFIG.validate
    return html`
      <div class="row">
        <div class="input checkbox metadata">
          <ui-checkbox
            id="validate"
            .checked="${enabled}"
            name="validate"
            @change="${this.handleBooleanChange}"
          ></ui-checkbox>
          <div class="label">
            <label for="validate" class="body-medium">Validate</label>
            <span class="body-small meta"
              >Enable strict validation of the postal code. This is an experimental feature.</span
            >
          </div>
        </div>
        ${renderHelp('taxonomy', 'postalCode:validate')}
      </div>
    `
  }

  protected renderAllowedPostalCodes(): TemplateResult {
    const value = this.config?.allowedPostalCodes ?? DEFAULT_POSTAL_CODE_CONFIG.allowedPostalCodes
    const chips = (value || []).map(
      (postalCode, index) =>
        html`<ui-chip type="input" removable data-index="${index}" @remove="${this.handleRemovePostalCode}"
          >${postalCode}</ui-chip
        >`
    )
    return html`
      <div class="row input-row">
        <div class="input chips-input">
          <ui-outlined-text-field
            class="input"
            name="allowedPostalCodes"
            label="Allowed Postal Codes"
            @change="${this.handleAllowedPostalCodesChange}"
            supportingText="Add a postal code and press Enter to add it to the list."
          ></ui-outlined-text-field>
          <ui-chip-set>${chips}</ui-chip-set>
        </div>
        ${renderHelp('taxonomy', 'postalCode:allowedPostalCodes')}
      </div>
    `
  }

  protected renderDisallowedPostalCodes(): TemplateResult {
    const value = this.config?.disallowedPostalCodes ?? DEFAULT_POSTAL_CODE_CONFIG.disallowedPostalCodes
    const chips = (value || []).map(
      (postalCode, index) =>
        html`<ui-chip type="input" removable data-index="${index}" @remove="${this.handleRemoveDisallowedPostalCode}"
          >${postalCode}</ui-chip
        >`
    )
    return html`
      <div class="row input-row">
        <div class="input chips-input">
          <ui-outlined-text-field
            class="input"
            name="disallowedPostalCodes"
            label="Disallowed Postal Codes"
            @change="${this.handleDisallowedPostalCodesChange}"
            supportingText="Add a postal code and press Enter to add it to the list."
          ></ui-outlined-text-field>
          <ui-chip-set>${chips}</ui-chip-set>
        </div>
        ${renderHelp('taxonomy', 'postalCode:disallowedPostalCodes')}
      </div>
    `
  }
}
