import '@things-factory/grist-ui'

import gql from 'graphql-tag'
import { css, html, LitElement } from 'lit-element'
import { connect } from 'pwa-helpers/connect-mixin'

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

class UndoUnloadPopup extends connect(store)(localize(i18next)(LitElement)) {
  static get properties() {
    return {
      _selectedRecords: Array,
      config: Object,
      data: Object,
      enableCartonLabel: Boolean,
      enableProductScanning: Boolean,
      orderType: String,
      orderNo: String,
      unloadedInventories: Array,
      _isExecuting: Boolean
    }
  }

  constructor() {
    super()
    this._selectedRecords = []
    this._isExecuting = false
  }

  static get styles() {
    return [
      SingleColumnFormStyles,
      css`
        .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);
        }
        data-grist {
          overflow-y: hidden;
          flex: 1;
        }
        .grist {
          display: flex;
          flex-direction: column;
          flex: 1;
          overflow-y: auto;
        }
        :host {
          padding: 10px;
          display: flex;
          flex-direction: column;
          overflow: hidden;
          background-color: white;
        }
      `
    ]
  }

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

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

  get inputForm() {
    return this.shadowRoot.querySelector('form#input-form')
  }

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

  render() {
    return html`
      <form id="input-form" class="single-column-form">
        <fieldset>
          ${this.enableCartonLabel
            ? html`<label>${i18next.t('label.carton_id')}</label>
                <barcode-scanable-input
                  name="cartonId"
                  custom-input
                  @keypress="${this._populateTargetedInventory.bind(this)}"
                ></barcode-scanable-input>`
            : html`<label>${i18next.t('label.lot_id')}</label>
                <barcode-scanable-input
                  name="lotId"
                  custom-input
                  @keypress="${this._populateTargetedInventory.bind(this)}"
                ></barcode-scanable-input>`}
        </fieldset>
      </form>

      <div class="grist">
        <data-grist
          id="grist"
          .mode=${isMobileDevice() ? 'LIST' : 'GRID'}
          .config=${this.config}
          .data="${this.data}"
          .selectedRecords=${this._selectedRecords}
        ></data-grist>
      </div>

      <div class="button-container">
        <mwc-button
          raised
          @click="${this._undoUnloading.bind(this)}"
          label="${i18next.t('button.undo')}"
          ?disabled=${this._isExecuting}
        ></mwc-button>
      </div>
    `
  }

  firstUpdated() {
    this.config = {
      pagination: { infinite: true },
      rows: { selectable: { multiple: true }, appendable: false },
      list: {
        fields: ['palletId', 'cartonId', 'batchId', 'sku', 'product', 'packingType', 'packingSize', 'qty', 'status']
      },
      columns: [
        { type: 'gutter', gutterName: 'sequence' },
        { type: 'gutter', gutterName: 'row-selector', multiple: true },
        { name: 'id', hidden: true },
        {
          type: 'string',
          name: 'palletId',
          label: true,
          header: i18next.t('field.lot_id'),
          width: 150
        },
        {
          type: 'string',
          name: 'cartonId',
          label: true,
          header: i18next.t('field.carton_id'),
          width: 150
        },
        {
          type: 'string',
          name: 'batchId',
          label: true,
          header: i18next.t('field.batch_id'),
          width: 150
        },
        {
          type: 'string',
          name: 'sku',
          label: true,
          header: i18next.t('field.sku'),
          width: 120
        },
        {
          type: 'object',
          name: 'product',
          label: true,
          header: i18next.t('field.product'),
          width: 250
        },
        {
          type: 'string',
          name: 'packingType',
          label: true,
          header: i18next.t('field.packing_type'),
          width: 120
        },
        {
          type: 'integer',
          name: 'packingSize',
          label: true,
          header: i18next.t('field.packing_size'),
          width: 100
        },
        {
          type: 'float',
          name: 'qty',
          label: true,
          header: i18next.t('field.qty'),
          width: 100
        },
        {
          type: 'string',
          name: 'status',
          label: true,
          header: i18next.t('field.status'),
          width: 120
        }
      ]
    }

    if (this.enableCartonLabel) {
      this._focusOnCartonInput()
    } else {
      this._focusOnLotInput()
    }
  }

  async _undoUnloading() {
    try {
      if (this.dataGrist.selected.some(s => s.inventoryItems?.length > 0)) {
        const result = await CustomAlert({
          title: i18next.t('title.are_you_sure'),
          text: i18next.t('text.all_related_serial_number_will_be_deleted'),
          confirmButton: { text: i18next.t('button.confirm') },
          cancelButton: { text: i18next.t('button.cancel') }
        })

        if (!result.value) return
      }
      if (!this._isExecuting) {
        this._isExecuting = true
        let selectedInventoryIds = []
        selectedInventoryIds = this.dataGrist.selected.map(inventory => inventory.id)

        if (!selectedInventoryIds?.length) throw new Error(i18next.t('text.select_at_least_one_inventory_to_undo'))

        this._validateScanInventory()

        const response = await client.mutate({
          mutation: gql`
            mutation undoUnloading($orderType: String!, $orderNo: String!, $inventoryIds: [String]!) {
              undoUnloading(orderType: $orderType, orderNo: $orderNo, inventoryIds: $inventoryIds)
            }
          `,
          variables: { orderType: this.orderType, orderNo: this.orderNo, inventoryIds: selectedInventoryIds }
        })

        if (!response.errors) {
          this.dispatchEvent(new CustomEvent('undo-inventory'))
        }
      }
    } catch (e) {
      this._showToast(e)
    } finally {
      this._isExecuting = false
    }
  }

  _populateTargetedInventory(e) {
    if (e.keyCode !== 13) return
    e.preventDefault()
    try {
      let targetedUndoInventories = []

      if (this.enableCartonLabel) {
        targetedUndoInventories = this.unloadedInventories.filter(
          inventory => inventory.cartonId === this.cartonInput?.value
        )
      } else {
        targetedUndoInventories = this.unloadedInventories.filter(
          inventory => inventory.palletId === this.lotInput?.value
        )
      }

      if (!targetedUndoInventories?.length) {
        if (this.enableCartonLabel) {
          this.cartonInput.value = ''
        } else {
          this.lotInput.value = ''
        }
        this._showToast({ message: i18next.t('text.no_matching_unloaded_inventory_found') })
      } else {
        this.data = {
          records: targetedUndoInventories.map(itm => {
            return { ...itm, sku: itm.product.sku }
          })
        }
        if (targetedUndoInventories?.length == 1) {
          this._selectedRecords = targetedUndoInventories
          this.data.records[0].__selected__ = true
        }
      }
    } catch (e) {
      this._showToast(e)
    }
  }

  _focusOnLotInput() {
    setTimeout(() => this.lotInput.focus(), 100)
  }

  _focusOnCartonInput() {
    setTimeout(() => this.cartonInput.focus(), 100)
  }

  _validateScanInventory() {
    if (this.enableCartonLabel) {
      if (!this.cartonInput?.value) {
        this._focusOnCartonInput()
        throw new Error(i18next.t('text.carton_id_is_empty'))
      }
    } else {
      if (!this.lotInput?.value) {
        this._focusOnLotInput()
        throw new Error(i18next.t('text.lot_id_is_empty'))
      }
    }
  }

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

window.customElements.define('undo-unload-popup', UndoUnloadPopup)
