/**
 * Copyright Aquera Inc 2023
 *
 * This source code is licensed under the BSD-3-Clause license found in the
 * LICENSE file in the root directory of this source tree.
 */

import {
  LitElement,
  html,
  CSSResultArray,
  TemplateResult,
  PropertyValues,
} from 'lit';
import { customElement, property } from 'lit/decorators.js';
import { styles } from './nile-table-cell-item.css';
import NileElement from '../internal/nile-element';
import { HasSlotController } from '../internal/slot';
import { createResizeHandler, resetAllColumnWidths } from '../internal/resizable-table-helper';

/**
 * Nile table Cell Item component.
 *
 * @tag nile-table-cell-item
 *
 */
@customElement('nile-table-cell-item')
export class NileTableCellItem extends NileElement {
  private readonly hasSlotController = new HasSlotController(this, '[default]');
  /**
   * The styles for TableCellItem
   * @remarks If you are extending this class you can extend the base styles with super. Eg `return [super(), myCustomStyles]`
   */
  public static get styles(): CSSResultArray {
    return [styles];
  }

  /** Enables the resize functionality. */
  @property({ type: Boolean, reflect: true }) resizable = false;

  /* #endregion */

  /* #region Methods */

  private handleResizeStart = createResizeHandler(this, 50);

  protected updated(changedProperties: PropertyValues) {
    super.updated(changedProperties);
    
    if (changedProperties.has('resizable')) {
      if (!this.resizable) {
        const tableBody = this.closest('nile-table-body');
        if (tableBody) {
          resetAllColumnWidths(tableBody);
        }
      }
    }
  }

  /**
   * Render method
   * @slot This is a slot test
   */
  public render(): TemplateResult {
    if (this.resizable) {
      return html`
        <div class="cell__wrapper" part="nile__table-cell">
          ${this.hasSlotController.test('[default]')
            ? html` <div class="column" part="nile__table-cell"><slot></slot></div>`
            : ''}
          <div class="resizer" @mousedown=${this.handleResizeStart}></div>
        </div>
      `;
    } else {
      return html`
        ${this.hasSlotController.test('[default]')
          ? html` <slot class="column" part="nile__table-cell"> </slot>`
          : ''}
      `;
    }
  }

  /* #endregion */
}

export default NileTableCellItem;

declare global {
  interface HTMLElementTagNameMap {
    'nile-table-cell-item': NileTableCellItem;
  }
}
