import { html, LitElement } from 'lit'
import { customElement, property } from 'lit/decorators.js'
import { classMap } from 'lit/directives/class-map.js'
import type { TAccordionSkin } from 'shared-types'

export type TPktAccordionSkin = TAccordionSkin

export interface IPktAccordion {
  compact?: boolean
  skin?: TPktAccordionSkin
  ariaLabelledBy?: string
  name?: string
  /**
   * @description A unique identifier to connect the accordion with a heading
   */
}

export class PktAccordion extends LitElement implements IPktAccordion {
  // Properties
  @property({ type: String, reflect: true, attribute: 'aria-labelledby' }) ariaLabelledBy: string =
    ''
  @property({ type: Boolean, reflect: true, attribute: 'compact' }) compact: boolean = false
  @property({ type: String, reflect: true, attribute: 'skin' }) skin: TPktAccordionSkin =
    'borderless'
  @property({ type: String, reflect: true, attribute: 'name' }) name: string = ''

  updated(changedProperties: Map<string, any>) {
    if (changedProperties.has('skin')) {
      this.requestUpdate()
    }

    if (changedProperties.has('name')) {
      this.updateAccordionItemNames()
    }
  }

  private updateAccordionItemNames() {
    if (this.name) {
      const slot = this.renderRoot?.querySelector('slot')
      if (slot) {
        const assignedElements = slot.assignedElements()
        assignedElements.forEach((element) => {
          if (element.tagName.toLowerCase() === 'pkt-accordion-item') {
            if (!element.hasAttribute('name')) {
              element.setAttribute('name', this.name)
            }
          }
        })
      }
    }
  }

  firstUpdated() {
    const slot = this.renderRoot?.querySelector('slot')
    if (slot) {
      slot.addEventListener('slotchange', () => {
        this.updateAccordionItemNames()
      })
    }
  }

  render() {
    const accordionClasses = {
      'pkt-accordion': true,
      'pkt-accordion--compact': this.compact,
      [`pkt-accordion--${this.skin}`]: this.skin,
    }

    return html`
      <div
        part="container"
        class=${classMap(accordionClasses)}
        data-testid="pkt-accordion"
        aria-labelledby=${this.ariaLabelledBy}
      >
        <slot></slot>
      </div>
    `
  }
}

export default PktAccordion

try {
  customElement('pkt-accordion')(PktAccordion)
} catch (e) {
  console.warn('Forsøker å definere <pkt-accordion>, men den er allerede definert')
}
