import '@material/mwc-button/mwc-button'
import '@things-factory/grist-ui'

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

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 InventoryHistoryByPallet extends localize(i18next)(LitElement) {
  static get styles() {
    return [
      ScrollbarStyles,
      css`
        :host {
          display: flex;
          flex-direction: column;
          overflow: hidden;
        }

        search-form {
          overflow: visible;
        }

        data-grist {
          overflow-y: hidden;
          flex: 1;
        }
      `
    ]
  }

  static get properties() {
    return {
      _searchFields: Array,
      config: Object,
      data: Object,
      palletId: String
    }
  }

  render() {
    return html`
      <data-grist
        .mode=${isMobileDevice() ? 'LIST' : 'GRID'}
        .config=${this.config}
        .fetchHandler="${this.fetchHandler.bind(this)}"
      ></data-grist>
    `
  }

  firstUpdated() {
    this.config = {
      list: {
        fields: [
          'palletId',
          'cartonId',
          'batchId',
          'productSku',
          'product',
          'location',
          'orderNo',
          'orderRefNo',
          'openingQty',
          'qty',
          'openingUomValue',
          'uomValue',
          'description',
          'batchIdRef'
        ]
      },
      rows: { appendable: false },
      pagination: { infinite: true },
      columns: [
        { type: 'gutter', gutterName: 'sequence' },
        {
          type: 'string',
          name: 'palletId',
          header: i18next.t('field.lot_id'),
          sortable: true,
          width: 200
        },
        {
          type: 'string',
          name: 'cartonId',
          header: i18next.t('field.carton_id'),
          sortable: true,
          width: 150
        },
        {
          type: 'string',
          name: 'productSku',
          header: i18next.t('field.sku'),
          sortable: true,
          width: 150
        },
        {
          type: 'object',
          name: 'product',
          header: i18next.t('field.product'),
          sortable: true,
          width: 500
        },
        {
          type: 'string',
          name: 'productBrand',
          header: i18next.t('field.brand'),
          sortable: true,
          width: 150
        },
        {
          type: 'string',
          name: 'batchId',
          header: i18next.t('field.batch_id'),
          sortable: true,
          width: 200
        },
        {
          type: 'object',
          name: 'location',
          header: i18next.t('field.location'),
          sortable: true,
          width: 200
        },
        {
          type: 'number',
          name: 'qty',
          header: i18next.t('field.qty'),
          sortable: true,
          width: 80
        },
        {
          type: 'number',
          name: 'openingQty',
          header: i18next.t('field.opening_qty'),
          sortable: true,
          width: 80
        },
        {
          type: 'string',
          name: 'uomValue',
          header: i18next.t('field.uom_value'),
          sortable: true,
          width: 80
        },
        {
          type: 'string',
          name: 'openingUomValue',
          header: i18next.t('field.opening_uom_value'),
          sortable: true,
          width: 80
        },
        {
          type: 'string',
          name: 'orderNo',
          header: i18next.t('field.order_no'),
          sortable: true,
          width: 150
        },
        {
          type: 'string',
          name: 'orderRefNo',
          header: i18next.t('field.ref_no'),
          sortable: true,
          width: 150
        },
        {
          type: 'string',
          name: 'status',
          header: i18next.t('field.status'),
          sortable: true,
          width: 150
        },
        {
          type: 'string',
          name: 'transactionType',
          header: i18next.t('field.transaction_type'),
          sortable: true,
          width: 150
        },
        {
          type: 'string',
          name: 'batchIdRef',
          header: i18next.t('field.batch_no_ref'),
          sortable: true,
          width: 200
        },
        {
          type: 'datetime',
          name: 'updatedAt',
          header: i18next.t('field.date'),
          sortable: true,
          width: 170
        },
        {
          type: 'object',
          name: 'updater',
          header: i18next.t('field.user'),
          sortable: true,
          width: 170
        }
      ]
    }
  }

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

  async fetchHandler({ page, limit, sorters = [] }) {
    try {
      if (!this.palletId) return
      const response = await client.query({
        query: gql`
          query inventoryHistories($filters: [Filter!], $pagination: Pagination, $sortings: [Sorting!]) {
            inventoryHistories(filters: $filters, pagination: $pagination, sortings: $sortings) {
              items {
                palletId
                cartonId
                batchId
                batchIdRef
                qty
                openingQty
                uomValue
                openingUomValue
                orderRefNo
                orderNo
                uomValue
                uom
                description
                status
                transactionType
                product {
                  sku
                  brand
                  name
                  description
                }
                warehouse {
                  name
                  description
                }
                zone
                location {
                  name
                  description
                }
                updatedAt
                updater {
                  name
                  description
                }
              }
              total
            }
          }
        `,
        variables: {
          filters: [{ name: 'palletId', operator: 'eq', value: this.palletId }],
          pagination: { page, limit },
          sortings: sorters
        }
      })

      if (!response.errors) {
        return {
          total: response.data.inventoryHistories.total || 0,
          records:
            response.data.inventoryHistories.items.map(itm => {
              return {
                ...itm,
                productSku: itm.product.sku,
                productBrand: itm.product.brand,
                uomValue: `${itm.uomValue} ${itm.uom}`,
                openingUomValue: `${itm.openingUomValue} ${itm.uom}`
              }
            }) || []
        }
      }
    } catch (e) {
      this._showToast(e)
    }
  }

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

window.customElements.define('inventory-history-by-pallet', InventoryHistoryByPallet)
