import '@things-factory/grist-ui'

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

import { MultiColumnFormStyles } from '@things-factory/form-ui'
import { i18next, localize } from '@things-factory/i18n-base'
import { client, CustomAlert } from '@things-factory/shell'
import { isMobileDevice } from '@things-factory/utils'
import { VAS_TYPES } from '@things-factory/sales-ui/client/constants/vas'

class orderVasPopup extends localize(i18next)(LitElement) {
  static get properties() {
    return {
      vasConfig: Object,
      vasData: Object,
      type: String,
      bizplaceIds: Array,
      selectedVasData: Object
    }
  }

  static get styles() {
    return [
      css`
        :host {
          display: flex;
          flex-direction: column;
          overflow: hidden;
          background-color: white;
        }
        .container {
          flex: 1;
          display: flex;
          overflow-y: auto;
          min-height: 20vh;
        }

        .grist {
          display: flex;
          flex-direction: column;
          flex: 1;
          overflow-y: auto;
        }
        .grist h2 mwc-icon {
          vertical-align: middle;
          margin: var(--grist-title-icon-margin);
          font-size: var(--grist-title-icon-size);
          color: var(--grist-title-icon-color);
        }
        data-grist {
          overflow-y: hidden;
          flex: 1;
        }
        h2 {
          padding: var(--subtitle-padding);
          font: var(--subtitle-font);
          color: var(--subtitle-text-color);
        }
        h3 {
          font: var(--subtitle-font);
          color: var(--subtitle-text-color);
          text-align: center;
        }
        .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);
        }
      `
    ]
  }

  constructor() {
    super()
    this.bizplaceIds = []
    this.vasData = { records: [], total: 0 }
  }

  render() {
    return html`
      <div class="container">
        <div class="grist">
          <search-form id="vas" .fields=${this._vasSearchFields} @submit=${() => this.vasGrist.fetch()}></search-form>
          <h2><mwc-icon>arrow_forward</mwc-icon>${i18next.t('title.vas')}</h2>
          <data-grist
            id="vas"
            .mode=${isMobileDevice() ? 'LIST' : 'GRID'}
            .config=${this.vasConfig}
            .fetchHandler="${this.fetchVas.bind(this)}"
          ></data-grist>
        </div>
      </div>

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

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

  firstUpdated() {
    this.vasConfig = {
      list: {
        fields: ['name', 'description', 'type']
      },
      pagination: { pages: [10, 20, 50, 100] },
      rows: {
        selectable: {
          multiple: true
        },
        appendable: false
      },
      columns: [
        { type: 'gutter', gutterName: 'sequence' },
        { type: 'gutter', gutterName: 'row-selector', multiple: true },
        {
          type: 'string',
          name: 'name',
          header: i18next.t('field.name'),
          width: 300
        },
        {
          type: 'string',
          name: 'description',
          header: i18next.t('field.description'),
          width: 350
        },
        {
          type: 'string',
          name: 'type',
          header: i18next.t('field.type'),
          width: 350
        }
      ]
    }

    const type = VAS_TYPES

    this._vasSearchFields = [
      {
        label: i18next.t('label.vas'),
        name: 'vas_info',
        type: 'text',
        props: { searchOper: 'i_like' }
      },
      {
        label: i18next.t('field.type'),
        name: 'type',
        type: 'select',
        options: [
          { value: '' },
          ...Object.values(type)
            .map(type => {
              return {
                name: type,
                value: type
              }
            })
            .sort()
        ],
        props: { searchOper: 'eq' }
      }
    ]
  }

  get vasGrist() {
    return this.shadowRoot.querySelector('data-grist#vas')
  }

  get vasSearchForm() {
    return this.shadowRoot.querySelector('search-form#vas')
  }

  async fetchVas({ page, limit, sorters = [{ name: 'name' }] }) {
    let filters = await this.vasSearchForm.getQueryFilters()

    if (this.bizplaceIds && this.bizplaceIds.length > 0)
      filters = [...filters, { name: 'bizplace_id', operator: 'in', value: this.bizplaceIds }]

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

    this.vasData = {
      total: response.data.vass.total || 0,
      records:
        response.data.vass.items.map(res => {
          return {
            ...res
          }
        }) || []
    }

    return {
      total: this.vasData.total,
      records: this.vasData?.records
    }
  }

  async _selectVas() {
    let selectedVas = this.vasGrist.dirtyData.records.filter(vas => vas?.__selected__ === true)

    if (selectedVas?.length > 0) {
      this.dispatchEvent(new CustomEvent('selected', { detail: selectedVas }))
      history.back()
    } else {
      document.dispatchEvent(new CustomEvent('notify', { detail: { message: i18next.t('text.nothing_selected') } }))
    }
  }

  _cancel() {
    history.back()
  }
}

window.customElements.define('order-vas-popup', orderVasPopup)
