import { customElement, property, query, state } from 'lit/decorators.js';
import { classMap } from 'lit/directives/class-map.js';
import { ifDefined } from 'lit/directives/if-defined.js';
import { html, literal } from 'lit/static-html.js';
import { WaInvalidEvent } from '../../events/invalid.js';
import { MirrorValidator } from '../../internal/validators/mirror-validator.js';
import { watch } from '../../internal/watch.js';
import { WebAwesomeFormAssociatedElement } from '../../internal/webawesome-form-associated-element.js';
import nativeStyles from '../../styles/native/button.css';
import appearanceStyles from '../../styles/utilities/appearance.css';
import sizeStyles from '../../styles/utilities/size.css';
import variantStyles from '../../styles/utilities/variants.css';
import { LocalizeController } from '../../utilities/localize.js';
import '../icon/icon.js';
import '../spinner/spinner.js';
import styles from './button.css';

/**
 * @summary Buttons represent actions that are available to the user.
 * @documentation https://backers.webawesome.com/docs/components/button
 * @status stable
 * @since 2.0
 *
 * @dependency wa-icon
 * @dependency wa-spinner
 *
 * @event blur - Emitted when the button loses focus.
 * @event focus - Emitted when the button gains focus.
 * @event wa-invalid - Emitted when the form control has been checked for validity and its constraints aren't satisfied.
 *
 * @slot - The button's label.
 * @slot prefix - A presentational prefix icon or similar element.
 * @slot suffix - A presentational suffix icon or similar element.
 *
 * @csspart base - The component's base wrapper.
 * @csspart prefix - The container that wraps the prefix.
 * @csspart label - The button's label.
 * @csspart suffix - The container that wraps the suffix.
 * @csspart caret - The button's caret icon, a `<wa-icon>` element.
 * @csspart spinner - The spinner that shows when the button is in the loading state.
 *
 * @cssproperty --background-color - The button's background color when the button is not being interacted with.
 * @cssproperty --background-color-active - The button's background color when active.
 * @cssproperty --background-color-hover - The button's background color on hover.
 * @cssproperty --border-color - The color of the button's border when the button is not being interacted with.
 * @cssproperty --border-color-active - The color of the button's border when active.
 * @cssproperty --border-color-hover - The color of the button's border on hover.
 * @cssproperty --text-color - The color of the button's label when the button is not being interacted with.
 * @cssproperty --text-color-active - The color of the button's label when active.
 * @cssproperty --text-color-hover - The color of the button's label on hover.
 */
@customElement('wa-button')
export default class WaButton extends WebAwesomeFormAssociatedElement {
  static shadowStyle = [variantStyles, appearanceStyles, sizeStyles, nativeStyles, styles];

  static get validators() {
    return [...super.validators, MirrorValidator()];
  }

  assumeInteractionOn = ['click'];
  private readonly localize = new LocalizeController(this);

  @query('.wa-button') button: HTMLButtonElement | HTMLLinkElement;

  @state() visuallyHiddenLabel = false;
  @state() invalid = false;
  @property() title = ''; // make reactive to pass through

  /** The button's theme variant. Defaults to `neutral` if not within another element with a variant. */
  @property({ reflect: true, initial: 'neutral' })
  variant: 'neutral' | 'brand' | 'success' | 'warning' | 'danger' | 'inherit' = 'inherit';

  /** The button's visual appearance. */
  @property({ reflect: true, default: 'accent' })
  appearance: 'accent' | 'filled' | 'outlined' | 'plain' = 'accent';

  /** The button's size. */
  @property({ reflect: true, initial: 'medium' }) size: 'small' | 'medium' | 'large' | 'inherit' = 'inherit';

  /** Draws the button with a caret. Used to indicate that the button triggers a dropdown menu or similar behavior. */
  @property({ type: Boolean, reflect: true }) caret = false;

  /** Disables the button. Does not apply to link buttons. */
  @property({ type: Boolean }) disabled = false;

  /** Draws the button in a loading state. */
  @property({ type: Boolean, reflect: true }) loading = false;

  /** Draws a pill-style button with rounded edges. */
  @property({ type: Boolean, reflect: true }) pill = false;

  /**
   * The type of button. Note that the default value is `button` instead of `submit`, which is opposite of how native
   * `<button>` elements behave. When the type is `submit`, the button will submit the surrounding form.
   */
  @property() type: 'button' | 'submit' | 'reset' = 'button';

  /**
   * The name of the button, submitted as a name/value pair with form data, but only when this button is the submitter.
   * This attribute is ignored when `href` is present.
   */
  @property({ reflect: true }) name: string | null = null;

  /**
   * The value of the button, submitted as a pair with the button's name as part of the form data, but only when this
   * button is the submitter. This attribute is ignored when `href` is present.
   */
  @property({ reflect: true }) value: string | null = null;

  /** When set, the underlying button will be rendered as an `<a>` with this `href` instead of a `<button>`. */
  @property() href = '';

  /** Tells the browser where to open the link. Only used when `href` is present. */
  @property() target: '_blank' | '_parent' | '_self' | '_top';

  /** When using `href`, this attribute will map to the underlying link's `rel` attribute. */
  @property() rel?: string;

  /** Tells the browser to download the linked file as this filename. Only used when `href` is present. */
  @property() download?: string;

  /**
   * The "form owner" to associate the button with. If omitted, the closest containing form will be used instead. The
   * value of this attribute must be an id of a form in the same document or shadow root as the button.
   */
  @property({ reflect: true }) form: string | null = null;

  /** Used to override the form owner's `action` attribute. */
  @property({ attribute: 'formaction' }) formAction: string;

  /** Used to override the form owner's `enctype` attribute.  */
  @property({ attribute: 'formenctype' })
  formEnctype: 'application/x-www-form-urlencoded' | 'multipart/form-data' | 'text/plain';

  /** Used to override the form owner's `method` attribute.  */
  @property({ attribute: 'formmethod' }) formMethod: 'post' | 'get';

  /** Used to override the form owner's `novalidate` attribute. */
  @property({ attribute: 'formnovalidate', type: Boolean }) formNoValidate: boolean;

  /** Used to override the form owner's `target` attribute. */
  @property({ attribute: 'formtarget' }) formTarget: '_self' | '_blank' | '_parent' | '_top' | string;

  private handleClick() {
    const form = this.getForm();

    if (!form) return;

    const lightDOMButton = this.constructLightDOMButton();

    // form.append(lightDOMButton);
    this.parentElement?.append(lightDOMButton);
    lightDOMButton.click();
    lightDOMButton.remove();
  }

  private constructLightDOMButton() {
    const button = document.createElement('button');
    button.type = this.type;
    button.style.position = 'absolute';
    button.style.width = '0';
    button.style.height = '0';
    button.style.clipPath = 'inset(50%)';
    button.style.overflow = 'hidden';
    button.style.whiteSpace = 'nowrap';
    if (this.name) {
      button.name = this.name;
    }
    button.value = this.value || '';

    ['form', 'formaction', 'formenctype', 'formmethod', 'formnovalidate', 'formtarget'].forEach(attr => {
      if (this.hasAttribute(attr)) {
        button.setAttribute(attr, this.getAttribute(attr)!);
      }
    });

    return button;
  }

  private handleInvalid() {
    this.dispatchEvent(new WaInvalidEvent());
  }

  private handleLabelSlotChange(event: Event) {
    // If the only thing slotted in is a visually hidden element, we consider it a visually hidden label and apply a
    // class so we can adjust styles accordingly.
    const elements = (event.target as HTMLSlotElement).assignedElements({ flatten: true });
    if (elements.length === 1 && elements[0].localName === 'wa-visually-hidden') {
      this.visuallyHiddenLabel = true;
    }
  }

  private isButton() {
    return this.href ? false : true;
  }

  private isLink() {
    return this.href ? true : false;
  }

  @watch('disabled', { waitUntilFirstUpdate: true })
  handleDisabledChange() {
    this.updateValidity();
  }

  // eslint-disable-next-line
  setValue(..._args: Parameters<WebAwesomeFormAssociatedElement['setValue']>) {
    // This is just a stub. We don't ever actually want to set a value on the form. That happens when the button is clicked and added
    // via the light dom button.
  }

  /** Simulates a click on the button. */
  click() {
    this.button.click();
  }

  /** Sets focus on the button. */
  focus(options?: FocusOptions) {
    this.button.focus(options);
  }

  /** Removes focus from the button. */
  blur() {
    this.button.blur();
  }

  getBoundingClientRect(): DOMRect {
    let rect = super.getBoundingClientRect();
    let buttonRect = this.button.getBoundingClientRect();

    if (rect.width === 0 && buttonRect.width > 0) {
      return buttonRect;
    }

    return rect;
  }

  render() {
    const isLink = this.isLink();
    const tag = isLink ? literal`a` : literal`button`;

    /* eslint-disable lit/no-invalid-html */
    /* eslint-disable lit/binding-positions */
    return html`
      <${tag}
        part="base"
        class=${classMap({
          button: true,
          'wa-button': true,
          caret: this.caret,
          disabled: this.disabled,
          loading: this.loading,
          rtl: this.localize.dir() === 'rtl',
          'visually-hidden-label': this.visuallyHiddenLabel,
        })}
        ?disabled=${ifDefined(isLink ? undefined : this.disabled)}
        type=${ifDefined(isLink ? undefined : this.type)}
        title=${this.title /* An empty title prevents browser validation tooltips from appearing on hover */}
        name=${ifDefined(isLink ? undefined : this.name)}
        value=${ifDefined(isLink ? undefined : this.value)}
        href=${ifDefined(isLink ? this.href : undefined)}
        target=${ifDefined(isLink ? this.target : undefined)}
        download=${ifDefined(isLink ? this.download : undefined)}
        rel=${ifDefined(isLink && this.rel ? this.rel : undefined)}
        role=${ifDefined(isLink ? undefined : 'button')}
        aria-disabled=${this.disabled ? 'true' : 'false'}
        tabindex=${this.disabled ? '-1' : '0'}
        @invalid=${this.isButton() ? this.handleInvalid : null}
        @click=${this.handleClick}
      >
        <slot name="prefix" part="prefix" class="prefix"></slot>
        <slot part="label" class="label" @slotchange=${this.handleLabelSlotChange}></slot>
        <slot name="suffix" part="suffix" class="suffix"></slot>
        ${
          this.caret
            ? html`
                <wa-icon part="caret" class="caret" library="system" name="chevron-down" variant="solid"></wa-icon>
              `
            : ''
        }
        ${this.loading ? html`<wa-spinner part="spinner"></wa-spinner>` : ''}
      </${tag}>
    `;
  }
}
declare global {
  interface HTMLElementTagNameMap {
    'wa-button': WaButton;
  }
}
