import { MultiColumnFormStyles } from '@things-factory/form-ui'
import { i18next, localize } from '@things-factory/i18n-base'
import { client, CustomAlert, gqlContext } from '@things-factory/shell'
import { isMobileDevice } from '@things-factory/utils'
import gql from 'graphql-tag'
import { css, html, LitElement } from 'lit-element'
import { ScrollbarStyles } from '@things-factory/styles'
import { inspect } from '../../../config.development'

class CycleCountInventoryDetailsPopup extends localize(i18next)(LitElement) {
  static get styles() {
    return [
      ScrollbarStyles,
      css`
        :host {
          display: flex;
          flex-direction: column;
          overflow: hidden;
          background-color: white;

          --grid-record-emphasized-background-color: #ffdbdb;
          --grid-record-emphasized-color: #703f3f;
        }
        search-form {
          overflow: visible;
        }
        data-grist {
          overflow-y: auto;
          flex: 1;
        }
        .gtinGrist {
          display: flex;
          flex-direction: column;
          overflow-y: auto;
          padding-left: 5px;
          padding-right: 5px;
        }
        .grist-container {
          overflow-y: hidden;
          display: flex;
          flex: 1;
        }
        .button-container {
          padding: 10px 0 12px 0;
          text-align: center;
        }
        [danger] {
          --mdc-theme-primary: var(--mdc-danger-button-primary-color);
        }
        .header {
          display: grid;
          grid-template-columns: repeat(24, 1fr);
          grid-gap: var(--form-grid-gap);
          grid-auto-rows: minmax(24px, auto);
          max-width: var(--form-multi-column-max-width);
          margin-top: var(--form-margin);
          margin-left: var(--form-margin);
          margin-right: var(--form-margin);
        }
        .header legend {
          grid-column: span 24;
          text-transform: capitalize;

          padding: var(--legend-padding);
          font: var(--legend-font);
          color: var(--legend-text-color);
          border-bottom: var(--legend-border-bottom);
        }
      `
    ]
  }

  static get properties() {
    return {
      cycleCountNo: String,
      inventoryId: String,
      cartonId: String,
      palletId: String,
      enableCartonLabel: { type: Boolean },
      config: Object,
      data: Object
    }
  }

  constructor() {
    super()
    this.data = {}
  }

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

  render() {
    return html`
      <div class="grist">
        <data-grist
          .mode="${isMobileDevice() ? 'LIST' : 'GRID'}"
          .config="${this.config}"
          .data="${this.data}"
          .fetchHandler="${this.fetchHandler.bind(this)}"
        ></data-grist>
      </div>

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

  async firstUpdated() {
    this.config = {
      rows: { appendable: false },
      list: {
        fields: [
          'originBatchNo',
          'inspectedBatchNo',
          'originLocation',
          'inspectedLocation',
          'originUomValue',
          'inspectedUomValue'
        ]
      },
      pagination: { infinite: true },
      columns: [
        { type: 'gutter', gutterName: 'sequence' },
        {
          type: 'string',
          name: 'countNo',
          header: i18next.t('field.count_no'),
          width: 120
        },
        {
          type: 'string',
          name: 'description',
          header: i18next.t('field.description'),
          width: 100
        },
        {
          type: 'string',
          name: 'originBatchNo',
          header: i18next.t('field.system_batch_no'),
          width: 150
        },
        {
          type: 'string',
          name: 'inspectedBatchNo',
          header: i18next.t('field.inspected_batch_no'),
          width: 200
        },
        {
          type: 'string',
          name: 'originLocationName',
          header: i18next.t('field.system_location'),
          width: 200
        },
        {
          type: 'string',
          name: 'inspectedLocationName',
          header: i18next.t('field.inspected_location'),
          width: 200
        },
        {
          type: 'string',
          name: 'originExpirationDate',
          header: i18next.t('field.system_expiration_date'),
          width: 200
        },
        {
          type: 'string',
          name: 'inspectedExpirationDate',
          header: i18next.t('field.inspected_expiration_date'),
          width: 200
        }
      ]
    }
    if (this.cartonId && this.enableCartonLabel) {
      this.config.columns = this.config.columns.map(column => {
        if (column.name === 'originUomValue' || column.name === 'inspectedUomValue') {
          return { ...column, hidden: true }
        }
        return column
      })
    }
  }

  async fetchHandler({ page, limit, sorters = [] }) {
    try {
      if (!this.inventoryId && !this.cycleCountNo) return

      const pagination = { page, limit }
      const sortings = sorters

      const filters = [
        { name: 'inventoryId', operator: 'eq', value: this.inventoryId },
        { name: 'cycleCountNo', operator: 'eq', value: this.cycleCountNo }
      ]

      const response = await client.query({
        query: gql`
          query inventoryCheckItems($filters: [Filter!], $pagination: Pagination, $sortings: [Sorting!]) {
            inventoryCheckItems(filters: $filters, pagination: $pagination, sortings: $sortings) {
              items {
                id
                name
                countNo
                originBatchNo
                inspectedBatchNo
                systemExpiryDate
                inspectedExpiryDate
                product {
                  description
                }
                originLocation {
                  id
                  name
                }
                inspectedLocation {
                  id
                  name
                  description
                }
                originUomValue
                inspectedUomValue
                bizplace {
                  id
                  name
                  description
                }
                updater {
                  name
                  description
                }
              }
              total
            }
          }
        `,
        variables: {
          filters,
          pagination,
          sortings
        },
        context: gqlContext()
      })

      const items = response?.data?.inventoryCheckItems?.items || []

      if (!response.errors) {
        this.data = {
          total: response.data.inventoryCheckItems.total || 0,
          records:
            response.data.inventoryCheckItems.items.map(itm => {
              return {
                ...itm,
                countNo: itm.countNo,
                description: itm.product?.description,
                inspectedBatchNo: itm.inspectedBatchNo,
                originLocationName: itm.originLocation ? itm.originLocation.name : null,
                inspectedLocationName: itm.inspectedLocation ? itm.inspectedLocation.name : null,
                originUomValue: itm.originUomValue,
                inspectedUomValue: itm.inspectedUomValue,
                originExpirationDate: itm.systemExpiryDate,
                inspectedExpirationDate: itm.inspectedExpiryDate
              }
            }) || []
        }
      }
    } catch (e) {
      this._showToast(e)
    }
  }

  _getStdDate() {
    let date = new Date()
    date.setDate(date.getDate())
    return date.toISOString().split('T')[0]
  }

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

window.customElements.define('cycle-count-inventory-details-popup', CycleCountInventoryDetailsPopup)
