import '@things-factory/grist-ui'

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

import { i18next, localize } from '@things-factory/i18n-base'
import { ScrollbarStyles } from '@things-factory/styles'
import { isMobileDevice } from '@things-factory/utils'

import { ORDER_PRODUCT_STATUS } from '../../constants'

export class ViewProductChangesPopup extends localize(i18next)(LitElement) {
  static get styles() {
    return [
      ScrollbarStyles,
      css`
        :host {
          display: flex;
          flex-direction: column;
          overflow: hidden;
          background-color: white;
        }
        .grist-container {
          display: flex;
          flex: 1;
          margin: 10px;
        }
        .grist {
          display: flex;
          flex-direction: column;
          flex: 1;
          overflow-y: auto;
        }
        .grist h2 mwc-icon {
          vertical-align: middle;
          margin: var(--grist-title-icon-margin);
          font-size: var(--grist-title-icon-size);
          color: var(--grist-title-icon-color);
        }
        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);
        }
        [danger] {
          --mdc-theme-primary: var(--mdc-danger-button-primary-color);
        }
      `
    ]
  }

  static get properties() {
    return {
      config: Object,
      data: Object,
      enableDirectInbound: Boolean
    }
  }

  render() {
    return html`
      <div class="grist-container">
        <div class="grist">
          <h2><mwc-icon>list_alt</mwc-icon>${i18next.t('title.order_products')}</h2>
          <data-grist
            id="product-grist"
            .mode="${isMobileDevice() ? 'LIST' : 'GRID'}"
            .config="${this.config}"
            .data="${this.productData}"
          ></data-grist>
        </div>
      </div>

      <div class="button-container">
        <mwc-button raised @click=${() => history.back()} label="${i18next.t('button.close')}"></mwc-button>
      </div>
    `
  }

  constructor() {
    super()
    this.productData = { records: [] }
  }

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

  updated(changedProps) {
    if (changedProps.has('data')) {
      this.productData = {
        ...this.data,
        records: this.data.records.filter(
          item => item.status === ORDER_PRODUCT_STATUS.ADDED.value || item.status === ORDER_PRODUCT_STATUS.EDITED.value
        )
      }
    }
  }

  firstUpdated() {
    const columns = [
      { type: 'gutter', gutterName: 'sequence' },
      {
        type: 'string',
        name: 'batchId',
        header: i18next.t('field.batch_id'),
        width: 150
      },
      {
        type: 'string',
        name: 'adjustedBatchId',
        header: i18next.t('field.adjusted_batch_id'),
        width: 150
      },
      {
        type: 'string',
        name: 'batchIdRef',
        header: i18next.t('field.batch_no_ref'),
        width: 150
      },
      {
        type: 'string',
        name: 'adjustedBatchIdRef',
        header: i18next.t('field.adjusted_batch_id_ref'),
        width: 150
      },
      {
        type: 'string',
        name: 'productSku',
        header: i18next.t('field.sku'),
        width: 150
      },
      {
        type: 'object',
        name: 'product',
        header: i18next.t('field.product'),
        record: { options: { queryName: 'products' } },
        width: 350
      },
      {
        type: 'string',
        name: 'packingType',
        header: i18next.t('field.packing_type'),
        width: 150
      },
      {
        type: 'string',
        name: 'adjustedPackingType',
        header: i18next.t('field.adjusted_packing_type'),
        width: 150
      },
      {
        type: 'float',
        name: 'uomValue',
        header: i18next.t('field.uom_value'),
        width: 80
      },
      {
        type: 'float',
        name: 'adjustedUomValue',
        header: i18next.t('field.adjusted_uom_value'),
        width: 80
      },
      {
        type: 'string',
        name: 'uom',
        header: i18next.t('field.uom'),
        width: 80
      },
      {
        type: 'string',
        name: 'adjustedUom',
        header: i18next.t('field.adjusted_uom'),
        width: 80
      },
      {
        type: 'float',
        name: 'packQty',
        header: i18next.t('field.pack_qty'),
        width: 80
      },
      {
        type: 'float',
        name: 'adjustedPackQty',
        header: i18next.t('field.adjusted_pack_qty'),
        width: 80
      },
      {
        type: 'float',
        name: 'totalUomValue',
        header: i18next.t('field.total_uom_value'),
        width: 120
      },
      {
        type: 'integer',
        name: 'adjustedTotalUomValue',
        header: i18next.t('field.adjusted_total_uom_value'),
        width: 120
      },
      {
        type: 'integer',
        name: 'palletQty',
        header: i18next.t('field.pallet_qty'),
        width: 80
      },
      {
        type: 'integer',
        name: 'adjustedPalletQty',
        header: i18next.t('field.adjusted_pallet_qty'),
        width: 80
      },
      {
        type: 'date',
        name: 'manufactureDate',
        header: i18next.t('field.manufacture_date'),
        width: 120
      },
      {
        type: 'float',
        name: 'unitPrice',
        header: i18next.t('field.unit_price'),
        width: 80
      },
      {
        type: 'float',
        name: 'adjustedUnitPrice',
        header: i18next.t('field.adjusted_unit_price'),
        width: 80
      },
      {
        type: 'string',
        name: 'remark',
        header: i18next.t('field.remark'),
        width: 200
      }
    ]

    function insertAfter(cols, anchorName, newCols) {
      const idx = cols.findIndex(c => c.name === anchorName)
      if (idx >= 0) cols.splice(idx + 1, 0, ...newCols)
    }

    const expDateColumn = {
      type: 'date',
      name: 'expDate',
      header: i18next.t('field.exp_date'),
      record: { editable: true },
      width: 120
    }

    const adjustedExpDateColumn = {
      type: 'date',
      name: 'adjustedExpDate',
      header: i18next.t('field.adjusted_exp_date'),
      width: 120
    }

    const locationColumn = {
      type: 'object',
      name: 'location',
      header: i18next.t('field.location'),
      record: { editable: true },
      handlers: {
        click: (columns, data, column, record, rowIndex) => {
          this._openLocationSelection(rowIndex)
        }
      },
      width: 150
    }

    const adjustedLocationColumn = {
      type: 'object',
      name: 'adjustedLocation',
      header: i18next.t('field.adjusted_location'),
      width: 150
    }

    const warehouseColumn = {
      type: 'object',
      name: 'warehouse',
      header: i18next.t('field.warehouse'),
      width: 150
    } 

    const adjustedWarehouseColumn = {
      type: 'object',
      name: 'adjustedWarehouse',
      header: i18next.t('field.adjusted_warehouse'),
      width: 150
    }

    if (this.enableDirectInbound) {
      insertAfter(columns, 'adjustedPalletQty', [expDateColumn, adjustedExpDateColumn] )
      insertAfter(columns, 'manufactureDate', [warehouseColumn, locationColumn, adjustedWarehouseColumn, adjustedLocationColumn])
    }

    this.config = {
      list: {
        fields: [
          'batchId',
          'adjustedBatchId',
          'batchIdRef',
          'adjustedBatchIdRef',
          'product',
          'packingType',
          'adjustedPackingType',
          'packQty',
          'adjustedPackQty',
          'palletQty',
          'adjustedPalletQty',
          'uom',
          'adjustedUom',
          'totalUomValue',
          'adjustedTotalUomValue',
          'unitPrice',
          'adjustedUnitPrice'
        ]
      },
      pagination: { infinite: true },
      rows: { appendable: false },
      columns
    }
  }

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

window.customElements.define('view-product-changes-popup', ViewProductChangesPopup)
