import '@things-factory/form-ui'
import '@things-factory/grist-ui'
import '../inventory/inventory-by-product-detail'

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

import { getPartnerCodeByName } from '@things-factory/code-base'
import { i18next, localize } from '@things-factory/i18n-base'
import { openPopup } from '@things-factory/layout-base'
import { client, PageView, store } from '@things-factory/shell'
import { flattenObject, isMobileDevice } from '@things-factory/utils'

function formatLocalDate(date = new Date()) {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

class InventorySummaryReport extends connect(store)(localize(i18next)(PageView)) {
  static get styles() {
    return css`
      :host {
        display: flex;
        flex-direction: column;
        width: 100%;
      }

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

      .summary {
        background-color: var(--main-section-background-color);
        display: flex;
        flex-direction: column;
        overflow-y: auto;
        align-items: flex-end;
        padding: var(--data-list-item-padding);
        display: grid;
        font-size: 14px;
        color: #394e64;
        grid-template-columns: repeat(2, 1fr);
        grid-auto-rows: minmax(24px, auto);
      }
    `
  }

  static get properties() {
    return {
      _searchFields: Object,
      _config: Object,
      _partners: Object,
      _gristData: Object,
      _byPallet: Boolean,
      data: Object
    }
  }

  get context() {
    return {
      title: i18next.t('title.inventory_summary_report'),
      printable: {
        accept: ['preview'],
        content: this
      },
      exportable: {
        name: i18next.t('title.inventory_summary_report'),
        data: this._exportableData.bind(this)
      },
      help: 'operato-wms/report/inventory-summary-report'
    }
  }

  get dataGrist() {
    return this.shadowRoot.querySelector('data-grist')
  }

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

  get _bizplaceSelector() {
    return this.searchForm.shadowRoot.querySelector('select[name=bizplace]')
  }

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

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

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

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

      <data-grist
        .mode=${isMobileDevice() ? 'LIST' : 'GRID'}
        .config=${this._config}
        .fetchHandler="${this.fetchHandler.bind(this)}"
      ></data-grist>

      ${this._byPallet
        ? html`
            <div class="summary">
              <label>${i18next.t('label.total_inbound_pallet')}: ${this._gristData.totalInboundQty}</label>
              <label>${i18next.t('label.total_opening_balance')}: ${this._gristData.totalOpeningBal}</label>
            </div>
          `
        : ''}
    `
  }

  get searchFields() {
    return [
      {
        label: i18next.t('field.company'),
        name: 'bizplace',
        type: 'select',
        options: [
          { value: '' },
          ...this._partners
            .map(partner => {
              return {
                name: `${partner.name} ${partner.description ? `(${partner.description})` : ''}`,
                value: partner.id
              }
            })
            .sort(this._compareValues('name', 'asc'))
        ],
        handlers: { change: this._companyChanged.bind(this) },
        props: { searchOper: 'eq' }
      },
      {
        label: i18next.t('field.from_date'),
        name: 'fromDate',
        type: 'date',
        props: {
          searchOper: 'eq',
          max: formatLocalDate(new Date())
        },
        value: (() => {
          const date = new Date()
          date.setMonth(date.getMonth() - 1)
          return formatLocalDate(date)
        })(),
        handlers: { change: this._modifyDateRange.bind(this) }
      },
      {
        label: i18next.t('field.to_date'),
        name: 'toDate',
        type: 'date',
        props: {
          searchOper: 'eq',
          min: (() => {
            const date = new Date()
            date.setMonth(date.getMonth() - 1)
            return formatLocalDate(date)
          })(),
          max: (() => {
            const max = new Date()
            return formatLocalDate(max)
          })()
        },
        value: formatLocalDate(new Date()),
        handlers: { change: this._submit.bind(this) }
      },
      {
        label: i18next.t('field.product_info'),
        name: 'product',
        type: 'string',
        props: { searchOper: 'in' }
      },
      {
        label: i18next.t('field.product_type'),
        name: 'productType',
        type: 'select',
        options: [{ value: '' }],
        props: { searchOper: 'eq' }
      },
      {
        label: i18next.t('field.has_transaction_or_balance'),
        name: 'hasTransactionOrBalance',
        type: 'checkbox',
        value: true,
        props: { searchOper: 'eq' }
      },
      {
        label: i18next.t('field.by_pallet'),
        name: 'byPallet',
        type: 'checkbox',
        props: { searchOper: 'eq' },
        handlers: { change: this._submit.bind(this) }
      }
    ]
  }

  get reportConfig() {
    let columns = [
      { type: 'gutter', gutterName: 'sequence' },
      {
        type: 'gutter',
        gutterName: 'button',
        icon: 'reorder',
        handlers: {
          click: this._showInventoryInfo.bind(this)
        }
      },
      {
        type: 'string',
        name: 'productSku',
        header: i18next.t('field.sku'),
        width: 150
      },
      {
        type: 'string',
        name: 'productNameDescription',
        header: i18next.t('field.product'),
        width: 400
      },
      {
        type: 'string',
        name: 'productType',
        header: i18next.t('field.product_type'),
        width: 150
      },
      {
        type: 'string',
        name: 'packingType',
        header: i18next.t('field.packing_type'),
        width: 150
      },
      {
        type: 'number',
        name: 'packingSize',
        header: i18next.t('field.packing_size'),
        width: 150
      },
      {
        type: 'float',
        name: 'openingQty',
        header: i18next.t('field.opening_balance'),
        width: 140
      },
      {
        type: 'float',
        name: 'totalInQty',
        record: { align: 'center' },
        header: i18next.t('field.inbound_qty'),
        width: 140
      },
      {
        type: 'float',
        name: 'adjustmentQty',
        header: i18next.t('field.adjusted_qty'),
        record: { align: 'center' },
        width: 140
      },
      {
        type: 'float',
        name: 'totalOutQty',
        record: { align: 'center' },
        header: i18next.t('field.outbound_qty'),
        width: 140
      },
      {
        type: 'float',
        name: 'missingQty',
        record: { align: 'center' },
        header: i18next.t('field.missing_qty'),
        width: 140
      },
      {
        type: 'float',
        name: 'closingQty',
        record: { align: 'center' },
        header: i18next.t('field.closing_balance'),
        width: 140
      }
    ]

    if (this._byPallet) {
      columns.splice(6, 1)
    }

    return {
      list: {
        fields: [
          'productSku',
          'productName',
          'productType',
          'packingType',
          'packingSize',
          'adjustmentQty',
          'openingQty',
          'totalInQty',
          'totalOutQty',
          'missingQty',
          'closingQty'
        ]
      },
      pagination: { limit: 50, pages: [50, 100, 200, 500, 1000] },
      rows: {
        selectable: false,
        insertable: false,
        appendable: false
      },
      columns: columns
    }
  }

  async pageInitialized() {
    this._byPallet = false
    this._gristData = { total: 0, totalWithOpeningBalance: 0, records: [] }
    this._products = []
    this._partners = [...(await this._fetchPartners())]

    this._searchFields = this.searchFields
    this._config = this.reportConfig
  }

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

  async fetchHandler({ page, limit, sorters = [] }) {
    this._byPallet = this._byPalletInput.checked
    try {
      this._validate()
      let filter = this.searchForm.queryFilters.map(filter => {
        switch (filter.name) {
          case 'fromDate':
            let fromDt = new Date(filter.value)
            fromDt.setHours(0)
            filter.value = fromDt.toISOString()
            break
          case 'toDate':
            let toDt = new Date(filter.value)
            toDt.setHours(23, 59, 59)
            filter.value = toDt.toISOString()
            break
          default:
            break
        }
        return filter
      })
      const response = await client.query({
        query: gql`
          query inventoryHistorySummaryReport($filters: [Filter!], $pagination: Pagination, $sortings: [Sorting!]) {
            inventoryHistorySummaryReport(filters: $filters, pagination: $pagination, sortings: $sortings) {
              items {
                batchId
                packingType
                packingSize
                product {
                  id
                  sku
                  name
                  description
                  type
                }
                openingQty
                missingQty
                totalInQty
                totalOutQty
                adjustmentQty
                closingQty
              }
              total
              totalInboundQty
              totalOpeningBal
            }
          }
        `,
        variables: { filters: filter, pagination: { page, limit }, sortings: sorters }
      })

      const data = {
        total: response.data.inventoryHistorySummaryReport.total,
        records:
          response.data.inventoryHistorySummaryReport.items.map(item =>
            flattenObject({
              ...item,
              productSku: item.product.sku,
              productNameDescription: `${item.product.name} (${item.product.description})`,
              productName: item.product.name,
              productDescription: item.product.description,
              productType: item.product.type
            })
          ) || []
      }

      this._gristData = {
        ...data,
        totalInboundQty: response.data.inventoryHistorySummaryReport.totalInboundQty || 0,
        totalOpeningBal: response.data.inventoryHistorySummaryReport.totalOpeningBal || 0
      }

      return data
    } catch (e) {
      this._showToast(e)
    }
  }

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

    if (!response.errors) {
      return response.data.partnersBizplaces.items
    }
  }
  _validate() {
    if (!this.searchForm.shadowRoot.querySelector('form').checkValidity())
      throw new Error(i18next.t('text.invalid_form_value'))
    if (!this._bizplaceSelector.value) throw new Error(i18next.t('text.no_company_selected'))
    if (!this._fromDateInput.value) throw new Error(i18next.t('text.from_date_is_empty'))
    if (!this._toDateInput.value) throw new Error(i18next.t('text.to_date_is_empty'))
  }

  _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
    }
  }

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

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

    const minDate = new Date(fromDate)
    if (Number.isNaN(minDate.getTime())) return

    const min = formatLocalDate(minDate)
    this._toDateInput.min = min
    this._submit()
  }

  async _companyChanged(e) {
    const _productType = !this._bizplaceSelector.value
      ? []
      : await getPartnerCodeByName(
          'PRODUCT_TYPES',
          this._partners.find(p => p.id == this._bizplaceSelector.value)?.company?.domainId || ''
        )

    // update searchFields with the latest productTypes and toDate's min props
    this._searchFields = this._searchFields.map(field => {
      switch (field.name) {
        case 'productType':
          field.options = [
            { value: '' },
            ..._productType.map(type => {
              return {
                name: type.name,
                value: type.name
              }
            })
          ]
          break

        case 'toDate':
          field.props = {
            ...field.props,
            min: this._toDateInput.min
          }
          break
      }

      return field
    })
  }

  _submit(e) {
    this._byPallet = this._byPalletInput.checked
    this._config = { ...this.reportConfig }
    this.searchForm.submit()
  }

  async _exportableData() {
    try {
      var headerSetting = [
        { header: i18next.t('field.sku_code'), key: 'product|sku', width: 25, type: 'string' },
        { header: i18next.t('field.product_name'), key: 'product|name', width: 50, type: 'string' },
        { header: i18next.t('field.product_description'), key: 'product|description', width: 50, type: 'string' },
        { header: i18next.t('field.product_type'), key: 'product|type', width: 30, type: 'string' },
        { header: i18next.t('field.packing_type'), key: 'packingType', width: 25, type: 'string' },
        { header: i18next.t('field.packing_size'), key: 'packingSize', width: 25, type: 'string' },
        { header: i18next.t('field.opening_balance'), key: 'openingQty', width: 25, type: 'string' },
        { header: i18next.t('field.inbound_qty'), key: 'totalInQty', width: 25, type: 'string' },
        { header: i18next.t('field.adjusted_qty'), key: 'adjustmentQty', width: 25, type: 'string' },
        { header: i18next.t('field.outbound_qty'), key: 'totalOutQty', width: 25, type: 'string' },
        { header: i18next.t('field.missing_qty'), key: 'missingQty', width: 25, type: 'string' },
        { header: i18next.t('field.closing_balance'), key: 'closingQty', width: 25, type: 'string' }
      ]

      if (this._byPallet) {
        headerSetting.splice(5, 1)
      }

      var exportData = {
        header: [...headerSetting],
        data: (await this.fetchHandler({ page: 1, limit: 9999999 })).records
      }

      return exportData
    } catch (e) {
      this._showToast(e)
    }
  }

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

  _showInventoryInfo(columns, data, column, record, rowIndex) {
    openPopup(
      html`
        <inventory-by-product-detail
          .productId="${record['product|id']}"
          .bizplaceId="${this._bizplaceSelector.value}"
        ></inventory-by-product-detail>
      `,
      {
        backdrop: true,
        size: 'large',
        title: `${record['product|name']}`
      }
    )
  }
}

window.customElements.define('inventory-summary-report', InventorySummaryReport)
