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

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

import { MultiColumnFormStyles } 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'

export class PrintLocationLabel extends localize(i18next)(LitElement) {
  static get properties() {
    return {
      selectedLocations: Array,
      _fullLocationFormat: Boolean,
      _labelIndicator: String,
      _config: Object,
      _data: Array
    }
  }

  constructor() {
    super()
    this._fullLocationFormat = true
  }

  static get styles() {
    return [
      MultiColumnFormStyles,
      ScrollbarStyles,
      css`
        :host {
          padding: 0 15px;
          display: flex;
          flex-direction: column;
          overflow-x: overlay;
          background-color: var(--main-section-background-color);
        }
        h2 {
          margin: var(--subtitle-margin);
          padding: var(--subtitle-padding);
          font: var(--subtitle-font);
          color: var(--subtitle-text-color);
          border-bottom: var(--subtitle-border-bottom);
        }
        .grist {
          display: flex;
          flex-direction: column;
          flex: 1;
          overflow-y: auto;
        }
        data-grist {
          overflow-y: hidden;
          flex: 1;
        }
        .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);
        }
        .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);
        }
      `
    ]
  }

  render() {
    return html`
      <div>
        <h2>${i18next.t('title.location_label_format')}</h2>
        <form class="multi-column-form">
          <fieldset>
            <label>${i18next.t('label.label_format')}</label>
            <select
              name="labelFormat"
              @change="${e => {
                this._fullLocationFormat = e.currentTarget.value === 'full_format' ? true : false
                if (this._labelIndicator.value != '') this.dataGrist.fetch()
              }}"
            >
              <option value="full_format">A-01-01-01 (${i18next.t('text.full_format')})</option>
              <option value="partial_format">A-01-01 (${i18next.t('text.partial_format')})</option>
            </select>

            <label>${i18next.t('label.label_indicator')}</label>
            <select
              name="labelIndicator"
              @change="${e => {
                let indicator = e.currentTarget.value
                if (indicator !== '') this.dataGrist.fetch()
              }}"
            >
              <option value="">-- ${i18next.t('text.please_select_label_indicator')} --</option>
              <option value="zone">${i18next.t('label.zone')}</option>
              <option value="row">${i18next.t('label.row')}</option>
              <option value="column">${i18next.t('label.column')}</option>
              <option value="shelf" ?hidden=${!this._fullLocationFormat}>${i18next.t('label.shelf')}</option>
            </select>
          </fieldset>
        </form>
      </div>

      <div class="grist">
        <h2>${i18next.t('title.print_preview')}</h2>
        <data-grist
          .mode=${isMobileDevice() ? 'LIST' : 'GRID'}
          .config=${this._config}
          .fetchHandler="${this.fetchHandler.bind(this)}"
        ></data-grist>
      </div>

      <div class="button-container">
        <mwc-button
          raised
          @click="${this._printLocations.bind(this)}"
          label="${i18next.t('button.print')}"
        ></mwc-button>
      </div>
    `
  }

  async firstUpdated() {
    this._config = {
      pagination: { pages: [0] },
      columns: [
        {
          type: 'string',
          name: 'name',
          header: i18next.t('field.name'),
          width: 250
        },
        {
          type: 'string',
          name: 'originalName',
          header: i18next.t('field.original_name'),
          width: 250
        },
        {
          type: 'string',
          name: 'indicator',
          header: i18next.t('field.indicator'),
          width: 250
        }
      ]
    }
  }

  get _labelIndicator() {
    return this.shadowRoot.querySelector('select[name=labelIndicator]')
  }

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

  async fetchHandler({ page, limit, sorters = [{ name: 'name' }] }) {
    if (this._labelIndicator.value == '') return
    const fetcherDetail = { page, limit, sorters }
    const indicator = this._labelIndicator.value || ''

    let filters = [
      {
        name: 'warehouse_id',
        operator: 'eq',
        value: this.warehouseId
      }
    ]

    let locations = [],
      totalLocations = 0

    if (this.selectedLocations && this.selectedLocations.length) {
      filters.push({
        name: 'name',
        operator: 'in',
        value: this.selectedLocations.map(location => location.name)
      })
      const { records, total } = await this._fetchLocations(filters, fetcherDetail)
      locations = records
      totalLocations = total
    } else {
      if (this._fullLocationFormat) {
        filters.push({
          name: 'type',
          operator: 'noteq',
          value: 'BUFFER'
        })
        const { records, total } = await this._fetchLocations(filters, fetcherDetail)
        locations = records
        totalLocations = total
      } else {
        // if partial format:
        // prevent from printing same location label.  eg: A-01-01-01, A-01-01-02 > will print A-01-01 twice{
        if (indicator == 'shelf') {
          this._showToast({
            level: 'error',
            message: i18next.t('text.shelf_is_not_allowed_as_an_indicator_for_partial_format')
          })
          return
        } else {
          const { records, total } = await this._fetchLocationsByGroup(filters, fetcherDetail)
          locations = records
          totalLocations = total
        }
      }
    }

    return {
      total: totalLocations,
      records: locations.map(location => {
        return {
          ...location,
          indicator: location[indicator],
          originalName: location.name,
          name:
            location.type === 'BUFFER'
              ? ''
              : this._fullLocationFormat // check if full location format is true
              ? `${location.zone}-${location.row}-${location.column}-${location.shelf}`
              : `${location.zone}-${location.row}-${location.column}`
        }
      })
    }
  }

  async _fetchLocations(filters, fetcherDetail) {
    try {
      const response = await client.query({
        query: gql`
          query locations($filters: [Filter!], $pagination: Pagination, $sortings: [Sorting!]) {
            locations(filters: $filters, pagination: $pagination, sortings: $sortings) {
              items {
                name
                zone
                row
                column
                shelf
                type
              }
              total
            }
          }
        `,
        variables: {
          filters,
          paginations: { page: fetcherDetail.page, limit: fetcherDetail.limit },
          sortings: fetcherDetail.sorters
        }
      })

      if (!response.errors) {
        return {
          records: response.data.locations.items || [],
          total: response.data.locations.total || 0
        }
      }
    } catch (e) {
      this._showToast({
        level: 'error',
        message: e
      })
    }
  }

  async _fetchLocationsByGroup(filters, fetcherDetail) {
    try {
      const response = await client.query({
        query: gql`
          query locationsByGroup($filters: [Filter!], $pagination: Pagination, $sortings: [Sorting!]) {
            locationsByGroup(filters: $filters, pagination: $pagination, sortings: $sortings) {
              items {
                name
                zone
                row
                column
                type
              }
              total
            }
          }
        `,
        variables: {
          filters,
          paginations: { page: fetcherDetail.page, limit: fetcherDetail.limit },
          sortings: fetcherDetail.sorters
        }
      })

      if (!response.errors) {
        return {
          records: response.data.locationsByGroup.items || [],
          total: response.data.locationsByGroup.total || 0
        }
      }
    } catch (e) {
      this._showToast({
        level: 'error',
        message: e
      })
    }
  }

  _printLocations() {
    const records = this.dataGrist.data && this.dataGrist.data.records
    if (records && records.length) {
      this.dispatchEvent(new CustomEvent(i18next.t('text.printing'), { detail: records }))
      history.back()
    } else {
      this._showToast({
        level: 'error',
        message: i18next.t('text.there_is_no_item_to_print')
      })
    }
  }

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

window.customElements.define('print-location-label', PrintLocationLabel)
