import '@things-factory/grist-ui'

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

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'

class SelectTransportVehiclePopup extends localize(i18next)(LitElement) {
  static get properties() {
    return {
			_searchFields: Array,
      config: Object,
      data: Object,
      importHandler: Object
    }
  }

  static get styles() {
    return [
      ScrollbarStyles,
      css`
        :host {
          display: flex;
          flex-direction: column;
          overflow: hidden;
          background-color: white;
        }

        search-form {
          overflow: visible;
        }
        .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);
        }
        .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);
        }
      `
    ]
  }

  render() {
    return html`
      <search-form
        id="search-form"
        .fields=${this._searchFields}
        @submit=${() => this.vehicleGrist.fetch()}
      ></search-form>

      <div class="grist-container">
        <div class="grist">
          <data-grist
            id="vehicle"
            .mode=${isMobileDevice() ? 'LIST' : 'GRID'}
            .config=${this.config}
            .fetchHandler=${this.fetchVehicles.bind(this)}
          ></data-grist>
        </div>
      </div>

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

  get vehicleGrist() {
    return this.shadowRoot.querySelector('data-grist#vehicle')
  }

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

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

    this.config = {
      pagination: { limit: 50, pages: [50, 100, 200, 500] },
			list: {
        fields: ['name', 'description', 'updatedAt']
      },
      rows: {
        appendable: false,
        selectable: { multiple: false } 
      },
      columns: [
        { type: 'gutter', gutterName: 'sequence' },
        {
          type: 'gutter',
          gutterName: 'row-selector',
          multiple: false
        },
        {
          type: 'string',
          name: 'id',
          hidden: true
        },
        {
          type: 'string',
          name: 'regNumber',
          header: i18next.t('field.reg_number'),
          width: 120
        },
        {
          type: 'string',
          name: 'description',
          header: i18next.t('field.description'),
          width: 180
        },
        {
          type: 'string',
          name: 'size',
          header: i18next.t('field.size'),
          width: 120
        },
        {
          type: 'string',
          name: 'status',
          header: i18next.t('field.status'),
          width: 220
        },
        {
          type: 'string',
          name: 'updatedAt',
          header: i18next.t('field.updated_at'),
          width: 180
        }
      ]
    }
  }

  async fetchVehicles({ page, limit, sorters = [] }) {
    const filters = this.searchForm.queryFilters
    const pagination = { page, limit }
    const sortings = sorters

    const response = await client.query({
      query: gql`
        query transportVehicles($filters: [Filter!]!, $pagination: Pagination, $sortings: [Sorting!]!) {
          transportVehicles(filters: $filters, pagination: $pagination, sortings: $sortings) {
            items {
              id
              name
              regNumber
              description
              size
              status
              updatedAt
            }
            total
          }
        }
      `,
      variables: { filters, pagination, sortings }
    })

    if (!response.errors) {
      return {
        total: response.data.transportVehicles.total || 0,
        records: response.data.transportVehicles.items || []
      }
    }
  }

	// not sure should handle dbl click or not
  // _dblClickHandler(columns, data, column, record, rowIndex, target) {
  //   if (this.selectMultipleProducts) return
  //   this.dispatchEvent(
  //     new CustomEvent('selected', {
  //       detail: {
  //         productDetailId: record.id,
  //         packingType: record.packingType,
  //         uom: record.uom,
  //         uomValue: record.uomValue,
  //         productName: `${record.name}(${record.description}(${record.sku}))`,
  //         isError: false,
  //         productBrand: record.brand,
  //         unitPrice: parseFloat(record.costPrice).toFixed(2),
  //         product: {
  //           id: record.productId,
  //           name: record.name,
  //           sku: record.sku,
  //           packingType: record.packingType,
  //           packingSize: record.packingSize,
  //           primaryUnit: record.uom,
  //           primaryValue: record.uomValue,
  //           costPrice: parseFloat(record.costPrice).toFixed(2)
  //         }
  //       }
  //     })
  //   )
  //   history.back()
  // }

  selectVehicle(record) {
    const selectedVehicle = this.vehicleGrist.selected[0]
    if (selectedVehicle) {
      this.dispatchEvent(
        new CustomEvent('selected', {
          detail: { 
						id: selectedVehicle.id,
						regNumber: selectedVehicle.regNumber,
            size: selectedVehicle.size
					}
        })
      )
      history.back()
    } else {
      document.dispatchEvent(
        new CustomEvent('notify', { detail: { message: i18next.t('text.no_vehicle_is_selected') } })
      )
    }
  }
}

window.customElements.define('select-transport-vehicle-popup', SelectTransportVehiclePopup)
