import '@things-factory/form-ui'
import '@things-factory/grist-ui'
import { i18next, localize } from '@things-factory/i18n-base'
import { client } from '@things-factory/shell'
import { ScrollbarStyles } from '@things-factory/styles'
import { isMobileDevice } from '@things-factory/utils'
import gql from 'graphql-tag'
import { css, html, LitElement } from 'lit-element'

class BranchLogisticsPopup extends localize(i18next)(LitElement) {
  static get properties() {
    return {
      _searchFields: Array,
      orderInformation: Object,
      branchConfig: Object,
      data: Object
    }
  }

  static get styles() {
    return [
      ScrollbarStyles,
      css`
        :host {
          display: flex;
          flex-direction: column;
          overflow: hidden;
          background-color: white;
        }
        .grist {
          display: flex;
          flex-direction: column;
          flex: 1;
          overflow-y: auto;
        }
        .grist-container {
          overflow-y: hidden;
          display: flex;
          flex: 1;
        }
        data-grist {
          overflow-y: hidden;
          flex: 1;
        }
        h2 {
          padding: var(--subtitle-padding);
          font: var(--subtitle-font);
          color: var(--subtitle-text-color);
          border-bottom: var(--subtitle-border-bottom);
        }
        .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);
        }
        [danger] {
          --mdc-theme-primary: var(--mdc-danger-button-primary-color);
        }
      `
    ]
  }

  render() {
    return html`
      <div class="grist-container">
        <div class="grist">
          <h2>${i18next.t('label.branch_info')}</h2>
          <data-grist
            id="logisticsBranch"
            .mode=${isMobileDevice() ? 'LIST' : 'GRID'}
            .config=${this.branchConfig}
            .fetchHandler="${this.fetchHandler.bind(this)}"
          ></data-grist>
        </div>
      </div>

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

  updated(changes) {
    if (this.active) {
      this.dataGrist.fetch()
    }
  }

  firstUpdated() {
    this.branchConfig = {
      rows: {
        selectable: {
          multiple: false
        },
        appendable: false
      },
      pagination: { infinite: true },
      columns: [
        { type: 'gutter', gutterName: 'sequence' },
        { type: 'gutter', gutterName: 'row-selector', multiple: false },
        {
          type: 'string',
          name: 'branchId',
          header: i18next.t('field.branch_id'),
          width: 180
        },
        {
          type: 'string',
          name: 'country',
          header: i18next.t('field.country'),
          width: 150
        },
        {
          type: 'string',
          name: 'state',
          header: i18next.t('field.state'),
          width: 120
        },
        {
          type: 'string',
          name: 'city',
          header: i18next.t('field.city'),
          width: 120
        },
        {
          type: 'string',
          name: 'address',
          header: i18next.t('field.address'),
          width: 120
        },
        {
          type: 'string',
          name: 'zipcode',
          header: i18next.t('field.zipcode'),
          width: 120
        },
        {
          type: 'string',
          name: 'district',
          header: i18next.t('field.district'),
          width: 120
        },
        {
          type: 'string',
          name: 'town',
          record: { align: 'left' },
          header: i18next.t('field.town'),
          width: 120
        }
      ]
    }
  }

  get logisticsBranchGrist() {
    return this.shadowRoot.querySelector('data-grist#logisticsBranch')
  }

  async fetchHandler() {
    const response = await client.query({
      query: gql`
        query getBranchList($storeId: String!, $orderNo: String!) {
          getBranchList(storeId: $storeId, orderNo: $orderNo) {
            branchId
            country
            state
            city
            address
            zipcode
            district
            town
          }
        }
      `,
      variables: {
        storeId: this.orderInformation.marketplaceStore.id,
        orderNo: this.orderInformation.orderNo
      }
    })

    if (!response.errors) {
      return {
        records: response.data.getBranchList || []
      }
    }
  }

  _selectBranch() {
    const selectedBranch = this.logisticsBranchGrist.selected[0]
    if (selectedBranch) {
      this.dispatchEvent(new CustomEvent('selected', { detail: this.logisticsBranchGrist.selected[0] }))
      history.back()
    } else {
      document.dispatchEvent(
        new CustomEvent('notify', { detail: { message: i18next.t('text.branch_is_not_selected') } })
      )
    }
  }
}

window.customElements.define('branch-logistics-popup', BranchLogisticsPopup)
