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

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

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

class ExistingManifestList extends 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 {
      _searchFields: Array,
      config: Object,
      data: Object,
      _shippingProviderList: Array
    }
  }

  get context() {
    return {
      title: i18next.t('title.existing_manifest'),
      actions: [
        {
          title: i18next.t('button.confirm'),
          action: this._returnExisting.bind(this),
          ...CommonButtonStyles.submit
        },
        {
          title: i18next.t('button.back'),
          action: () => navigate(`create_loading_manifest`),
          ...CommonButtonStyles.back
        }
      ]
    }
  }

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

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

  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 pageUpdated(changes, lifecycle) {
    if (this.active) {
      this.dataGrist.fetch()
    }
  }

  constructor() {
    super()
    this._shippingProviderList = []
  }

  async pageInitialized() {
    this._searchFields = [
      {
        label: i18next.t('field.manifest_no'),
        name: 'name',
        type: 'text',
        props: { searchOper: 'i_like' }
      },
      {
        label: i18next.t('field.transporter'),
        name: 'shippingProvider',
        type: 'select',
        options: [
          { value: '' },
          ...this._shippingProviderList.map(sp => {
            return {
              name: sp,
              value: sp
            }
          })
        ],
        props: { searchOper: 'i_like' }
      }
    ]

    this.config = {
      list: {
        fields: ['name', 'shippingProvider', 'status', 'dispatchedAt', 'createdAt']
      },
      rows: { appendable: false, selectable: { multiple: false } },
      columns: [
        { type: 'gutter', gutterName: 'sequence' },
        { type: 'gutter', gutterName: 'row-selector', multiple: true },
        {
          type: 'string',
          name: 'name',
          header: i18next.t('field.manifest_no'),
          label: true,
          sortable: true,
          width: 180
        },
        {
          type: 'int',
          name: 'totalTrackingNo',
          header: i18next.t('field.total_tracking_no'),
          label: true,
          width: 150
        },
        {
          type: 'string',
          name: 'shippingProvider',
          header: i18next.t('field.transporter'),
          label: true,
          sortable: true,
          width: 150
        },
        {
          type: 'string',
          name: 'status',
          header: i18next.t('field.status'),
          label: true,
          sortable: true,
          width: 150
        },
        {
          type: 'datetime',
          name: 'createdAt',
          header: i18next.t('field.created_at'),
          label: true,
          sortable: true,
          width: 160
        },
        {
          type: 'object',
          name: 'creator',
          header: i18next.t('field.created_by'),
          label: true,
          sortable: true,
          width: 200
        }
      ]
    }
  }

  async fetchHandler({ page, limit, sorters = [{ name: 'createdAt', desc: true }] }) {
    const filtersWithAdditional = [...this.searchForm.queryFilters]
    const response = await client.query({
      query: gql`
        query manifests($filters: [Filter!], $pagination: Pagination, $sortings: [Sorting!], $isSelectOpen: Boolean) {
          manifests(filters: $filters, pagination: $pagination, sortings: $sortings, isSelectOpen: $isSelectOpen) {
            items {
              id
              name
              shippingProvider
              totalTrackingNo
              status
              createdAt
              creator {
                id
                name
                description
              }
            }
            total
          }
        }
      `,
      variables: { filters: filtersWithAdditional, pagination: { page, limit }, sortings: sorters, isSelectOpen: true }
    })

    if (!response.errors) {
      let shippingProviders = response.data.manifests.items.map(itm =>
        itm.shippingProvider == 'EMS' ? 'EFMX' : itm.shippingProvider
      )
      shippingProviders = [...new Set(shippingProviders)]

      if (this._shippingProviderList.length < shippingProviders.length) {
        this._shippingProviderList = shippingProviders
        this._searchFields.filter(x => x.name == 'shippingProvider')[0].options = [
          { value: '' },
          ...this._shippingProviderList.map(sp => {
            return {
              name: sp,
              value: sp == 'EFMX' ? 'EMS' : sp
            }
          })
        ]
        this._searchFields = [...this._searchFields]
      }
      return {
        total: response.data.manifests.total || 0,
        records:
          response.data.manifests.items.map(itm => {
            if (itm.shippingProvider == 'EMS') {
              return { ...itm, shippingProvider: 'EFMX' }
            }
            return itm
          }) || []
      }
    }
  }

  get _columns() {
    return this.config.columns
  }

  _returnExisting() {
    const selected = this.dataGrist.selected
    if (selected.length < 1) {
      this._showToast({ message: i18next.t('text.please_select_a_manifest_to_proceed') })
      return
    }
    let selectedObject = selected.reduce((acc, curr) => Object.assign(acc, curr), {})
    const encodedShippingProvider = encodeURIComponent(selectedObject.shippingProvider)

    const url = `create_loading_manifest?name=${selectedObject.name}&shippingProvider=${encodedShippingProvider}&id=${selectedObject.id}`
    navigate(url)
  }

  _showToast({ type, message, duration }) {
    document.dispatchEvent(
      new CustomEvent('notify', {
        detail: {
          type,
          message,
          option: { timer: duration ? duration : 1500 }
        }
      })
    )
  }
}

customElements.define('existing-manifest-list', ExistingManifestList)
