import '@things-factory/grist-ui'

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

import { getCodeByName } from '@things-factory/code-base'
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 { GROUP_TYPES, INVENTORY_STATUS } from '../constants'

class SelectInventoryPopUp extends localize(i18next)(LitElement) {
  static get properties() {
    return {
      productConfig: Object,
      data: Object,
      bizplaceId: String,
      releaseShelfLifeOverride: Number,
      searchFields: Array,
      selectMultipleProducts: Boolean,
      switchTypePane: String,
      recall: Boolean,
      inventoryData: 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.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')
  }

  async firstUpdated() {
    const paneType = this.switchTypePane
    const _packingType = await getCodeByName('PACKING_TYPES')
    const { SINGLE, BUNDLE } = GROUP_TYPES
    const _groupTypes = [SINGLE, BUNDLE]

    if (paneType === 'product') {
      this.searchFields = [
        {
          label: i18next.t('field.batch_id'),
          name: 'batchId',
          props: { searchOper: 'i_like' }
        },
        {
          label: i18next.t('field.product_info'),
          name: 'productName',
          props: { searchOper: 'i_like' }
        },
        {
          label: i18next.t('field.packing_type'),
          name: 'packingType',
          type: 'select',
          options: [
            { value: '' },
            ..._packingType.map(packingType => {
              return {
                name: packingType.name,
                value: packingType.name
              }
            })
          ],
          props: { searchOper: 'eq' }
        },
        {
          label: i18next.t('field.group_type'),
          name: 'groupType',
          type: 'select',
          options: [
            { value: '' },
            ..._groupTypes.map(groupType => {
              return {
                name: groupType.value,
                value: groupType.value
              }
            })
          ],
          props: { searchOper: 'eq' }
        }
      ]

      this.productConfig = {
        pagination: { pages: [10, 20, 50, 100] },
        rows: {
          appendable: false,
          selectable: { multiple: this.selectMultipleProducts ? this.selectMultipleProducts : false }
        },
        columns: [
          { type: 'gutter', gutterName: 'sequence' },
          {
            type: 'gutter',
            gutterName: 'row-selector',
            multiple: this.selectMultipleProducts ? this.selectMultipleProducts : false,
            label: true
          },
          {
            type: 'string',
            name: 'productId',
            hidden: true,
            label: true
          },
          { type: 'string', name: 'remainUomValue', hidden: true, label: true },
          {
            type: 'string',
            name: 'batchId',
            header: i18next.t('field.batch_id'),
            sortable: true,
            label: true,
            width: 120
          },
          {
            type: 'string',
            name: 'batchIdRef',
            header: i18next.t('field.batch_no_ref'),
            label: true,
            width: 120
          },
          {
            type: 'string',
            name: 'productSKU',
            header: i18next.t('field.sku'),
            sortable: true,
            label: true,
            width: 150
          },
          {
            type: 'string',
            name: 'productName',
            header: i18next.t('field.product_info'),
            sortable: true,
            label: true,
            width: 220
          },
          {
            type: 'string',
            name: 'productBrand',
            header: i18next.t('field.brand'),
            label: true,
            width: 180
          },
          {
            type: 'string',
            name: 'packingType',
            header: i18next.t('field.packing_type'),
            label: true,
            width: 100
          },
          {
            type: 'string',
            name: 'packingSize',
            header: i18next.t('field.packing_size'),
            label: true,
            width: 120
          },
          {
            type: 'string',
            name: 'uom',
            header: i18next.t('field.uom'),
            label: true,
            width: 120
          },
          {
            type: 'string',
            name: 'remainQty',
            header: i18next.t('field.remain_qty'),
            label: true,
            width: 120
          },
          {
            type: 'string',
            name: 'remainUomValueWithUom',
            header: i18next.t('field.remain_uom_value'),
            label: true,
            width: 120
          },
          {
            type: 'string',
            name: 'groupType',
            header: i18next.t('field.group_type'),
            label: true,
            width: 120
          }
        ]
      }
    } else {
      this.searchFields = [
        {
          label: i18next.t('field.lot_id'),
          name: 'palletId',
          props: { searchOper: 'i_like' }
        },
        {
          label: i18next.t('field.batch_id'),
          name: 'batchId',
          props: { searchOper: 'i_like' }
        },
        {
          label: i18next.t('field.product_info'),
          name: 'productName',
          props: { searchOper: 'i_like' }
        },
        {
          label: i18next.t('field.location'),
          name: 'locationName',
          props: { searchOper: 'i_like' }
        }
      ]

      this.productConfig = {
        pagination: { pages: [10, 20, 50, 100] },
        rows: {
          appendable: false,
          selectable: { multiple: this.selectMultipleProducts ? this.selectMultipleProducts : false }
        },
        columns: [
          { type: 'gutter', gutterName: 'sequence' },
          {
            type: 'gutter',
            gutterName: 'row-selector',
            multiple: this.selectMultipleProducts ? this.selectMultipleProducts : false
          },
          {
            type: 'string',
            name: 'productId',
            hidden: true,
            label: true
          },
          { type: 'string', name: 'remainUomValue', hidden: true, label: true },
          {
            type: 'string',
            name: 'palletId',
            header: i18next.t('field.lot_id'),
            label: true,
            width: 120
          },
          {
            type: 'string',
            name: 'cartonId',
            header: i18next.t('field.carton_id'),
            label: true,
            width: 120
          },
          {
            type: 'string',
            name: 'productSKU',
            header: i18next.t('field.sku'),
            sortable: true,
            label: true,
            width: 150
          },
          {
            type: 'string',
            name: 'productName',
            header: i18next.t('field.product_name'),
            sortable: true,
            label: true,
            width: 220
          },
          {
            type: 'string',
            name: 'productBrand',
            header: i18next.t('field.brand'),
            label: true,
            width: 180
          },
          {
            type: 'string',
            name: 'batchId',
            header: i18next.t('field.batch_id'),
            sortable: true,
            label: true,
            width: 120
          },
          {
            type: 'string',
            name: 'location',
            header: i18next.t('field.location'),
            label: true,
            width: 120
          },
          {
            type: 'string',
            name: 'packingType',
            header: i18next.t('field.packing_type'),
            label: true,
            width: 100
          },
          {
            type: 'string',
            name: 'packingSize',
            header: i18next.t('field.packing_size'),
            label: true,
            width: 120
          },
          {
            type: 'string',
            name: 'uom',
            header: i18next.t('field.uom'),
            label: true,
            width: 120
          },
          {
            type: 'string',
            name: 'remainQty',
            header: i18next.t('field.remain_qty'),
            label: true,
            width: 120
          },
          {
            type: 'string',
            name: 'remainUomValueWithUom',
            header: i18next.t('field.remain_uom_value'),
            label: true,
            width: 120
          },
          {
            type: 'string',
            name: 'batchIdRef',
            header: i18next.t('field.batch_no_ref'),
            label: true,
            width: 120
          },
          {
            type: 'string',
            name: 'remark',
            header: i18next.t('field.remark'),
            label: true,
            width: 120
          }
        ]
      }
    }
  }

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

    const paneType = this.switchTypePane
    const recall = this.recall

    if (recall) {
      filters.push({ name: 'recall', operator: '', value: recall })
    }

    if (paneType === 'product') {
      const data = this.processedInventoryData ? this.processedInventoryData : this.inventoryData
      const filtered = Array.isArray(data)
        ? data.filter(res => res && res.batchId !== null)
        : this.inventoryData.filter(res => res && res.batchId !== null)

      if (filtered?.length > 0) {
        const remapData = filtered.map(res => {
          return {
            batchId: res.batchId,
            groupType: res.groupType,
            packingType: res.packingType,
            packingSize: res.packingSize,
            productId: res.productId,
            releaseQty: res.releaseQty,
            releaseUomValue: res.releaseUomValue
          }
        })
        filters.push({ name: 'batch_product', operator: 'notin', value: remapData })
      }
      // ensure release shelf-life override is passed for product selection as well
      if (typeof this.releaseShelfLifeOverride !== 'undefined' && this.releaseShelfLifeOverride !== null) {
        filters.push({ name: 'releaseShelfLifeOverride', operator: 'eq', value: Number(this.releaseShelfLifeOverride) })
      }

      const response = await client.query({
        query: gql`
          query inventoryProductGroup($filters: [Filter!], $pagination: Pagination, $sortings: [Sorting!]) {
            inventoryProductGroup(filters: $filters, pagination: $pagination, sortings: $sortings) {
              items {
                id
                productId
                productDetailId
                batchId
                batchIdRef
                groupType
                packingSize
                productBrand
                productName
                productSKU
                isInventoryDecimal
                packingType
                remainQty
                remainUomValue
                remainUomValueWithUom
                uom
              }
              total
            }
          }
        `,
        variables: { filters, pagination, sortings }
      })

      if (!response.errors) {
        return {
          total: response.data.inventoryProductGroup.total || 0,
          records: response.data.inventoryProductGroup.items || []
        }
      }
    } else {
      if (typeof this.releaseShelfLifeOverride !== 'undefined' && this.releaseShelfLifeOverride !== null) {
        filters.push({
          name: 'releaseShelfLifeOverride',
          operator: 'eq',
          value: Number(this.releaseShelfLifeOverride)
        })
      }
      filters.push({ name: 'status', operator: 'eq', value: INVENTORY_STATUS.STORED.value })

      const data = this.inventoryData
      if (data?.length > 0) {
        filters.push({
          name: 'id',
          value: data.map(record => record?.inventory?.id),
          operator: 'notin'
        })
      }
      const response = await client.query({
        query: gql`
          query inventoriesByPallet($filters: [Filter!], $pagination: Pagination, $sortings: [Sorting!]) {
            inventoriesByPallet(filters: $filters, pagination: $pagination, sortings: $sortings) {
              items {
                id
                batchId
                palletId
                cartonId
                productId
                productDetailId
                productSKU
                productName
                productBrand
                palletId
                isInventoryDecimal
                location {
                  name
                  type
                }
                packingType
                packingSize
                uom
                remainQty
                remainUomValue
                remainUomValueWithUom
                batchIdRef
                remark
              }
              total
            }
          }
        `,
        variables: { filters, pagination, sortings }
      })

      if (!response.errors) {
        return {
          total: response.data.inventoriesByPallet.total || 0,
          records:
            response.data.inventoriesByPallet.items.map(item => {
              return {
                ...item,
                location: item?.location?.name,
                locationType: item?.location?.type
              }
            }) || []
        }
      }
    }
  }

  selectProduct() {
    const paneType = this.switchTypePane

    if (this.selectMultipleProducts !== true) {
      const selectedProduct = this.productGrist.selected[0]
      if (selectedProduct) {
        this.dispatchEvent(
          new CustomEvent('selected', {
            detail: {
              packingType: selectedProduct.packingType,
              uom: selectedProduct.uom,
              uomValue: selectedProduct.uomValue,
              productName: `${selectedProduct.name}(${selectedProduct.description}(${selectedProduct.sku}))`,
              isError: false,
              productBrand: selectedProduct.brand,
              product: {
                id: selectedProduct.productId,
                name: selectedProduct.name,
                sku: selectedProduct.sku,
                packingType: selectedProduct.packingType,
                packingSize: selectedProduct.packingSize,
                primaryUnit: selectedProduct.uom,
                primaryValue: selectedProduct.uomValue,
                isInventoryDecimal: selectedProduct.isInventoryDecimal
              },
              productDetail: {
                id: selectedProduct.productDetailId
              }
            }
          })
        )
        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 {
            productName:
              paneType === 'product' ? `${itm.batchId}(${itm.productName})` : `${itm.batchId}(${itm.palletId})`,
            productSKU: itm.productSKU,
            product: { id: itm.productId, name: itm.productName },
            uom: itm.uom,
            uomValue: itm.uomValue,
            productBrand: itm.productBrand,
            packingType: itm.packingType,
            packingSize: itm.packingSize,
            remainQty: itm.remainQty,
            remainUomValueWithUom: itm.remainUomValueWithUom,
            productId: itm.productId,
            productDetailId: itm.productDetailId,
            isInventoryDecimal: itm.isInventoryDecimal,
            remainUomValue: itm.remainUomValue,
            batchId: itm.batchId,
            batchIdRef: itm.batchIdRef,
            groupType: itm.groupType,
            location: itm.location,
            releaseQty: 0,
            releaseUomValue: 0,
            palletId: itm.palletId,
            inventory: {
              id: itm.id,
              productName:
                paneType === 'product' ? `${itm.batchId}(${itm.productName})` : `${itm.batchId}(${itm.palletId})`,
              productSKU: itm.productSKU,
              uom: itm.uom,
              uomValue: itm.uomValue,
              productBrand: itm.productBrand,
              packingType: itm.packingType,
              packingSize: itm.packingSize,
              remainQty: itm.remainQty,
              remainUomValueWithUom: itm.remainUomValueWithUom,
              productId: itm.productId,
              productDetailId: itm.productDetailId,
              remainUomValue: itm.remainUomValue,
              batchId: itm.batchId,
              batchIdRef: itm.batchIdRef,
              groupType: itm.groupType,
              location: itm.location,
              locationType: itm.locationType,
              palletId: itm.palletId
            }
          }
        })

        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-inventory-popup', SelectInventoryPopUp)
