import { i18next, localize } from '@things-factory/i18n-base'
import { css, html, LitElement } from 'lit-element'
import { SingleColumnFormStyles } from '@things-factory/form-ui'
import { client } from '@things-factory/shell'
import { PALLET_STATUS } from '../constants'
import gql from 'graphql-tag'

class PopupReusablePallet extends localize(i18next)(LitElement) {
  static get properties() {
    return {
      label: String,
      value: String,
      reusablePalletInput: String,
      _reusablePallet: Object
    }
  }

  static get styles() {
    return [
      SingleColumnFormStyles,
      css`
        :host {
          display: flex;
          flex-direction: column;
          overflow-x: overlay;
          background-color: var(--main-section-background-color);
        }
        .container {
          display: flex;
          flex-direction: column;
          flex: 1;
        }
        .container > barcode-scannable-input {
          flex: 1;
          resize: none;
          border-color: var(--primary-color);
          padding: 5px;
          margin: 10px;
          outline: none;
        }
        .button-container {
          padding: var(--button-container-padding);
          margin: var(--button-container-margin);
          text-align: var(--button-container-align);
          background-color: var(--button-container-background);
          height: var(--button-container-height);
        }
      `
    ]
  }

  get reusablePalletInput() {
    return this.shadowRoot
      .querySelector('barcode-scanable-input[name=reusablePalletId]')
      .shadowRoot.querySelector('input')
  }

  firstUpdated() {}

  updated(changedProps) {}

  render() {
    return html`
      <div class="container">
        <form id="input-form" class="single-column-form">
          <fieldset>
            <label>${this.label}</label>
            <barcode-scanable-input
              name="reusablePalletId"
              custom-input
              without-enter
              @keypress="${async e => {
                if (e.keyCode !== 13) return
                e.preventDefault()
                await this._verifyInput()
              }}"
            ></barcode-scanable-input>
          </fieldset>
        </form>
      </div>
      <div class="button-container">
        <mwc-button
          raised
          @click="${async () => await this._verifyInput()}"
          label="${i18next.t('button.confirm')}"
        ></mwc-button>
        <mwc-button
          raised
          @click="${async () => {
            this.dispatchEvent(new CustomEvent('normalPallet'))
            history.back()
          }}"
          label="${i18next.t('button.disable')}"
        ></mwc-button>
      </div>
    `
  }

  async _verifyInput() {
    if (!this.reusablePalletInput.value) return this._showToast({ message: i18next.t('text.reusable_pallet_id_empty') })

    if (!(await this._isReusablePallet())) return this._showToast({ message: i18next.t('text.not_a_reusable_pallet') })

    this._showToast({
      message: `${i18next.t('text.now_using_reusable_pallet')} ${this.reusablePalletInput.value}`
    })
    this.dispatchEvent(
      new CustomEvent('submit', {
        detail: { reusablePallet: this._reusablePallet }
      })
    )
    history.back()
  }

  async _isReusablePallet() {
    try {
      const response = await client.query({
        query: gql`
          query palletByStatus($name: String!, $status: String!) {
            palletByStatus(name: $name, status: $status) {
              id
              name
            }
          }
        `,
        variables: { name: this.reusablePalletInput.value, status: PALLET_STATUS.ACTIVE.value }
      })

      if (response.data.palletByStatus) {
        this._reusablePallet = response.data.palletByStatus
        return true
      }

      return false
    } catch (e) {
      this._showToast(e)
    }
  }

  _showToast({ type, message }) {
    document.dispatchEvent(
      new CustomEvent('notify', {
        detail: {
          type,
          message
        }
      })
    )
  }
}

window.customElements.define('popup-reusable-pallet', PopupReusablePallet)
