import '@things-factory/grist-ui'

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 { store } from '@things-factory/shell'
import { isMobileDevice } from '@things-factory/utils'

class PickingSameCartonPopup extends connect(store)(localize(i18next)(LitElement)) {
  static get properties() {
    return {
      config: Object,
      data: Object,
      pickingInventories: Array
    }
  }

  constructor() {
    super()
  }

  static get styles() {
    return [
      SingleColumnFormStyles,
      css`
        .button-container {
          padding: 10px 0 12px 0;
          text-align: center;
        }
        .button-container mwc-button {
          margin: 0 5px;
        }
        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;
        }
        .header {
          padding: 10px;
          font-weight: bold;
          font-size: 14px;
          color: var(--secondary-color);
          border-bottom: 1px solid var(--secondary-color);
          margin-bottom: 10px;
        }
      `
    ]
  }

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

  updated(changeProps) {
    if (changeProps.has('pickingInventories')) {
      if (this.pickingInventories && this.pickingInventories.length) {
        this.data = {
          records: this.pickingInventories.map(inv => ({
            ...inv,
            locationName: inv.location?.name || ''
          }))
        }
      }
    }
  }

  render() {
    return html`
      <div class="header">
        ${i18next.t('text.please_select_an_inventory')}
      </div>

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

      <div class="button-container">
        <mwc-button
          raised
          @click="${this._selectPickingInventory.bind(this)}"
          label="${i18next.t('button.select')}"
        ></mwc-button>
        <mwc-button
          @click="${() => {
            this.dispatchEvent(new CustomEvent('selection', { detail: null }))
            history.back()
          }}"
          label="${i18next.t('button.cancel')}"
        ></mwc-button>
      </div>
    `
  }

  firstUpdated() {
    this.config = {
      pagination: { infinite: true },
      rows: { selectable: { multiple: false }, appendable: false },
      list: {
        fields: [
          'locationName',
          'palletId',
          'batchId',
          'batchIdRef',
          'expirationDate',
          'qty',
          'releaseQty',
          'packingType'
        ]
      },
      columns: [
        { type: 'gutter', gutterName: 'sequence' },
        { type: 'gutter', gutterName: 'row-selector', multiple: false, header: { renderer: () => '' } },
        { name: 'name', hidden: true },
        {
          type: 'string',
          name: 'locationName',
          label: true,
          header: i18next.t('field.location'),
          width: 120
        },
        {
          type: 'string',
          name: 'palletId',
          label: true,
          header: i18next.t('field.pallet_id'),
          width: 120
        },
        {
          type: 'string',
          name: 'batchId',
          label: true,
          header: i18next.t('field.batch_no'),
          width: 100
        },
        {
          type: 'string',
          name: 'batchIdRef',
          label: true,
          header: i18next.t('field.lot_id'),
          width: 100
        },
        {
          type: 'date',
          name: 'expirationDate',
          label: true,
          header: i18next.t('field.expiration'),
          width: 100
        },
        {
          type: 'float',
          name: 'qty',
          label: true,
          header: i18next.t('field.available_qty'),
          width: 80
        },
        {
          type: 'float',
          name: 'releaseQty',
          label: true,
          header: i18next.t('field.release_qty'),
          width: 80
        },
        {
          type: 'string',
          name: 'packingType',
          label: true,
          header: i18next.t('field.packing_type'),
          width: 100
        }
      ]
    }
  }

  async _selectPickingInventory() {
    try {
      const selectedInventory = this.dataGrist.selected[0]
      if (!selectedInventory) throw new Error(i18next.t('text.please_select_inventory'))

      this.dispatchEvent(new CustomEvent('selection', { detail: selectedInventory }))
      history.back()
    } catch (e) {
      this._showToast(e)
    }
  }

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

window.customElements.define('picking-same-carton-popup', PickingSameCartonPopup)
