import '@things-factory/grist-ui'
import './vas-selector'

import gql from 'graphql-tag'
import { css, html, LitElement } from 'lit-element'

import { SingleColumnFormStyles } from '@things-factory/form-ui'
import { i18next, localize } from '@things-factory/i18n-base'
import { client } from '@things-factory/shell'

//vas --inbound
class AdjustPalletQty extends localize(i18next)(LitElement) {
  static get properties() {
    return {
      config: String,
      record: Object,
      repalletizingClick: Boolean
    }
  }
  static get styles() {
    return [
      SingleColumnFormStyles,
      css`
        :host {
          padding: 10px;
          display: flex;
          flex-direction: column;
          overflow-x: overlay;
          background-color: var(--main-section-background-color);
        }
        .button-container {
          padding: var(--button-container-padding);
          margin: var(--button-container-margin);
          margin-top: auto;
          text-align: var(--button-container-align);
          background-color: var(--button-container-background);
          height: var(--button-container-height);
        }
        .button-container button {
          background-color: var(--button-container-button-background-color);
          border-radius: var(--button-container-button-border-radius);
          height: var(--button-container-button-height);
          border: var(--button-container-button-border);
          margin: var(--button-container-button-margin);

          padding: var(--button-padding);
          color: var(--theme-white-color);
          font: var(--button-font);
          text-transform: var(--button-text-transform);
        }
        .button-container button:hover,
        .button-container button:active {
          background-color: var(--button-background-focus-color);
        }
      `
    ]
  }
  constructor() {
    super()
    this.repalletizingClick = true
  }
  render() {
    return html`
      <form
        class="single-column-form"
        @keypress="${e => {
          if (e.keyCode === 13) {
            e.preventDefault()
            this._adjustPalletQty()
          }
        }}"
      >
        <fieldset>
          <legend>${i18next.t('title.product')}</legend>
          <label>${i18next.t('label.batch_no')}</label>
          <input name="batchId" readonly value="${this.record.batchId}" />

          <label>${i18next.t('label.product')}</label>
          <input
            name="productName"
            readonly
            value="${`${this.record.product.name} ${
              this.record.product.description ? `(${this.record.product.description})` : ''
            }`}"
          />

          <label>${i18next.t('label.pack_qty')}</label>
          <input name="packQty" readonly value="${this.record.packQty}" />
        </fieldset>

        <fieldset>
          <legend>${i18next.t('title.adjust_pallet_qty')}</legend>
          <label>${i18next.t('label.pallet_qty')}</label>
          <input
            name="palletQty"
            type="number"
            min="1"
            value="${this.record.palletQty ? this.record.palletQty : ''}"
            required
          />
        </fieldset>
      </form>

      <div class="button-container">
        <mwc-button raised @click="${this._adjustPalletQty.bind(this)}">${i18next.t('button.adjust')}</mwc-button>
      </div>
    `
  }

  get _form() {
    return this.shadowRoot.querySelector('form')
  }

  get _palletQtyInput() {
    return this.shadowRoot.querySelector('input[name=palletQty]')
  }

  firstUpdated() {
    this._focusOnInput()
  }

  _focusOnInput() {
    setTimeout(() => this._palletQtyInput.select(), 100)
  }

  async _adjustPalletQty() {
    try {
      this._validate()

      const response = await client.mutate({
        mutation: gql`
          mutation updateOrderProduct($name: String!, $patch: OrderProductPatch!) {
            updateOrderProduct(name: $name, patch: $patch) {
              name
            }
          }
        `,
        variables: { name: this.record?.name, patch: { palletQty: parseInt(this._palletQtyInput.value) } }
      })

      if (!response.errors) {
        this.dispatchEvent(
          new CustomEvent('pallet-adjusted', {
            detail: {
              palletQty: parseInt(this._palletQtyInput.value)
            }
          })
        )

        history.back()
      }
    } catch (e) {
      this._showToast(e)
    }
  }

  _validate() {
    if (!this._form.checkValidity()) throw new Error(i18next.t('text.invalid_form'))
  }

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

window.customElements.define('adjust-pallet-qty', AdjustPalletQty)
