import { i18next, localize } from '@things-factory/i18n-base'
import { client,gqlContext } from '@things-factory/shell'
import { isMobileDevice } from '@things-factory/utils'
import gql from 'graphql-tag'
import { css, html, LitElement } from 'lit-element'
import '@material/mwc-button'

class SelectOperatorPopup extends localize(i18next)(LitElement) {
  static get properties() {
    return {
      searchField: Array,
      config: Object,
      bizplace: Object,
      selectSorter: Boolean
    }
  }

  static get styles() {
    return [
      css`
        :host {
          display: flex;
          flex-direction: column;
          overflow: hidden;
          background-color: var(--main-section-background-color);
        }
        data-grist {
          overflow-y: auto;
          flex: 1;
        }
        .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);
        }
      `
    ]
  }

  render() {
    return html`
      <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>

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

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

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

  async firstUpdated() {

    const roles = [...(await this.fetchRoles())]

    this.searchFields = [
      {
        name: 'name',
        label: i18next.t('field.name'),
        type: 'text',
        props: { searchOper: 'i_like' }
      },
      {
        name: 'email',
        label: i18next.t('field.email'),
        type: 'text',
        props: { searchOper: 'i_like' }
      },
      {
        label: i18next.t('field.role'),
        name: 'roles',
        type: 'select',
        options: [
          { value: '' },
          ...roles
            .map(roles => {
              return {
                name: `${roles.name}`,
                value: roles.name
              }
            })
            .sort(this._compareValues('name', 'asc'))
        ],
        props: { searchOper: 'eq' }
      }
    ]

    this.config = {
      row: { selectable: { multiple: false } },
      pagination: { infinite: true },
      columns: [
        { type: 'gutter', gutterName: 'sequence' },
        {
          type: 'gutter',
          gutterName: 'row-selector',
          multiple: false
        },
        {
          type: 'string',
          name: 'name',
          header: i18next.t('field.name'),
          sortable: true,
          width: 150
        },
        {
          type: 'string',
          name: 'roles',
          header: i18next.t('field.role'),
          width: 150
        },
        {
          type: 'string',
          name: 'email',
          header: i18next.t('field.email'),
          sortable: true,
          width: 200
        },
        {
          type: 'string',
          name: 'pending',
          header: i18next.t('label.pending'),
          sortable: true,
          width: 100,
          hidden: this.selectSorter
        },
        {
          type: 'string',
          name: 'picking',
          header: i18next.t('label.picking'),
          sortable: true,
          width: 100,
          hidden: this.selectSorter
        }
      ]
    }
  }

  async fetchHandler({ page, limit, sorters }) {
    const filters = await this.searchForm.getQueryFilters()
    const pagination = { }
    const sortings = sorters || []

    const response = await client.query({
      query: gql`
        query pickingAssignmentStatusByUsers($filters: [Filter], $pagination: Pagination, $sortings: [Sorting]) {
          pickingAssignmentStatusByUsers(filters: $filters, pagination: $pagination, sortings: $sortings) {
            user {
              id
              name
              email
              description
            }
            pending
            picking
          }
        }
      `,
      variables: { filters, pagination, sortings}
    })

    if (!response.errors) {
      return {
        total: response.data.pickingAssignmentStatusByUsers.length || 0,
        records: response.data.pickingAssignmentStatusByUsers.map(item => {
          return {
            ...item,
            name: item.user.name,
            email: item.user.email,
            roles: item.user.description
          }
        })
      }
    }
  }

  async fetchRoles() {
    const response = await client.query({
      query: gql`
        query roles($sortings: [Sorting!]) {
          roles(sortings: $sortings) {
            items {
              id
              name
              description
              privileges {
                id
                name
              }
            }
            total
          }
        }
      `,
      variables: { sortings: [{ name: 'name' }] },
      context: gqlContext()
    })

    return response.data.roles.items
  }

  _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
    }
  }

  selectOperator() {
    const selectedOperator = this.dataGrist.selected[0]
    if (selectedOperator?.name) {
      this.dispatchEvent(new CustomEvent('updateOperator', { detail: selectedOperator.user }))
      history.back()
    } else {
      this.showToast(i18next.t('text.target_is_not_selected'))
    }
  }

  showToast(message) {
    document.dispatchEvent(new CustomEvent('notify', { detail: { message, option: { timer: 1000 } } }))
  }
}

window.customElements.define('select-operator-popup', SelectOperatorPopup)
