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

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

import { getPartnerCodeByName } from '@things-factory/code-base'
import { i18next, localize } from '@things-factory/i18n-base'
import { client, PageView, store } from '@things-factory/shell'
import { ScrollbarStyles } from '@things-factory/styles'
import { isMobileDevice } from '@things-factory/utils'

class InventoryComparison extends connect(store)(localize(i18next)(PageView)) {
  static get styles() {
    return [
      ScrollbarStyles,
      css`
        :host {
          display: flex;
          flex-direction: column;
          overflow: hidden;
        }

        search-form {
          overflow: visible;
        }

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

  static get properties() {
    return {
      _config: Object,
      _searchFields: Object,
      _partners: Object,
      _gristData: Object,
      _nonTally: Boolean,
      data: Object
    }
  }

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

  get searchForm() {
    return this.shadowRoot.querySelector('search-form')
  }

  get _bizplaceSelector() {
    return this.searchForm.shadowRoot.querySelector('select[name=bizplace]')
  }

  get _toDateInput() {
    return this.searchForm.shadowRoot.querySelector('input[name=toDate]')
  }

  get searchFields() {
    return [
      {
        label: i18next.t('field.company'),
        name: 'bizplace',
        type: 'select',
        options: [
          { value: '' },
          ...this._partners
            .map(partner => {
              return {
                name: `${partner.name} ${partner.description ? `(${partner.description})` : ''}`,
                value: partner.id
              }
            })
            .sort(this._compareValues('name', 'asc'))
        ],
        props: { searchOper: 'eq' }
      },
      {
        label: i18next.t('field.date'),
        name: 'toDate',
        type: 'date',
        props: {
          searchOper: 'eq',
          min: (() => {
            let date = new Date()
            date.setMonth(date.getMonth() - 1)
            return date.toISOString().split('T')[0]
          })(),
          max: new Date().toISOString().split('T')[0]
        },
        value: new Date().toISOString().split('T')[0]
      },
      {
        label: i18next.t('field.product_info'),
        name: 'product',
        type: 'string',
        props: { searchOper: 'in' }
      },
      {
        label: i18next.t('field.non_tally'),
        name: 'nonTally',
        type: 'checkbox',
        value: this._nonTally,
        props: { searchOper: 'eq' }
      }
    ]
  }

  get context() {
    return {
      title: i18next.t('title.inventory_comparison_list')
    }
  }

  async pageInitialized() {
    this._partners = [...(await this._fetchPartners())]
    this._searchFields = this.searchFields
    this._gristData = { total: 0, records: [] }
    this._config = {
      list: {
        fields: ['productSku', 'productName', 'batchId', 'packingType', 'closingQty', 'remainQty']
      },
      pagination: { limit: 50, pages: [50, 100, 200, 500, 1000] },
      rows: {
        selectable: false,
        insertable: false,
        appendable: false
      },
      columns: [
        { type: 'gutter', gutterName: 'sequence' },
        {
          type: 'string',
          name: 'productSku',
          header: i18next.t('field.sku'),
          width: 150
        },
        {
          type: 'string',
          name: 'productName',
          header: i18next.t('field.product'),
          width: 400
        },
        {
          type: 'string',
          name: 'batchId',
          header: i18next.t('field.batch_id'),
          width: 150
        },
        {
          type: 'string',
          name: 'packingType',
          header: i18next.t('field.packing_type'),
          width: 150
        },
        {
          type: 'number',
          name: 'closingQty',
          header: i18next.t('field.summary_report_quantity'),
          width: 200
        },
        {
          type: 'number',
          name: 'remainQty',
          header: i18next.t('field.onhand_inventory_quantity'),
          width: 200
        }
      ]
    }
  }

  pageUpdated(changes, lifecycle) {
    if (this.active) {
      this.dataGrist.fetch()
    }
  }

  async fetchHandler({ page, limit, sorters = [] }) {
    try {
      let filter = this.searchForm.queryFilters.map(filter => {
        switch (filter.name) {
          case 'toDate':
            let toDt = new Date(filter.value)
            toDt.setHours(23, 59, 59)
            filter.value = toDt.toISOString()
            break
          default:
            break
        }
        return filter
      })

      const response = await client.query({
        query: gql`
          query inventoryComparisonList($filters: [Filter], $pagination: Pagination, $sortings: [Sorting]) {
            inventoryComparisonList(filters: $filters, pagination: $pagination, sortings: $sortings) {
              items {
                productSku
                productName
                packingType
                closingQty
                remainQty
                batchId
              }
              total
            }
          }
        `,
        variables: { filters: filter, pagination: { page, limit }, sortings: sorters }
      })

      if (!response.errors) {
        return {
          total: response.data?.inventoryComparisonList?.total || 0,
          records: response.data?.inventoryComparisonList?.items || []
        }
      }
    } catch (error) {
      throw error
    }
  }

  render() {
    return html`
      <search-form id="search-form" .fields=${this._searchFields} @submit=${e => this.dataGrist.fetch()}></search-form>

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

  async _companyChanged(e) {
    this._productType = !this._bizplaceSelector.value
      ? []
      : await getPartnerCodeByName(
          'PRODUCT_TYPES',
          this._partners.find(p => p.id == this._bizplaceSelector.value)?.company?.domainId || ''
        )

    this._searchFields = [...this.searchFields]
  }

  _compareValues(key, order = 'asc') {
    return function innerSort(a, b) {
      if (!a.hasOwnProperty(key) || !b.hasOwnProperty(key)) {
        return 0
      }

      const varA = typeof a[key] === 'string' ? a[key].toUpperCase() : a[key]
      const varB = typeof b[key] === 'string' ? b[key].toUpperCase() : b[key]

      let comparison = 0
      if (varA > varB) {
        comparison = 1
      } else if (varA < varB) {
        comparison = -1
      }
      return order === 'desc' ? comparison * -1 : comparison
    }
  }

  async _fetchPartners() {
    const filters = []
    const response = await client.query({
      query: gql`
        query partnersBizplaces($filters: [Filter!]) {
          partnersBizplaces(filters: $filters) {
            items {
              id
              name
              description
              company {
                id
                domainId
              }
            }
          }
        }
      `,
      variables: { filters }
    })

    if (!response.errors) {
      return response.data.partnersBizplaces.items
    }
  }
}

window.customElements.define('inventory-comparison', InventoryComparison)
