import { injectStyle } from '@descope-ui/common/components-helpers';
import { createBaseInputClass } from '../../baseClasses/createBaseInputClass';
import { observeAttributes } from '../../helpers/componentHelpers';
import { createDispatchEvent } from '../../helpers/mixinsHelpers';

export const createBaseButtonSelectionGroupInternalClass = (componentName) => {
  class BaseButtonSelectionGroupInternalClass extends createBaseInputClass({
    componentName,
    baseSelector: 'slot',
  }) {
    constructor() {
      super();

      this.innerHTML = `
    <slot part="wrapper"></slot>
      `;
    }

    dispatchChange = createDispatchEvent.bind(this, 'change');

    get items() {
      return this.querySelector('slot').assignedElements();
    }

    get isReadonly() {
      return this.getAttribute('readonly') === 'true';
    }

    get size() {
      return this.getAttribute('size') || 'md';
    }

    // eslint-disable-next-line getter-return, class-methods-use-this
    get value() {
      // eslint-disable-next-line no-console
      console.warn('get value', 'is not implemented');
    }

    // eslint-disable-next-line class-methods-use-this
    set value(value) {
      // eslint-disable-next-line no-console
      console.warn('set value', 'is not implemented');
    }

    onSizeChange() {
      this.items.forEach((item) => {
        item.setAttribute('size', this.size);
      });
    }

    onReadOnlyChange() {
      this.querySelector('slot').toggleAttribute('inert', this.isReadonly);
    }

    // eslint-disable-next-line class-methods-use-this
    getValidity() {
      // eslint-disable-next-line no-console
      console.warn('getValidity', 'is not implemented');
    }

    onObservedAttributeChange(attrs) {
      attrs.forEach((attr) => {
        switch (attr) {
          case 'size':
            this.onSizeChange();
            break;
          case 'readonly':
            this.onReadOnlyChange();
            break;
          default:
            break;
        }
      });
    }

    init() {
      // we are adding listeners before calling to super because it's stopping the events
      this.addEventListener('focus', (e) => {
        // we want to ignore focus events we are dispatching
        if (e.isTrusted) {
          this.items[0]?.focus();
        }
      });

      super.init?.();

      observeAttributes(this, this.onObservedAttributeChange.bind(this), {
        includeAttrs: ['size', 'readonly'],
      });
    }
  }

  return BaseButtonSelectionGroupInternalClass;
};
