/**
 * 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, state, property } from 'lit/decorators.js';
import { styles } from './nile-table-header-item.css';
import NileElement from '../internal/nile-element';
import { HasSlotController } from '../internal/slot';
import { createResizeHandler, resetAllColumnWidths } from '../internal/resizable-table-helper';

/**
 * Nile icon component.
 *
 * @tag nile-table-header-item
 *
 */
@customElement('nile-table-header-item')
export class NileTableHeaderItem extends NileElement {
  private readonly hasSlotController = new HasSlotController(this, '[default]');
  /**
   * The styles for TableHeaderItem
   * @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 sort functionality. */
  @property({ type: Boolean, reflect: true }) havesort = false;

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

  /** Places the icon . */
  @property({ type: String, reflect: true, attribute: 'icon-name' }) iconName =
    '';

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

  @state() sorting_ct = 0;

  /* #endregion */

  /* #region Methods */

  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
   */
  private handleSort(e: any) {
    this.sorting_ct++;
    let curr_sort_string = this.hasSlotController.host.innerHTML;
    const order = ['normal', 'asc', 'des'];
    this.emit('nile-click-sort', {
      value: { curr_sort_string, order: order[this.sorting_ct % 3] },
    });
  }

  private handleSearch(e: any) {
    this.emit('nile-search', { value: e.detail.value });
  }

  private handleResizeStart = createResizeHandler(this, 50);

  public render(): TemplateResult {
    return html`
      <div class="header__item__wrapper" part="nile__table-header-cell">
        <div class="headers">
          <slot> </slot>
          ${this.havesort && this.sorting_ct % 3 === 0
            ? html`<nile-icon
                name="var(--nile-icon-sort, var(--ng-icon-chevron-selector-vertical))"
                method="var(--nile-svg-method-fill, var(--ng-svg-method-stroke))"
                size="var(--nile-icon-size-16, var(--ng-icon-size-12))"
                @click=${this.handleSort}
                class="hover__arrow"
              ></nile-icon>`
            : null}
          ${this.havesort && this.sorting_ct % 3 === 1
            ? html`<nile-icon
                name="var(--nile-icon-sort-down, var(--ng-icon-arrow-down))"
                method="var(--nile-svg-method-fill, var(--ng-svg-method-stroke))"
                size="var(--nile-icon-size-16, var(--ng-icon-size-12))"
                class="stroke-width"
                @click=${this.handleSort}
              ></nile-icon>`
            : null}
          ${this.havesort && this.sorting_ct % 3 === 2
            ? html`<nile-icon
                name="var(--nile-icon-sort-up, var(--ng-icon-arrow-up))"
                method="var(--nile-svg-method-fill, var(--ng-svg-method-stroke))"
                size="var(--nile-icon-size-16, var(--ng-icon-size-12))"
                class="stroke-width"
                @click=${this.handleSort}
              ></nile-icon>`
            : null}
          ${this.iconName
            ? html` <nile-icon name="${this.iconName}" method="var(--nile-svg-method-fill, var(--ng-svg-method-stroke))" size="16"></nile-icon>`
            : html``}
          ${this.havefilter
            ? html` <nile-popover title="Filter" placement="bottom">
                <nile-icon name="var(--nile-icon-filter, var(--ng-icon-filter-lines))" size="16" method="var(--nile-svg-method-fill, var(--ng-svg-method-stroke))" slot="anchor"></nile-icon>
                <nile-input
                  placeholder="Search"
                  @nile-input=${this.handleSearch}
                  part="filter__search"
                ></nile-input>
                <slot name="filter__content" part="filter__content"></slot>
              </nile-popover>`
            : html``}
        </div>
        ${this.resizable 
          ? html`<div class="resizer" @mousedown=${this.handleResizeStart}></div>`
          : null}
      </div>`;
  }
}

export default NileTableHeaderItem;

declare global {
  interface HTMLElementTagNameMap {
    'nile-table-header-item': NileTableHeaderItem;
  }
}
