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 SelectProductPopup extends localize(i18next)(LitElement) {
  static get properties() {
    return {
      productConfig: Object,
      productDetailConfig: Object,
      data: Object,
      bizplaceId: String,
      searchFields: Array,
      _productName: String,
      productDetailData: Array,
      selectMultipleProducts: Boolean
    }
  }

  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.productGrist.fetch()}
      ></search-form>

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

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

  get productGrist() {
    return this.shadowRoot.querySelector('data-grist#product')
  }

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

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

    this.productConfig = {
      pagination: { pages: [10, 20, 50, 100] },
      rows: {
        appendable: false,
        selectable: { multiple: this.selectMultipleProducts ? this.selectMultipleProducts : false },
        handlers: { dblclick: this._dblClickHandler.bind(this) }
      },
      columns: [
        { type: 'gutter', gutterName: 'sequence' },
        {
          type: 'gutter',
          gutterName: 'row-selector',
          multiple: this.selectMultipleProducts ? this.selectMultipleProducts : false
        },
        {
          type: 'string',
          name: 'productId',
          hidden: true
        },
        {
          type: 'string',
          name: 'sku',
          header: i18next.t('field.sku'),
          width: 120
        },
        {
          type: 'string',
          name: 'name',
          header: i18next.t('field.name'),
          width: 180
        },
        {
          type: 'string',
          name: 'brand',
          header: i18next.t('field.brand'),
          width: 120
        },
        {
          type: 'string',
          name: 'description',
          header: i18next.t('field.description'),
          width: 220
        },
        {
          type: 'string',
          name: 'packingType',
          header: i18next.t('field.packing_type'),
          width: 180
        },
        {
          type: 'float',
          name: 'packingSize',
          header: i18next.t('field.packing_size'),
          width: 100
        },
        {
          type: 'string',
          name: 'uom',
          header: i18next.t('field.uom'),
          width: 120
        },
        {
          type: 'string',
          name: 'uomValue',
          header: i18next.t('field.uom_value'),
          width: 120
        },
        {
          type: 'float',
          name: 'costPrice',
          header: i18next.t('field.unit_cost'),
          width: 120
        }
      ]
    }
  }

  async fetchProducts({ page, limit, sorters = [] }) {
    const filters = [
      ...this.searchForm.queryFilters,
      { name: 'bizplace_id', operator: 'eq', value: this.bizplaceId },
      { name: 'create_arrival_notice', operator: 'eq', value: true }
    ]
    const pagination = { page, limit }
    const sortings = sorters

    const response = await client.query({
      query: gql`
        query productDetails($filters: [Filter!]!, $pagination: Pagination, $sortings: [Sorting!]!) {
          productDetails(filters: $filters, pagination: $pagination, sortings: $sortings) {
            items {
              id
              name
              packingType
              packingSize
              uom
              uomValue
              costPrice
              product {
                id
                name
                sku
                brand
                description
                type
                costPrice
                isInventoryDecimal
                isRequiredCheckExpiry
              }
            }
            total
          }
        }
      `,
      variables: { filters, pagination, sortings }
    })

    if (!response.errors) {
      return {
        total: response.data.productDetails.total || 0,
        records:
          response.data.productDetails.items.map(item => {
            return {
              ...item,
              productName: item.product.name,
              productId: item.product.id,
              sku: item.product.sku,
              brand: item.product.brand,
              name: item.name,
              description: item.product.description,
              costPrice: (item.costPrice = (item?.costPrice || 0).toFixed(2)),
              isInventoryDecimal: item.product.isInventoryDecimal,
              isRequiredCheckExpiry: item.product.isRequiredCheckExpiry
            }
          }) || []
      }
    }
  }

  _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),
            isInventoryDecimal: record.isInventoryDecimal,
            isRequiredCheckExpiry: record.isRequiredCheckExpiry
          }
        }
      })
    )
    history.back()
  }

  selectProduct(record) {
    if (this.selectMultipleProducts !== true) {
      const selectedProduct = this.productGrist.selected[0]
      if (selectedProduct) {
        this.dispatchEvent(
          new CustomEvent('selected', {
            detail: {
              productDetailId: selectedProduct.id,
              packingType: selectedProduct.packingType,
              uom: selectedProduct.uom,
              uomValue: selectedProduct.uomValue,
              productName: `${selectedProduct.name}(${selectedProduct.description}(${selectedProduct.sku}))`,
              isError: false,
              productBrand: selectedProduct.brand,
              unitPrice: parseFloat(selectedProduct.costPrice).toFixed(2),
              product: {
                id: selectedProduct.productId,
                name: selectedProduct.name,
                sku: selectedProduct.sku,
                packingType: selectedProduct.packingType,
                packingSize: selectedProduct.packingSize,
                primaryUnit: selectedProduct.uom,
                primaryValue: selectedProduct.uomValue,
                costPrice: parseFloat(selectedProduct.costPrice).toFixed(2),
                isInventoryDecimal: selectedProduct.isInventoryDecimal,
                isRequiredCheckExpiry: selectedProduct.isRequiredCheckExpiry
              }
            }
          })
        )
        history.back()
      } else {
        document.dispatchEvent(
          new CustomEvent('notify', { detail: { message: i18next.t('text.product_is_not_selected') } })
        )
      }
    } else {
      const selectedMultipleProducts = this.productGrist.selected
      if (selectedMultipleProducts) {
        const multipleProducts = selectedMultipleProducts.map(itm => {
          return {
            productDetailId: itm.id,
            packingType: itm.packingType,
            uom: itm.uom,
            uomValue: itm.uomValue,
            productName: `${itm.name}(${itm.description}(${itm.sku}))`,
            isError: false,
            unitPrice: parseFloat(itm.costPrice).toFixed(2),
            productBrand: itm.brand,
            product: {
              id: itm.productId,
              name: itm.name,
              sku: itm.sku,
              packingType: itm.packingType,
              packingSize: itm.packingSize,
              primaryUnit: itm.uom,
              primaryValue: itm.uomValue,
              costPrice: parseFloat(itm.costPrice).costPrice,
              isInventoryDecimal: itm.isInventoryDecimal,
              isRequiredCheckExpiry: itm.isRequiredCheckExpiry
            }
          }
        })

        this.dispatchEvent(
          new CustomEvent('selected', {
            detail: {
              multipleProducts
            }
          })
        )
        history.back()
      } else {
        document.dispatchEvent(
          new CustomEvent('notify', { detail: { message: i18next.t('text.product_is_not_selected') } })
        )
      }
    }
  }
}

window.customElements.define('select-product-popup', SelectProductPopup)
