import '@things-factory/barcode-ui'
import { SingleColumnFormStyles } from '@things-factory/form-ui'
import { client } from '@things-factory/shell'
import gql from 'graphql-tag'
import { i18next, localize } from '@things-factory/i18n-base'
import { css, html, LitElement } from 'lit-element'
import { isMobileDevice } from '@things-factory/utils'
import { ScrollbarStyles } from '@things-factory/styles'

class CheckInventoryPopup extends localize(i18next)(LitElement) {
  static get properties() {
    return {
      worksheetName: String,
      bizplaceName: String,
      bizplaceId: String,
      cycleCountNo: String,
      missingInventory: Object,
      config: Object,
      data: Object
    }
  }

  static get styles() {
    return [
      ScrollbarStyles,
      SingleColumnFormStyles,
      css`
        :host {
          padding: 10px;
          display: flex;
          flex-direction: column;
          overflow-x: overlay;
          background-color: var(--main-section-background-color);
        }
        .grist {
          background-color: var(--main-section-background-color);
          display: flex;
          flex-direction: column;
          flex: 1;
          overflow-y: auto;
        }
        data-grist {
          overflow-y: hidden;
          flex: 1;
        }
        .input-container {
          display: flex;
        }
        .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);
        }
        .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);
        }
        .button-container > barcode-scanable-input {
          margin: auto;
        }
        [field-2column] {
          background-color: var(--theme-white-color);
          margin: var(--margin-wide) 0;
          padding: var(--padding-wide);
          border-radius: var(--border-radius);
          box-shadow: var(--box-shadow);
          display: grid;
          grid-template-columns: 1fr 1fr;
          gap: 5px 15px;
          clear: both;
          max-width: var(--input-container-max-width);
        }
        [field] {
          display: flex;
          flex-direction: column;
          padding-bottom: var(--padding-default);
        }
        [grid-span] {
          grid-column: span 3;
        }
        label {
          display: flex;
          flex-direction: column;

          font: var(--label-font);
          color: var(--label-color);
          text-transform: var(--label-text-transform);
        }
        input {
          border: var(--border-dark-color);
          border-radius: var(--border-radius);
          margin: var(--input-margin);
          padding: var(--input-padding);
          background-color: var(--theme-white-color);
          font: var(--input-font);

          flex: 1;
        }
        legend mwc-icon {
          vertical-align: middle;
          margin: var(--grist-title-icon-margin);
          font-size: var(--grist-title-icon-size);
          color: var(--grist-title-icon-color);
          cursor: pointer;
        }
      `
    ]
  }

  connectedCallback() {
    super.connectedCallback()
  }

  async firstUpdated() {
    await this.updateComplete

    this.focusOnInput()
    this.initConfig()
    this.dataGrist.fetch()
  }

  focusOnInput() {
    if (this.enableCartonLabel) {
      this.cartonIdInput.value = ''
      this.focusOnCartonInput()
    } else {
      this.palletIdInput.value = ''
      this.focusOnPalletInput()
    }
  }
  initConfig() {
    this.config = {
      list: {
        fields: ['locationName', 'productSku', 'status']
      },
      pagination: { infinite: true },
      rows: {
        selectable: { multiple: false },
        appendable: false
      },
      columns: [
        { type: 'gutter', gutterName: 'sequence' },
        {
          type: 'string',
          name: 'locationName',
          header: i18next.t('field.location'),
          sortable: true,
          width: 100
        },
        {
          type: 'string',
          name: 'productSku',
          header: i18next.t('field.sku'),
          sortable: true,
          width: 230
        },
        {
          type: 'string',
          name: 'status',
          header: i18next.t('field.status'),
          sortable: true,
          width: 130
        }
      ]
    }
    this.dataGrist.fetch()
  }

  async pageUpdated(changes, lifecycle) {
    if (this.active) {
      await this.updateComplete

      this.dataGrist.fetch()
    }
  }
  get cartonIdInput() {
    return this.shadowRoot.querySelector('barcode-scanable-input[name=cartonId]').shadowRoot.querySelector('input')
  }

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

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

  get infoForm() {
    return this.renderRoot.querySelector('form#info-form')
  }

  get dataGrist() {
    return this.shadowRoot.querySelector('data-grist')
  }

  render() {
    return html`
      <form id="info-form" class="single-column-form">
        <legend>${i18next.t('title.scan_area')}</legend>
        ${this.enableCartonLabel
          ? html` <label>${i18next.t('label.carton_id')}</label>
              <barcode-scanable-input
                name="cartonId"
                custom-input
                @keypress="${async e => {
                  if (e.keyCode === 13) {
                    e.preventDefault()
                    if (this.cartonIdInput.value) {
                      this.cartonId = this.cartonIdInput.value
                      this.fetchHandler(this.bizplaceId)
                    }
                  }
                }}"
              ></barcode-scanable-input>`
          : html`
              <label>${i18next.t('label.lot_id')}</label>
              <barcode-scanable-input
                name="palletId"
                custom-input
                @keypress="${async e => {
                  if (e.keyCode === 13) {
                    e.preventDefault()
                    if (this.palletIdInput.value) {
                      this.palletId = this.palletIdInput.value
                      this.fetchHandler(this.bizplaceId)
                    }
                  }
                }}"
              ></barcode-scanable-input>
            `}
        <label>${i18next.t('label.product_info')}</label>
        <barcode-scanable-input
          name="productInfo"
          custom-input
          @keypress="${async e => {
            if (e.keyCode === 13) {
              e.preventDefault()
              if (this.productInfoInput.value) {
                this.productInfo = this.productInfoInput.value
                this.fetchHandler(this.bizplaceId)
              }
            }
          }}"
        ></barcode-scanable-input>
      </form>
      <data-grist .mode=${'GRID'} .config=${this.config} .data=${this.data}></data-grist>
    `
  }

  focusOnCartonInput() {
    this.cartonIdInput.focus()
  }

  focusOnPalletInput() {
    this.palletIdInput.focus()
  }

  focusOnProductInfoInput() {
    this.productInfoInput.focus()
  }

  constructor() {
    super()
    this.data = { records: [] }
  }

  async fetchHandler(bizplaceId) {
    try {
      const variables = {
        cartonId: this.enableCartonLabel ? this.cartonId : null,
        palletId: !this.enableCartonLabel ? this.palletId : null,
        bizplaceId,
        worksheetName: this.worksheetName,
        cycleCountNo: this.cycleCountNo,
        productInfo: this.productInfoInput.value
      }

      const response = await client.query({
        query: gql`
          query inventoryByCycleCount(
            $cartonId: String
            $palletId: String
            $productInfo: String
            $bizplaceId: String!
            $cycleCountNo: String!
            $worksheetName: String!
          ) {
            inventoryByCycleCount(
              cartonId: $cartonId
              palletId: $palletId
              productInfo: $productInfo
              bizplaceId: $bizplaceId
              cycleCountNo: $cycleCountNo
              worksheetName: $worksheetName
            ) {
              items {
                status
                originLocationName
                inspectedLocationName
                sku
              }
            }
          }
        `,
        variables
      })

      if (!response.errors) {
        const { items } = response.data.inventoryByCycleCount
        this.data = {
          records:
            items && items.length
              ? items.map(item => ({
                  status: item.status,
                  locationName: item.inspectedLocationName || item.originLocationName,
                  productSku: item.sku
                }))
              : []
        }

        if (!items.length) {
          this._showToast({ message: i18next.t('text.the_inventory_not_in_this_worksheet') })
        }
      } else {
        throw new Error(response.errors)
      }
    } catch (e) {
      this._showToast(e)
    }
  }

  selectOnInput(input) {
    setTimeout(() => input.select(), 100)
  }

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

window.customElements.define('check-inventory-popup', CheckInventoryPopup)
