import { html, nothing, TemplateResult } from "lit";
import { property, queryAsync, state } from "lit/decorators.js";
import { classMap } from "lit/directives/class-map.js";
import { when } from 'lit/directives/when.js';
import { EventUtils } from "@api-client/core/build/browser.js"; // build/src/lib/events/Utils.js
import { UiElement } from "../UiElement.js";
import UiRipple from "../effects/ripple.js";
import { ripple } from '../effects/rippleDirective.js';
import { close, arrowDropDown, check } from "../icons/Icons.js";
import { isDisabled, setDisabled } from "../lib/disabled.js";
import { BeginPressConfig, EndPressConfig } from "../controllers/ActionController.js";
import '../../define/ui/ui-ripple.js';

export enum ChipType {
  assist = 'assist',
  filter = 'filter',
  input = 'input',
  suggestion = 'suggestion',
}

/**
 * @slot icon - The leading icon, sized 18x18 px
 * @slot avatar - The leading image, sized 24x24 px
 * @fires list - When the user requested to activate the list associated with the element.
 * @fires select - When the checked state changed through a user interaction. This only related to `filter` chips. Note, `select` is dispatched just before the `click` event.
 */
export default class UiChip extends UiElement {
  /**
   * Whether the chip is disabled. The user can't interact with the chip when `true`.
   * @attribute
   */
  @property({ type: Boolean, reflect: true }) 
  get disabled(): boolean {
    return isDisabled(this);
  }

  set disabled(value: boolean) {
    const old = isDisabled(this);
    setDisabled(this, value);
    this.requestUpdate('disabled', old);
  }

  /**
   * The type of the rendered chip.
   * @attribute
   * 
   * @see https://m3.material.io/components/chips/guidelines
   */
  @property({ type: String }) type: ChipType;

  /**
   * Whether the chip should be rendered as elevated.
   * @attribute
   */
  @property({ type: Boolean, reflect: true }) elevated?: boolean;

  /**
   * Whether the chip renders the "close" icon at the end.
   * @attribute
   */
  @property({ type: Boolean, reflect: true }) closable?: boolean;

  /**
   * Whether the chip is currently checked.
   * Note, this controls the presentation layer only. It has no meaning when it comes to forms and inputs.
   * @attribute
   */
  @property({ type: Boolean, reflect: true }) checked?: boolean;

  /**
   * The ID attribute of the list element that is rendered after activating the chip.
   * When this is set the chip renders the dropdown icon at the end and sets `aria-*` 
   * attributes informing the assistive technology that this chip controls a list.
   * 
   * @attribute
   */
  @property({ type: String, reflect: true }) list?: string;

  @queryAsync('ui-ripple') protected ripple!: Promise<UiRipple | null>;

  @state() protected showRipple = false;

  /**
   * Determines when the element has an icon in the "icon" slot.
   */
  @state() protected hasIcon: boolean;

  /**
   * Determines when the element has an image in the "avatar" slot.
   */
  @state() protected hasAvatar: boolean;

  constructor() {
    super();

    this.disabled = false;
    this.type = ChipType.assist;
    this.hasIcon = false;
    this.hasAvatar = false;

    this.actionController.cancelKeyboardEvents = true;

    this.addEventListener('click', this.handleClick.bind(this));
    this.addEventListener('keydown', this.handleKeyDown.bind(this));
    this.addEventListener('keyup', this.handleKeyUp.bind(this));
    this.addEventListener('pointerdown', this.handlePointerDown.bind(this));
    this.addEventListener('pointerup', this.handlePointerUp.bind(this));
    this.addEventListener('pointercancel', this.handlePointerCancel.bind(this));
    this.addEventListener('pointerleave', this.handlePointerLeave.bind(this));
    this.addEventListener('contextmenu', this.handleContextMenu.bind(this));
    this.addEventListener('focus', this.handleFocus.bind(this));
    this.addEventListener('blur', this.handleBlur.bind(this));
  }

  override connectedCallback(): void {
    super.connectedCallback();
    if (!this.hasAttribute('role')) {
      this.setAttribute('role', 'button');
    }
    if (!this.hasAttribute('tabindex') && !this.disabled) {
      this.setAttribute('tabindex', '0');
    }
  }

  protected async pressRipple(): Promise<void> {
    const element = await this.getRipple();
    if (element && !element.isPressed) {
      element.beginPress();
    }
  }

  protected async endRipple(): Promise<void> {
    const element = await this.getRipple();
    element?.endPress();
  }

  override beginPress(options: BeginPressConfig): void {
    super.beginPress(options);
    this.pressRipple();
  }

  override async handleKeyDown(e: KeyboardEvent): Promise<void> {
    super.handleKeyDown(e);
    if (this.type === ChipType.filter && e.code === 'ArrowDown') {
      e.preventDefault();
      this.listAction();
    } else if (this.closable && e.code === 'Backspace') {
      e.preventDefault();
      this.closeAction();
    }
  }

  protected async handleFocus(): Promise<void> {
    const element = await this.getRipple();
    element?.beginFocus();
  }

  protected async handleBlur(): Promise<void> {
    const element = await this.getRipple();
    element?.endFocus();
  }

  protected readonly getRipple = (): Promise<UiRipple | null> => {
    this.showRipple = true;
    return this.ripple;
  };

  override endPress(info: EndPressConfig): void {
    super.endPress(info);
    this.endRipple();
    const { cancelled, reason } = info;
    if (cancelled) {
      return;
    }
    if (reason === 'enter' || reason === 'space') {
      this.click();
    }
  }

  override handleClick(e: MouseEvent): void {
    super.handleClick(e);
    if (this.type === ChipType.filter) {
      this.toggleChecked();
    }
  }

  /**
   * Toggles the "filter" type of the chip.
   */
  toggleChecked(): void {
    this.checked = !this.checked;
    this.dispatchEvent(new Event('select'));
  }

  /**
   * Sets the `hasIcon` state property when the "icon" slot change event is dispatched.
   */
  protected handleIconSlotChange(e: Event): void {
    const slot = e.target as HTMLSlotElement;
    this.hasIcon = !!slot.assignedNodes().length;
  }

  /**
   * Sets the `_hasAvatar` state property when the "avatar" slot change event is dispatched.
   */
  protected handleAvatarSlotChange(e: Event): void {
    const slot = e.target as HTMLSlotElement;
    this.hasAvatar = !!slot.assignedNodes().length;
  }

  protected handleListClick(e: Event): void {
    e.preventDefault();
    e.stopPropagation();
    this.listAction();
  }

  protected handleClose(e: Event): void {
    e.preventDefault();
    e.stopPropagation();
    this.closeAction();
  }

  protected async closeAction(): Promise<void> {
    this.dispatchEvent(new Event('close'));
  }

  protected async listAction(): Promise<void> {
    this.dispatchEvent(new Event('list'));
  }

  protected override render(): TemplateResult {
    const { pressed = false } = this;
    const containerClasses = classMap({
      surface: true,
      withIcon: this.hasIcon,
      withAvatar: this.hasAvatar,
      pressed,
    });
    return html`
    <div class="${containerClasses}" ${ripple(this.getRipple)}>
      <div class="container"></div>
      ${when(this.showRipple, this.renderRipple)}
      <div class="content">
        ${this.renderLeadingIcon()}
        ${this.renderAvatar()}
        <slot></slot>
        ${this.renderTrailingIcon()}
      </div>
    </div>
    `;
  }

  protected renderLeadingIcon(): TemplateResult | typeof nothing {
    const { type } = this;
    if (type === ChipType.suggestion) {
      return nothing;
    }
    if (type === ChipType.filter) {
      const iconClasses = classMap({
        'leading-icon': true,
        'check-mark': true,
        checked: !!this.checked,
      });
      return html`<span class="${iconClasses}" role="presentation">${check}</span>`;
    }
    return html`<slot name="icon" @slotchange="${this.handleIconSlotChange}"></slot>`;
  }

  protected renderAvatar(): TemplateResult | typeof nothing {
    const { type } = this;
    if (type === ChipType.input) {
      return html`<slot name="avatar" @slotchange="${this.handleAvatarSlotChange}"></slot>`;
    }
    return nothing;
  }

  protected renderTrailingIcon(): TemplateResult | typeof nothing {
    const { closable=false, list, type } = this;
    if (type === ChipType.filter) {
      if (list) {
        return html`<span class="trailing-icon" role="presentation" @click="${this.handleListClick}" @keypress="${EventUtils.cancelEvent}">${arrowDropDown}</span>`;
      }
    }
    if (type === ChipType.input && closable) {
      return html`<span 
        class="trailing-icon" 
        @click="${this.handleClose}" 
        @keypress="${EventUtils.cancelEvent}"
        role="button"
        aria-label="Activate to close or disabled this chip."
      >${close}</span>`;
    }
    return nothing;
  }

  protected renderRipple = (): TemplateResult => {
    const { disabled } = this;
    return html`<ui-ripple class="ripple" ?disabled="${disabled}"></ui-ripple>`;
  };
}
