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 } from '@things-factory/shell'
import { isMobileDevice } from '@things-factory/utils'
import { VAS_TYPES } from '@things-factory/sales-ui/client/constants/vas'

class SelectVasPopup extends localize(i18next)(LitElement) {
  static get properties() {
    return {
      vasConfig: Object,
      selectedVasConfig: Object,
      vasData: Object,
      type: String,
      partnerBizplaceIds: Array,
      selectedVasData: Object,
      deletedVas: Array
    }
  }

  static get styles() {
    return [
      MultiColumnFormStyles,
      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.partnerBizplaceIds = []
    this.vasData = { records: [], total: 0 }
    this.selectedVasData = { records: [] }
    this.deletedVas = []
  }

  render() {
    return html`
      <h3>${this.currentSku.productSKU} (${this.currentSku.batchId})</h3>
      <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 class="grist">
          <h2><mwc-icon>arrow_back</mwc-icon>${i18next.t('title.selected_vas')}</h2>
          <data-grist
            id="selectedVas"
            .mode=${isMobileDevice() ? 'LIST' : 'GRID'}
            .config=${this.selectedVasConfig}
            .data=${this.selectedVasData}
          ></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.confirm')}`}"
          raised
        ></mwc-button>
      </div>
    `
  }

  firstUpdated() {
    // pre-exsiting vas
    if (this.currentSelectedVas) {
      this.selectedVasData.records = this.currentSelectedVas
      this.currentSelectedVas = undefined
    }

    this.vasConfig = {
      list: {
        fields: ['name', 'description', 'type']
      },
      pagination: { pages: [10, 20, 50, 100] },
      rows: {
        selectable: {
          multiple: true
        },
        appendable: false
        // handlers: { dblclick: this._dblClickHandler.bind(this) }
      },
      columns: [
        { type: 'gutter', gutterName: 'sequence' },
        {
          type: 'gutter',
          gutterName: 'button',
          icon: 'add',
          handlers: {
            click: (columns, data, column, record, rowIndex) => {
              this.selectedVasData = {
                records: [
                  ...this.selectedVasData?.records,
                  {
                    id: record.id,
                    name: record.name,
                    description: record.description,
                    type: record.type
                  }
                ]
              }

              this.firstUpdated()
            }
          }
        },
        {
          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
        }
      ]
    }

    this.selectedVasConfig = {
      list: {
        fields: ['name', 'description', 'type']
      },
      pagination: { infinite: true },
      rows: {
        selectable: {
          multiple: true
        },
        appendable: false
        // handlers: { dblclick: this._dblClickHandler.bind(this) }
      },
      columns: [
        { type: 'gutter', gutterName: 'sequence' },
        {
          type: 'gutter',
          gutterName: 'button',
          icon: 'close',
          handlers: {
            click: (columns, data, column, record, rowIndex) => {
              this.selectedVasGrist.dirtyData?.records.splice(rowIndex, 1)
              this.selectedVasData = { records: this.selectedVasGrist.dirtyData?.records }
              this.deletedVas.push({ ...record })
              this.firstUpdated()
            }
          }
        },
        {
          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' }
      }
    ]
  }

  _filterSelectedVas() {
    this.selectedVasSearchForm.getQueryFilters
  }

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

  get selectedVasGrist() {
    return this.shadowRoot.querySelector('data-grist#selectedVas')
  }

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

  get selectedVasSearchForm() {
    return this.shadowRoot.querySelector('search-form#selectedVas')
  }

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

    if (this.selectedVasData?.records.length > 0) {
      filters.push({
        name: 'id',
        operator: 'notin',
        value: this.selectedVasData?.records.map(selected => selected.id)
      })
    }

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

    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,
            fullAddress: res.address
              ? `${res.address ? res.address : ''} ${res.address2 ? res.address : ''} ${
                  res.postCode ? res.postCode + ',' : ''
                } ${res.city ? res.city + ',' : ''} ${res.state ? res.state + ',' : ''} Malaysia`
              : ''
          }
        }) || []
    }

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

  _selectVas() {
    if (this.selectedVasGrist.dirtyData.records.length > 0) {
      this.dispatchEvent(new CustomEvent('selected', { detail: this.selectedVasGrist.dirtyData.records }))
      this.dispatchEvent(new CustomEvent('deleted', { detail: this.deletedVas }))
      history.back()
    } else {
      document.dispatchEvent(new CustomEvent('notify', { detail: { message: i18next.t('text.nothing_selected') } }))
    }
  }

  // _dblClickHandler(columns, data, column, record, rowIndex, target) {
  //   this.dispatchEvent(new CustomEvent('selected', { detail: record }))
  //   history.back()
  // }

  _cancel() {
    history.back()
  }
}

window.customElements.define('select-vas-popup', SelectVasPopup)
