import '@things-factory/grist-ui'
import '@things-factory/barcode-ui'

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

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

class SerialNumberListPopup extends localize(i18next)(LitElement) {
  static get properties() {
    return {
      serialNumberConfig: Object,
      serialNumberGrist: Object,
      data: Object,
      orderType: String,
      orderId: String,
      _inventoryInfo: String,
      _currentSerialNumber: String,
      _selectedInventoryItemId: Object
    }
  }

  static get styles() {
    return [
      MultiColumnFormStyles,
      SingleColumnFormStyles,
      ScrollbarStyles,
      css`
        :host {
          display: flex;
          flex-direction: column;
          overflow: hidden;
          background-color: white;
        }

        .grist {
          display: flex;
          flex-direction: column;
          flex: 1;
          overflow-y: auto;
        }
        .grist-container {
          overflow-y: hidden;
          display: flex;
          flex: 1;
          padding: 10px;
        }
        data-grist {
          overflow-y: hidden;
          flex: 1;
        }
        h2 {
          padding: var(--subtitle-padding);
          font: var(--subtitle-font);
          color: var(--subtitle-text-color);
          border-bottom: var(--subtitle-border-bottom);
        }
        .grist h2 {
          font: var(--grist-title-font);
        }
        .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);
        }
      `
    ]
  }

  render() {
    return html`
      <form class="multi-column-form">
        <fieldset>
          <legend>${this.data.product.sku}</legend>
        </fieldset>
      </form>

      <form id="inventory-info-form" class="single-column-form">
        <fieldset>
          <label
            >${i18next.t('field.lot_id')} / ${i18next.t('field.carton_id')} / ${i18next.t('field.serial_number')}</label
          >
          <barcode-scanable-input
            name="inventoryInfo"
            custom-input
            @keypress="${e => {
              if (e.keyCode === 13) {
                e.preventDefault()
                this._inventoryInfo = this.inventoryInfoInput.value
                this.serialNumberGrist.fetch()
              }
            }}"
          ></barcode-scanable-input>
        </fieldset>
      </form>

      <div class="grist-container">
        <div class="grist">
          <data-grist
            id="serialNumberGrist"
            .mode=${isMobileDevice() ? 'LIST' : 'GRID'}
            .config=${this.serialNumberConfig}
            .fetchHandler=${this.fetchInventoryItems.bind(this)}
          ></data-grist>
        </div>
      </div>

      <form id="input-form" class="single-column-form">
        <input
          name="selectedSerialNumber"
          placeholder="-- Selected Serial Number --"
          disabled
          readonly
          class="mobile-full-width"
          value="${this._currentSerialNumber}"
        />
        <barcode-scanable-input name="serialNumber" class="mobile-full-width" custom-input></barcode-scanable-input>

        <mwc-button
          name="updateSerialNumber"
          class="mobile-full-width"
          @click=${async () => {
            await this.updateInventoryItemSerialNumber()
          }}
          raised
          label="${i18next.t('button.update')}"
        ></mwc-button>
      </form>

      <div class="button-container">
        <mwc-button
          danger
          @click=${() => {
            this.dispatchEvent(new CustomEvent('close-serial-number-list', {}))
            history.back()
          }}
          raised
          label="${i18next.t('button.back')}"
        ></mwc-button>
      </div>
    `
  }

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

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

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

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

  firstUpdated() {
    this.serialNumberConfig = {
      pagination: { pages: [10, 20, 50, 100] },
      rows: {
        appendable: false,
        handlers: {
          click: async (columns, data, column, record, rowIndex) => {
            try {
              this.serialNumberGrist.showSpinner()
              this._currentSerialNumber = record.serialNumber
              this._selectedInventoryItemId = record.id
            } catch (ex) {
              console.log(ex)
            } finally {
              this.serialNumberGrist.hideSpinner()
            }
          }
        }
      },
      list: {
        fields: ['serialNumber', 'palletId', 'cartonId']
      },
      columns: [
        { type: 'gutter', gutterName: 'sequence', forList: true },
        { type: 'object', name: 'inventory', hidden: true },
        {
          type: 'gutter',
          gutterName: 'button',
          icon: 'close',
          forList: true,
          handlers: {
            click: (columns, data, column, record, rowIndex) => {
              this.undoSerialNumberUnload(record.id)
            }
          }
        },
        {
          type: 'string',
          name: 'serialNumber',
          header: i18next.t('field.serial_number'),
          label: true,
          width: 150
        },
        {
          type: 'string',
          name: 'palletId',
          header: i18next.t('field.lot_id'),
          label: true,
          width: 180
        },
        {
          type: 'string',
          name: 'cartonId',
          header: i18next.t('field.carton_id'),
          label: true,
          width: 180
        }
      ]
    }
  }

  async fetchInventoryItems({ page, limit, sorters = [{ name: 'serialNumber' }] }) {
    let filters = [
      { name: 'orderType', operator: 'eq', value: this.orderType },
      { name: 'orderId', operator: 'eq', value: this.orderId },
      { name: 'productId', operator: 'eq', value: this.data.product.id }
    ]

    if (this._inventoryInfo) filters.push({ name: 'inventory_info', operator: 'i_like', value: this._inventoryInfo })

    const pagination = { page, limit }
    const sortings = sorters

    const response = await client.query({
      query: gql`
        query inventoryItemsByInventory($filters: [Filter!]!, $pagination: Pagination, $sortings: [Sorting!]!) {
          inventoryItemsByInventory(filters: $filters, pagination: $pagination, sortings: $sortings) {
            items {
              id
              name
              status
              serialNumber
              inventory {
                id
                name
                palletId
                cartonId
              }
              product {
                id
                name
                sku
              }
            }
            total
          }
        }
      `,
      variables: { filters, pagination, sortings }
    })

    if (!response.errors) {
      return {
        total: response.data.inventoryItemsByInventory.total || 0,
        records:
          response.data.inventoryItemsByInventory.items.map(item => {
            return {
              ...item,
              palletId: item.inventory.palletId,
              cartonId: item.inventory.cartonId
            }
          }) || []
      }
    }
  }

  async undoSerialNumberUnload(id) {
    try {
      const response = await client.mutate({
        mutation: gql`
          mutation undoSerialNumberUnload($worksheetDetailName: String!, $inventoryItemId: String!) {
            undoSerialNumberUnload(worksheetDetailName: $worksheetDetailName, inventoryItemId: $inventoryItemId)
          }
        `,
        variables: {
          worksheetDetailName: this.data.name,
          inventoryItemId: id
        }
      })

      if (!response.errors) {
        this.serialNumberGrist.fetch()
      }
    } catch (e) {
      this._showToast(e)
    }
  }

  async updateInventoryItemSerialNumber() {
    try {
      this.validate()

      const response = await client.mutate({
        mutation: gql`
          mutation updateInventoryItemSerialNumber($id: String!, $serialNumber: String!) {
            updateInventoryItemSerialNumber(id: $id, serialNumber: $serialNumber)
          }
        `,
        variables: {
          id: this._selectedInventoryItemId,
          serialNumber: this.serialInput.value
        }
      })

      if (!response.errors) {
        this.serialInput.value = ''
        this.serialNumberGrist.fetch()
      }
    } catch (e) {
      this._showToast(e)
    }
  }

  validate() {
    // validate for previous picking execution (multiple picking scanning)
    if (this.selectedSerialInput.value == '') throw new Error(i18next.t('text.no_serial_number_selected'))

    if (this.serialInput.value == '') throw new Error(i18next.t('text.please_key_in_new_serial_number'))
  }

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

window.customElements.define('serial-number-list-popup', SerialNumberListPopup)
