import '@things-factory/form-ui'
import '@things-factory/grist-ui'

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

import { i18next, localize } from '@things-factory/i18n-base'
import { client, PageView, store } from '@things-factory/shell'

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 ProductLabelReport extends connect(store)(localize(i18next)(PageView)) {
  static get styles() {
    return css`
      :host {
        display: flex;
        flex-direction: column;
        width: 100%;
      }

      data-report {
        flex: 1;
      }
    `
  }

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

  get context() {
    return {
      title: i18next.t('title.product_label_report'),
      printable: {
        accept: ['preview'],
        content: this
      },
      exportable: {
        name: i18next.t('title.date_product_label', {
          state: {
            text: (() => {
              let date = new Date()
              return date.getFullYear().toString() + (date.getMonth() + 1).toString() + date.getDate().toString()
            })()
          }
        }),
        data: this._exportableData.bind(this)
      },
      help: 'operato-wms/report/inventory-report'
    }
  }

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

  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]')
  }

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

      <data-report .config=${this._config} .fetchHandler=${this.fetchHandler.bind(this)}></data-report>
    `
  }

  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'))
        ],
        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: formatLocalDate(new Date())
        },
        value: formatLocalDate(new Date())
      },
      {
        label: i18next.t('field.product_type'),
        name: 'type',
        type: 'string',
        props: { searchOper: 'in' }
      }
    ]
  }

  get reportConfig() {
    return {
      rows: {
        selectable: false,
        groups: [{ column: 'type', title: 'Sub Total' }],
        totals: ['count']
      },
      columns: [
        {
          type: 'string',
          name: 'type',
          header: i18next.t('field.type'),
          imex: { header: i18next.t('field.type'), key: 'type', width: 25, type: 'string' },
          width: 400
        },
        {
          type: 'string',
          name: 'date',
          header: i18next.t('field.date'),
          sortable: true,
          imex: { header: i18next.t('field.date'), key: 'createdAt', width: 25, type: 'string' },
          width: 200
        },
        {
          type: 'number',
          name: 'count',
          header: i18next.t('field.count'),
          record: { align: 'center' },
          sortable: true,
          imex: { header: i18next.t('field.count'), key: 'count', width: 25, type: 'string' },
          width: 120
        }
      ]
    }
  }

  async pageInitialized() {
    this._products = []
    this._partners = [...(await this._fetchPartners())]

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

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

  async fetchHandler({ page, limit, sorters = [] }) {
    // return {
    //   total: 0,
    //   records: [
    //     { productType: 'DRUM', count: 16, createdAt: '2021/10/13' },
    //     { productType: 'WOOD', count: 50, createdAt: '2021/10/18' },
    //     { productType: 'WOOD', count: 6, createdAt: '2021/10/11' },
    //     { productType: 'WOOD', count: 21, createdAt: '2021/10/15' },
    //     { productType: 'GSC', count: 30, createdAt: '2021/10/20' },
    //     { productType: 'GSC', count: 3, createdAt: '2021/10/11' },
    //     { productType: 'WOOD', count: 8, createdAt: '2021/10/12' },
    //     { productType: 'FG', count: 4, createdAt: '2021/10/18' },
    //     { productType: 'GSC', count: 2, createdAt: '2021/10/14' },
    //     { productType: 'GSC', count: 213, createdAt: '2021/10/12' },
    //     { productType: 'WOOD', count: 3, createdAt: '2021/10/20' },
    //     { productType: 'GSC', count: 51, createdAt: '2021/10/16' },
    //     { productType: 'PKG', count: 1, createdAt: '2021/10/18' },
    //     { productType: 'GSC', count: 27, createdAt: '2021/10/15' },
    //     { productType: 'GSC', count: 174, createdAt: '2021/10/18' }
    //   ]
    // }
    try {
      this._validate()

      var tzoffset = new Date().getTimezoneOffset() * 60
      const response = await client.query({
        query: gql`
          query productLabelReport($filters: [Filter!], $pagination: Pagination, $sortings: [Sorting!]) {
            productLabelReport(filters: $filters, pagination: $pagination, sortings: $sortings) {
              items {
                type
                date
                count
                bizplace {
                  id
                  name
                }
              }
              total
            }
          }
        `,
        variables: {
          filters: [...this.searchForm.queryFilters, { name: 'tzoffset', operator: 'custom', value: tzoffset }],
          pagination: { page, limit },
          sortings: sorters
        }
      })

      return {
        total: response.data.productLabelReport.total,
        records: response.data.productLabelReport.items
      }

      // @farishelmi any usage for this? If no please remove.
      // return {
      //   total: 0,
      //   records:
      //     response.data.inventoryHistoryReport.map(item => {
      //       let date = new Date(parseInt(item.createdAt))
      //       return flattenObject({
      //         ...item,
      //         createdAt:
      //           date.getDate().toString() + '/' + (date.getMonth() + 1).toString() + '/' + date.getFullYear().toString()
      //       })
      //     }) || []
      // }
    } 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
            }
          }
        }
      `,
      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'))
  }

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

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

  _exportableData() {
    try {
      const report = this.report
      var headerSetting = [
        ...report._config.columns
          .filter(column => column.type !== 'gutter' && column.record !== undefined && column.imex !== undefined)
          .map(column => {
            return column.imex
          })
      ]

      return {
        header: headerSetting,
        data: report.data.records,
        groups: report._config.rows.groups,
        totals: report._config.rows.totals
      }
    } catch (e) {
      this._showToast(e)
    }
  }

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

window.customElements.define('product-label-report', ProductLabelReport)
