import '@things-factory/form-ui'
import '@things-factory/grist-ui'
import '../inventory/serial-number-list-popup'

import gql from 'graphql-tag'
import { css, html } from 'lit-element'
import { connect } from 'pwa-helpers/connect-mixin'

import { getCodeByName } from '@things-factory/code-base'
import { i18next, localize } from '@things-factory/i18n-base'
import { CONDITION_OF_GOODS } from '../constants'
import { client, PageView, store, gqlContext } from '@things-factory/shell'
import { CommonButtonStyles, ScrollbarStyles } from '@things-factory/styles'
import { isMobileDevice } from '@things-factory/utils'
import { openPopup } from '@things-factory/layout-base'

class InventoryAdjustmentApproval extends connect(store)(localize(i18next)(PageView)) {
  static get styles() {
    return [
      ScrollbarStyles,
      css`
        :host {
          display: flex;
          flex-direction: column;
          overflow: hidden;
        }

        search-form {
          overflow: visible;
        }

        .grist-container {
          overflow-y: hidden;
          display: flex;
          flex: 1;
        }

        .grist {
          background-color: var(--main-section-background-color);
          display: flex;
          flex-direction: column;
          overflow-y: auto;
        }

        .grist-inventory-change {
          flex: 3;
        }

        .grist-inventory-changes-detail {
          flex: 2;
        }

        data-grist {
          overflow-y: auto;
          flex: 1;
        }
      `
    ]
  }

  static get properties() {
    return {
      _searchFields: Array,
      _lockedPallet: Array,
      config: Object,
      data: Object,
      _detailData: Object,
      _compareColumn: Array,
      _selectedInventoryChange: Object
    }
  }

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

      <div class="grist-container">
        <div class="grist grist-inventory-change">
          <data-grist
            id="grist-inventory-change"
            .mode=${isMobileDevice() ? 'LIST' : 'GRID'}
            .config=${this.config}
            .fetchHandler="${this.fetchHandler.bind(this)}"
          ></data-grist>
        </div>
        <div class="grist grist-inventory-changes-detail">
          <data-grist
            id="grist-inventory-detail"
            .mode=${isMobileDevice() ? 'LIST' : 'GRID'}
            .config=${this.detailGristConfig}
            .data="${this._detailData}"
          ></data-grist>
        </div>
      </div>
    `
  }

  get context() {
    return {
      title: i18next.t('title.inventory_adjustment_approval'),
      actions: [
        {
          title: i18next.t('button.reject'),
          action: this._rejectInventoryChanges.bind(this),
          ...CommonButtonStyles.reject
        },
        {
          title: i18next.t('button.approve'),
          action: this._approveInventoryChanges.bind(this),
          ...CommonButtonStyles.approve
        }
      ],
      help: 'operato-wms/inventory/inventory-adjustment-approval'
    }
  }

  get dataGrist() {
    return this.shadowRoot.querySelector('#grist-inventory-change')
  }

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

  get _fromDateInput() {
    return this.searchForm.shadowRoot.querySelector('input[name=fromDate]')
  }

  get _toDateInput() {
    return this.searchForm.shadowRoot.querySelector('input[name=toDate]')
  }

  async pageInitialized() {
    this._selectedInventoryChange = null
    this._lockedPallet = []
    const partners = await this._fetchPartners()
    const _approvalStatus = await getCodeByName('APPROVAL_STATUS')

    this._compareColumn = [
      { column: 'batchId', name: 'Batch No' },
      { column: 'batchIdRef', name: 'Batch No Ref' },
      { column: 'packingType', name: 'Packing Type' },
      { column: 'packingSize', name: 'Packing Size' },
      { column: 'bizplace', name: 'Customer' },
      { column: 'sku', name: 'SKU' },
      { column: 'product', name: 'Product' },
      { column: 'location', name: 'Location' },
      { column: 'qty', name: 'Quantity' },
      { column: 'uom', name: 'Uom' },
      { column: 'uomValue', name: 'UomValue' },
      { column: 'conditionOfGoods', name: 'Inventory Quality' },
      { column: 'expirationDate', name: 'Exp. Date' },
      { column: 'manufactureDate', name: 'Mfg. Date' },
      { column: 'unitCost', name: 'Unit Cost' },
      { column: 'adjustmentCode', name: 'Adjustment Code' },
      { column: 'adjustmentNote', name: 'Note' },
      { column: 'inventoryItemChange', name: 'Inventory Item Changes' },
      { column: 'status', name: 'Status' }
    ]

    this.config = {
      rows: {
        appendable: false,
        classifier: record => {
          return {
            emphasized: !!this._lockedPallet.find(changes => changes['id'] === record.id)
          }
        },
        selectable: {
          multiple: true
        },
        handlers: {
          click: (columns, data, column, record, rowIndex) => {
            if (record) {
              this._selectedInventoryChange = record
              let recordDiff = []
              let compareData = []

              switch (record.status.toLowerCase()) {
                case 'pending':
                  compareData = record.inventory
                  break
                case 'rejected':
                case 'approved':
                  compareData = { ...record.lastInventoryHistory }

                  if (compareData) {
                    compareData.qty =
                      (record.lastInventoryHistory.openingQty || 0) + record.lastInventoryHistory.qty || 0
                    compareData.uomValue =
                      (record.lastInventoryHistory.openingUomValue || 0) + record.lastInventoryHistory.uomValue || 0
                  }
                  break
                default:
                  break
              }

              compareData.sku = compareData?.product?.sku

              if (compareData == null) {
                this._compareColumn.map(item => {
                  if (record[item.column]) {
                    let updateVal =
                      typeof record[item.column] === 'object' ? record[item.column].name : record[item.column]

                    // Translate conditionOfGoods value
                    if (item.column === 'conditionOfGoods' && updateVal) {
                      updateVal = this._getConditionOfGoodsLabel(updateVal)
                    }

                    recordDiff.push({
                      column: item.name,
                      current: '[N/A]',
                      update: updateVal
                    })
                  }
                })
              } else {
                this._compareColumn.map(item => {
                  let currentVal = compareData[item.column]?.name || compareData[item.column] || '[N/A]'
                  let updatedVal

                  if (item.column == 'status' && record.transactionType == 'MISSING') {
                    updatedVal = record.transactionType || '[N/A]'
                  } else if (item.column == 'status') {
                    updatedVal = '[N/A]'
                  }

                  if (item.column !== 'status') {
                    updatedVal = record[item.column]?.name || record[item.column] || '[N/A]'
                  }

                  // Translate conditionOfGoods values
                  if (item.column === 'conditionOfGoods') {
                    if (currentVal && currentVal !== '[N/A]') {
                      currentVal = this._getConditionOfGoodsLabel(currentVal)
                    }
                    if (updatedVal && updatedVal !== '[N/A]') {
                      updatedVal = this._getConditionOfGoodsLabel(updatedVal)
                    }
                  }

                  recordDiff.push({
                    column: item.name,
                    current: currentVal || '[N/A]',
                    update: updatedVal != null && currentVal != updatedVal ? updatedVal : '[N/A]'
                  })
                })
              }

              this._detailData = {
                records: recordDiff
              }
            }
          }
        }
      },
      list: { fields: ['transactionType', 'status', 'palletId', 'cartonId', 'customerName', 'creator', 'createdAt'] },
      columns: [
        { type: 'gutter', gutterName: 'sequence' },
        { type: 'gutter', gutterName: 'row-selector', multiple: true },
        {
          type: 'string',
          name: 'transactionType',
          header: i18next.t('field.type'),
          sortable: true,
          width: 130
        },
        {
          type: 'string',
          name: 'status',
          header: i18next.t('field.status'),
          sortable: true,
          width: 130
        },
        {
          type: 'string',
          name: 'palletId',
          header: i18next.t('field.lot_id'),
          sortable: true,
          width: 130
        },
        {
          type: 'string',
          name: 'cartonId',
          header: i18next.t('field.carton_id'),
          sortable: true,
          width: 130
        },
        {
          type: 'string',
          name: 'customerName',
          header: i18next.t('field.company'),
          sortable: true,
          width: 230
        },
        {
          type: 'object',
          name: 'creator',
          header: i18next.t('field.submitted_by'),
          sortable: true,
          width: 150
        },
        {
          type: 'datetime',
          name: 'createdAt',
          header: i18next.t('field.submitted_at'),
          sortable: true,
          width: 150
        },
        {
          type: 'datetime',
          name: 'updatedAt',
          header: i18next.t('field.updated_at'),
          sortable: true,
          width: 150
        }
      ]
    }

    this.detailGristConfig = {
      pagination: { infinite: true },
      list: { fields: ['column', 'current', 'update'] },
      rows: {
        appendable: false,
        handlers: {
          click: (columns, data, column, record, rowIndex) => {
            if (record.column == 'Inventory Item Changes')
              this._openSerialNumberPopup(this._selectedInventoryChange, rowIndex)
          }
        }
      },
      columns: [
        { type: 'gutter', gutterName: 'sequence' },
        {
          type: 'string',
          name: 'column',
          header: i18next.t('field.column'),
          sortable: false,
          width: 130
        },
        {
          type: 'string',
          name: 'current',
          header: i18next.t('field.before'),
          sortable: false,
          width: 240
        },
        {
          type: 'string',
          name: 'update',
          header: i18next.t('field.after'),
          sortable: false,
          width: 240
        }
      ]
    }

    this._searchFields = [
      {
        label: i18next.t('field.company'),
        name: 'bizplace',
        type: 'select',
        options: [
          { value: '' },
          ...partners
            .map(partner => {
              return {
                name: `${partner.name} ${partner.description ? `(${partner.description})` : ''}`,
                value: partner.id
              }
            })
            .sort(this._compareValues('name', 'asc'))
        ],
        props: { searchOper: 'eq' }
      },
      {
        label: i18next.t('field.lot_id'),
        name: 'palletId',
        type: 'text',
        props: { searchOper: 'i_like' }
      },
      {
        label: i18next.t('field.carton_id'),
        name: 'cartonId',
        type: 'text',
        props: { searchOper: 'i_like' }
      },
      {
        label: i18next.t('field.status'),
        name: 'status',
        type: 'select',
        options: [
          { value: '' },
          ..._approvalStatus.map(stat => {
            return {
              name: stat.name,
              value: stat.name
            }
          })
        ],
        props: { searchOper: 'eq' }
      },
      {
        label: i18next.t('field.from_date'),
        name: 'fromDate',
        type: 'date',
        props: {
          searchOper: 'eq',
          max: new Date().toISOString().split('T')[0]
        },
        attrs: ['custom'],
        value: (() => {
          let date = new Date()
          date.setMonth(date.getMonth() - 1)
          return date.toISOString().split('T')[0]
        })(),
        handlers: { change: this._modifyDateRange.bind(this) }
      },
      {
        label: i18next.t('field.to_date'),
        name: 'toDate',
        type: 'date',
        props: {
          searchOper: 'eq',
          min: (() => {
            let date = new Date()
            date.setMonth(date.getMonth() - 1)
            return date.toISOString().split('T')[0]
          })(),
          max: new Date().toISOString().split('T')[0]
        },
        attrs: ['custom'],
        value: new Date().toISOString().split('T')[0]
      }
    ]
  }

  async pageUpdated(changes, lifecycle) {
    if (this.active) {
      this.dataGrist.fetch()
    }
  }

  async fetchHandler({ page, limit, sorters = [] }) {
    const filters = await this.searchForm.getQueryFilters()
    const response = await client.query({
      query: gql`
        query inventoryChanges($filters: [Filter!], $pagination: Pagination, $sortings: [Sorting!]) {
          inventoryChanges(filters: $filters, pagination: $pagination, sortings: $sortings) {
            items {
              id
              palletId
              cartonId
              batchId
              batchIdRef
              packingType
              packingSize
              qty
              uom
              uomValue
              status
              transactionType
              expirationDate
              manufactureDate
              unitCost
              adjustmentCode
              adjustmentNote
              conditionOfGoods
              sku
              bizplace {
                id
                name
                description
              }
              product {
                id
                name
                sku
                description
                type
              }
              location {
                id
                name
                description
              }
              inventory {
                cartonId
                batchId
                batchIdRef
                packingType
                packingSize
                status
                bizplace {
                  id
                  name
                  description
                }
                product {
                  id
                  name
                  sku
                  description
                  type
                }
                location {
                  id
                  name
                  description
                }
                qty
                uom
                uomValue
                expirationDate
                manufactureDate
                unitCost
                adjustmentCode
                adjustmentNote
                conditionOfGoods
              }
              lastInventoryHistory {
                batchId
                packingType
                packingSize
                batchIdRef
                status
                bizplace {
                  id
                  name
                  description
                }
                product {
                  id
                  sku
                  name
                  description
                  type
                }
                location {
                  id
                  name
                  description
                }
                openingQty
                qty
                openingUomValue
                uom
                uomValue
                expirationDate
                manufactureDate
                unitCost
              }
              createdAt
              updatedAt
              creator {
                name
                description
              }
            }
            total
          }
        }
      `,
      variables: { filters: [...filters], pagination: { page, limit }, sortings: sorters }
    })

    return {
      total: response.data.inventoryChanges.total || 0,
      records:
        response.data.inventoryChanges.items.map(item => {
          let inventoryChangesExpDate = item?.expirationDate
            ? this._convertUnixTimestampToDate(item?.expirationDate)
            : null
          let lastInventoryChangesExpDate = item?.lastInventoryHistory?.expirationDate
            ? this._convertUnixTimestampToDate(item?.lastInventoryHistory?.expirationDate)
            : null

          let inventoryExpDate = item?.inventory?.expirationDate
            ? this._convertUnixTimestampToDate(item?.inventory?.expirationDate)
            : null

          let inventoryChangesMfgDate = item?.manufactureDate
            ? this._convertUnixTimestampToDate(item?.manufactureDate)
            : null
          let lastInventoryChangesMfgDate = item?.lastInventoryHistory?.manufactureDate
            ? this._convertUnixTimestampToDate(item?.lastInventoryHistory?.manufactureDate)
            : null

          let inventoryMfgDate = item?.inventory?.manufactureDate
            ? this._convertUnixTimestampToDate(item?.inventory?.manufactureDate)
            : null

          return {
            ...item,
            cartonId: item.inventory?.cartonId,
            inventory: {
              ...item.inventory,
              expirationDate: inventoryExpDate ? inventoryExpDate : null,
              manufactureDate: inventoryMfgDate ? inventoryMfgDate : null
            },
            lastInventoryHistory: {
              ...item.lastInventoryHistory,
              expirationDate: lastInventoryChangesExpDate ? lastInventoryChangesExpDate : null,
              manufactureDate: lastInventoryChangesMfgDate ? lastInventoryChangesMfgDate : null
            },
            customerName: item?.inventory?.bizplace?.name || item.bizplace.name,
            expirationDate: inventoryChangesExpDate ? inventoryChangesExpDate : null,
            manufactureDate: inventoryChangesMfgDate ? inventoryChangesMfgDate : null
          }
        }) || []
    }
  }

  _modifyDateRange(e) {
    const fromDate = e.currentTarget.value

    if (this._toDateInput.value < fromDate) this._toDateInput.value = fromDate

    let min = new Date(fromDate)
    let today = new Date()
    today.setHours(0, 0, 0, 0)

    min = min.toISOString().split('T')[0]

    this._toDateInput.min = min
  }

  async _fetchPartners() {
    const response = await client.query({
      query: gql`
        query partnersBizplaces($filters: [Filter!]) {
          partnersBizplaces(filters: $filters) {
            items {
              id
              name
              description
            }
          }
        }
      `,
      variables: { filters: [] }
    })

    if (!response.errors) {
      return response.data.partnersBizplaces.items
    }
  }

  async _approveInventoryChanges() {
    var patches = this.dataGrist.selected
      .filter(item => item.status.toLowerCase() == 'pending')
      .map(item => {
        return { id: item.id }
      })
    if (patches && patches.length) {
      const response = await client.mutate({
        mutation: gql`
          mutation warehouseInventoryAdjustment($patches: [InventoryChangePatch!]!) {
            warehouseInventoryAdjustment(patches: $patches) {
              items {
                id
              }
              total
            }
          }
        `,
        variables: { patches },
        context: gqlContext()
      })
      if (!response.errors) {
        this._lockedPallet = response.data.warehouseInventoryAdjustment.items
        this._showToast({
          message:
            response.data.warehouseInventoryAdjustment.total > 0
              ? 'Highlighted pallet could not be approved due to ongoing process.'
              : i18next.t('text.data_approved'),
          option: 7000
        })
        this.dataGrist.fetch()
      }
    }
  }

  async _rejectInventoryChanges() {
    var patches = this.dataGrist.selected
      .filter(item => item.status.toLowerCase() == 'pending')
      .map(item => {
        return { id: item.id }
      })
    if (patches && patches.length) {
      const response = await client.mutate({
        mutation: gql`
          mutation rejectInventoryChanges($patches: [InventoryChangePatch!]!) {
            rejectInventoryChanges(patches: $patches)
          }
        `,
        variables: { patches }
      })

      if (!response.errors) {
        this.dataGrist.fetch()
        this._showToast({ message: i18next.t('text.data_rejected') })
      }
    }
  }

  get _columns() {
    return this.config.columns
  }

  async fetchProduct(bizplace = []) {
    const response = await client.query({
      query: gql`
        query productsByBizplace($filters: [Filter!]) {
          productsByBizplace(filters: $filters) {
            items {
              id
              name
            }
          }
        }
      `,
      variables: { filters: [...bizplace] }
    })
    return response.data.productsByBizplace.items
  }

  _convertUnixTimestampToDate(unixTimestampValue) {
    let convertedUnix = new Date(unixTimestampValue)
    return `${convertedUnix.getDate()}/${convertedUnix.getMonth() + 1}/${convertedUnix.getFullYear()}`
  }

  _compareValues(key, order = 'asc') {
    return function innerSort(a, b) {
      if (!a.hasOwnProperty(key) || !b.hasOwnProperty(key)) {
        return 0
      }

      const varA = typeof a[key] === 'string' ? a[key].toUpperCase() : a[key]
      const varB = typeof b[key] === 'string' ? b[key].toUpperCase() : b[key]

      let comparison = 0
      if (varA > varB) {
        comparison = 1
      } else if (varA < varB) {
        comparison = -1
      }
      return order === 'desc' ? comparison * -1 : comparison
    }
  }

  _openSerialNumberPopup(inventory, rowIndex) {
    openPopup(
      html`
        <serial-number-list-popup
          .title="${i18next.t('title.serial_number_list')}"
          .inventory=${inventory}
          .adjustmentType=${'APPROVAL'}
          .enableRemove=${false}
          .enableUpdateBtn=${false}
        ></serial-number-list-popup>
      `,
      {
        backdrop: false,
        size: 'large',
        title: i18next.t('title.serial_number_list')
      }
    )
  }

  _showToast({ type, message, option }) {
    document.dispatchEvent(
      new CustomEvent('notify', {
        detail: {
          type,
          message,
          option
        }
      })
    )
  }

  _getDateString(date) {
    return `${date.getDate()} ${date.toLocaleString('default', { month: 'short' })} ${date.getFullYear()}`
  }

  _getConditionOfGoodsLabel(value) {
    const condition = Object.values(CONDITION_OF_GOODS).find(c => c.value === value)
    return condition ? i18next.t(`label.${condition.name}`) : value || ''
  }
}

window.customElements.define('inventory-adjustment-approval', InventoryAdjustmentApproval)
