import { getComponentName } from '../../../helpers/componentHelpers';
import { createBaseButtonSelectionGroupInternalClass } from '../createBaseButtonSelectionGroupInternalClass';

export const componentName = getComponentName('button-selection-group-internal');

export class ButtonSelectionGroupInternalClass extends createBaseButtonSelectionGroupInternalClass(
  componentName
) {
  getSelectedNode() {
    return this.items.find((item) => item.hasAttribute('selected'));
  }

  get allowDeselect() {
    return this.getAttribute('allow-deselect') === 'true';
  }

  removeSelected() {
    this.getSelectedNode()?.removeAttribute('selected');
  }

  onClick(e) {
    if (e.target !== e.currentTarget) {
      if (e.target === this.getSelectedNode() && this.allowDeselect) {
        this.removeSelected();
      } else {
        this.setSelected(e.target);
      }
      this.dispatchChange();
    }
  }

  setSelected(node) {
    if (node !== this.getSelectedNode()) {
      this.removeSelected();
      node?.setAttribute('selected', 'true');
    }
  }

  get defaultValue() {
    return this.getAttribute('default-value');
  }

  setDefaultValue() {
    // we want to defer this action until all attributes are synched
    setTimeout(() => {
      if (this.defaultValue) {
        this.value = this.defaultValue;
        this.setCustomValidity();
      }
    });
  }

  get value() {
    return this.getSelectedNode()?.value || '';
  }

  set value(value) {
    const node = this.items.find((child) => child.value === value);
    this.setSelected(node);
  }

  getValidity() {
    if (this.isRequired && !this.value) {
      return { valueMissing: true };
    }

    return {};
  }

  init() {
    super.init();

    this.setDefaultValue();

    this.querySelector('slot').addEventListener('click', this.onClick.bind(this));
  }
}
