import { SingleColumnFormStyles } from '@things-factory/form-ui'
import '@things-factory/grist-ui'
import { i18next, localize } from '@things-factory/i18n-base'
import { client, store } from '@things-factory/shell'
import gql from 'graphql-tag'
import { css, html, LitElement } from 'lit-element'
import { connect } from 'pwa-helpers/connect-mixin'

class ExpiryDatePopup extends connect(store)(localize(i18next)(LitElement)) {
  static get properties() {
    return {
      inventory: Object
    }
  }

  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 {
          display: flex;
          flex-direction: column;
          height: 100vh;
          justify-content: space-evenly;
          padding: 0 20px;
          margin: var(--button-container-margin);
          text-align: var(--button-container-align);
          background-color: var(--button-container-background);
        }
      `
    ]
  }

  render() {
    return html`
      <form id="input-form" class="single-column-form">
        <fieldset>
          <label>${i18next.t('label.expiry_date')}</label>
          <input name="expDate" type="date" />
        </fieldset>
      </form>
      <div class="button-container">
        <mwc-button
          raised
          @click="${this._updateExpirationDate.bind(this)}"
          label="${i18next.t('button.update')}"
        ></mwc-button>
      </div>
    `
  }

  get expDateInput() {
    return this.shadowRoot.querySelector('input[name="expDate"]')
  }

  async _updateExpirationDate() {
    try {
      this._validateInput()
      delete this.inventory.product.sku
      delete this.inventory.product.isRequiredCheckExpiry
      delete this.inventory.checked
      delete this.inventory.reusablePalletName
      delete this.inventory.packingTypeSize
      delete this.inventory.actualQty
      delete this.inventory.__seq__
      delete this.inventory.__origin__

      const response = await client.mutate({
        mutation: gql`
          mutation updateInventory($patch: InventoryPatch!) {
            updateInventory(patch: $patch) {
              expirationDate
            }
          }
        `,
        variables: {
          patch: { ...this.inventory, expirationDate: this.expDateInput.value }
        }
      })

      if (!response.errors) {
        const expirationDate = response.data.updateInventory.expirationDate
        this.dispatchEvent(new CustomEvent('updated-expiry-date', { detail: expirationDate }))
        this._showToast({ message: i18next.t('text.expiration_date_updated') })
        history.back()
      }
    } catch (e) {
      this._showToast(e)
    }
  }

  _validateInput() {
    if (!this.expDateInput.value) {
      this._focusOnExipryDateInput()
      throw new Error(i18next.t('text.expiry_date_is_empty'))
    }
  }

  _focusOnExipryDateInput() {
    setTimeout(() => this.expDateInput.focus(), 100)
  }

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

window.customElements.define('expiry-date-popup', ExpiryDatePopup)
