import '@material/mwc-button'
import '@things-factory/form-ui'
import '@things-factory/grist-ui'

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

import { i18next } from '@things-factory/i18n-base'
import { client } from '@things-factory/shell'
import { isMobileDevice } from '@things-factory/utils'

class PartnerSelector extends LitElement {
  static get styles() {
    return [
      css`
        :host {
          display: flex;
          flex-direction: column;
          overflow: hidden;
          background-color: white;
        }
        data-grist {
          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);
        }
      `
    ]
  }

  static get properties() {
    return {
      searchFields: Array,
      config: Object,
      data: Object
    }
  }

  render() {
    return html`
      <search-form id="search-form" .fields=${this.searchFields} @submit=${() => 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 raised @click="${this.select.bind(this)}">${i18next.t('button.select')}</mwc-button>
      </div>
    `
  }

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

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

  firstUpdated() {
    this.searchFields = [
      {
        name: 'name',
        label: i18next.t('field.name'),
        type: 'text',
        props: { searchOper: 'i_like' }
      }
    ]

    this.config = {
      list: { fields: ['name'] },
      rows: { selectable: { multiple: true }, appendable: false },
      columns: [
        { type: 'gutter', gutterName: 'sequence' },
        { type: 'gutter', gutterName: 'row-selector', multiple: false },
        {
          type: 'string',
          name: 'name',
          header: i18next.t('field.name'),
          sortable: true,
          width: 180
        }
      ]
    }
  }

  async fetchHandler({ page, limit, sorters = [] }) {
    const filters = this.searchForm.queryFilters
    const pagination = { page, limit }
    const sortings = sorters
    const response = await client.query({
      query: gql`
        query partnersBizplaces($filters: [Filter!], $pagination: Pagination, $sortings: [Sorting!]) {
          partnersBizplaces(filters: $filters, pagination: $pagination, sortings: $sortings) {
            items {
              id
              name
              description
            }
            total
          }
        }
      `,
      variables: { filters, pagination, sortings }
    })

    return {
      records: response.data.partnersBizplaces.items || [],
      total: response.data.partnersBizplaces.total || 0
    }
  }

  select() {
    const selectedItems = this.dataGrist.selected
    if (!selectedItems.length) {
      this.showToast(i18next.t('text.nothing_selected'))
      return
    }

    history.back()

    this.dispatchEvent(
      new CustomEvent('select', {
        detail: selectedItems[0]
      })
    )
  }

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

customElements.define('partner-selector', PartnerSelector)
