/* eslint-disable no-param-reassign */
import { GridSortColumn } from '@vaadin/grid/vaadin-grid-sort-column';

export class GridItemDetailsColumnClass extends GridSortColumn {
  get sortable() {
    return this.getAttribute('sortable') === 'true';
  }

  // eslint-disable-next-line class-methods-use-this
  _defaultRenderer(cell, _col, model) {
    const grid = _col._gridValue;
    const itemIdx = grid.detailsOpenedItems?.indexOf(model.item) ?? -1;
    const isOpened = itemIdx !== -1;

    const toggleIcon = document.createElement('vaadin-icon');
    toggleIcon.icon = isOpened ? 'vaadin:angle-up' : 'vaadin:angle-down';
    toggleIcon.classList.add('toggle-details-button', isOpened ? 'opened' : 'closed');
    cell.innerHTML = '';
    cell.append(toggleIcon);

    toggleIcon.onclick = () => {
      grid.detailsOpenedItems = isOpened
        ? grid.detailsOpenedItems.toSpliced(itemIdx, 1)
        : [...grid.detailsOpenedItems, model.item];
    };
  }

  _defaultHeaderRenderer(root, _column) {
    if (this.sortable) {
      super._defaultHeaderRenderer(root, _column);

      return;
    }

    this.__setTextContent(root, this.__getHeader(this.header, this.path));
  }
}
