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

import gql from 'graphql-tag'
import { css, html } from 'lit-element'

import { MultiColumnFormStyles } from '@things-factory/form-ui'
import { i18next, localize } from '@things-factory/i18n-base'
import { client, CustomAlert, navigate, PageView } from '@things-factory/shell'
import { CommonButtonStyles } from '@things-factory/styles'
import { isMobileDevice } from '@things-factory/utils'

import { WORKSHEET_STATUS, WORKSHEET_TYPE } from '../constants'

class WorksheetReplenishment extends localize(i18next)(PageView) {
  static get properties() {
    return {
      _worksheetStatus: String,
      _worksheetType: String,
      _orderNo: String,
      orderInformation: Object,
      worksheetDetailData: Object
    }
  }

  static get styles() {
    return [
      MultiColumnFormStyles,
      css`
        :host {
          display: flex;
          flex-direction: column;
          overflow-x: auto;
        }
        .form-container {
          display: flex;
        }
        .form-container > form {
          flex: 1;
        }
        barcode-tag {
          width: 100px;
          height: 100px;
          margin: 10px;
        }
        .grist {
          background-color: var(--main-section-background-color);
          display: flex;
          flex-direction: row;
          flex: 1;
          overflow-y: auto;
        }
        .grist-column {
          flex: 1;
          display: flex;
          flex-direction: column;
          overflow: auto;
        }
        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 {
          margin: var(--grist-title-margin);
          border: var(--grist-title-border);
          font: var(--grist-title-font);
          color: var(--secondary-color);
        }

        .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);
        }

        h2 + data-grist {
          padding-top: var(--grist-title-with-grid-padding);
        }
      `
    ]
  }

  constructor() {
    super()
    this.worksheetDetailData = { records: [] }
    this._logisticsInitiated = false
  }

  get context() {
    var actions = [
      {
        title: i18next.t('button.back'),
        action: () => history.back(),
        ...CommonButtonStyles.back
      }
    ]

    if (this._worksheetStatus === WORKSHEET_STATUS.DEACTIVATED.value) {
      actions.push({
        title: i18next.t('button.activate'),
        action: this._activateWorksheet.bind(this),
        ...CommonButtonStyles.activate
      })
    }

    return {
      title: i18next.t('title.worksheet_replenishment'),
      actions,
      printable: {
        accept: ['preview'],
        content: this
      }
    }
  }

  render() {
    return html`
      <div class="form-container">
        <form class="multi-column-form">
          <fieldset>
            <legend>${i18next.t('title.replenishment')}</legend>
            <label>${i18next.t('label.order_no')}</label>
            <input name="replenishment" readonly />

            <label>${i18next.t('label.picker')}</label>
            <input name="assignee" readonly />

            <label>${i18next.t('label.status')}</label>
            <input name="status" readonly />
          </fieldset>
        </form>

        <barcode-tag bcid="qrcode" .value=${this._orderNo} showLogo="true"></barcode-tag>
      </div>

      <div class="grist">
        <div class="grist-column">
          <h2><mwc-icon>list_alt</mwc-icon>${i18next.t('title.worksheet_detail')}</h2>
          <data-grist
            id="wsd-grist"
            .mode=${isMobileDevice() ? 'LIST' : 'GRID'}
            .config=${this.config}
            .data="${this.worksheetDetailData}"
          ></data-grist>
        </div>
      </div>
    `
  }

  async pageUpdated(changes) {
    if (this.active && (changes.resourceId || this._worksheetNo)) {
      if (changes.resourceId) {
        this._worksheetNo = changes.resourceId
      }
    }

    this.config = {
      list: {
        fields: ['cartonId', 'sku', 'product', 'location', 'transferQty', 'status']
      },
      pagination: { infinite: true },
      rows: { appendable: false },
      columns: [
        { type: 'gutter', gutterName: 'sequence' },
        {
          type: 'string',
          name: 'cartonId',
          header: i18next.t('field.carton_id'),
          width: 150
        },
        {
          type: 'string',
          name: 'sku',
          header: i18next.t('field.sku'),
          width: 150
        },
        {
          type: 'string',
          name: 'name',
          header: i18next.t('field.product'),
          width: 150
        },
        {
          type: 'object',
          name: 'location',
          header: i18next.t('field.storage_location'),
          width: 150
        },

        {
          type: 'integer',
          name: 'transferQty',
          header: i18next.t('field.transfer_qty'),
          width: 150
        },
        {
          type: 'string',
          name: 'status',
          header: i18next.t('field.status'),
          width: 150
        }
      ]
    }
    await this.fetchWorksheet()
    this.updateContext()
    if (this._worksheetType == WORKSHEET_TYPE.PUTAWAY_REPLENISHMENT.value) {
      let index = this.config.columns.findIndex(itm => itm.name == 'location')
      this.config.columns[index].header = i18next.t('field.picking_location')
    }
  }

  // pageInitialized() {
  //   this.config = {
  //     list: {
  //       fields: ['cartonId', 'sku', 'product', 'location', 'transferQty', 'status']
  //     },
  //     pagination: { infinite: true },
  //     rows: { appendable: false },
  //     columns: [
  //       { type: 'gutter', gutterName: 'sequence' },
  //       { type: 'gutter', gutterName: 'row-selector', multiple: true },
  //       {
  //         type: 'string',
  //         name: 'cartonId',
  //         header: i18next.t('field.carton_id'),
  //         width: 150
  //       },
  //       {
  //         type: 'string',
  //         name: 'sku',
  //         header: i18next.t('field.sku'),
  //         width: 150
  //       },
  //       {
  //         type: 'string',
  //         name: 'name',
  //         header: i18next.t('field.product'),
  //         width: 150
  //       },
  //       {
  //         type: 'string',
  //         name: 'location',
  //         header: i18next.t('field.storage_location'),
  //         width: 150
  //       },
  //       {
  //         type: 'integer',
  //         name: 'transferQty',
  //         header: i18next.t('field.transfer_qty'),
  //         width: 150
  //       },
  //       {
  //         type: 'string',
  //         name: 'status',
  //         header: i18next.t('field.status'),
  //         width: 150
  //       }
  //     ]
  //   }
  // }

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

  get wsdGrist() {
    return this.shadowRoot.querySelector('data-grist#wsd-grist')
  }

  async fetchWorksheet() {
    if (!this._worksheetNo) return
    const response = await client.query({
      query: gql`
        query worksheet($name: String!) {
          worksheet(name: $name) {
            type
            status
            assignee {
              id
              name
            }
            replenishment {
              id
              name
            }
            worksheetDetails {
              targetInventory {
                status
                releaseQty
                releaseUomValue
                product {
                  id
                  name
                  description
                  sku
                }
                inventory {
                  id
                  cartonId
                  location {
                    name
                  }
                }
              }
              status
            }
          }
        }
      `,
      variables: {
        name: this._worksheetNo
      }
    })

    if (!response.errors) {
      const worksheet = response.data.worksheet
      const worksheetDetails = worksheet.worksheetDetails
      this._worksheetStatus = worksheet.status
      this._orderNo = worksheet?.replenishment?.name || ''
      this._worksheetType = worksheet.type

      this._fillupForm({
        ...worksheet,
        replenishment: worksheet.replenishment.name
      })

      this.worksheetDetailData = {
        records: worksheetDetails.map(worksheetDetail => {
          return {
            ...worksheetDetail.targetInventory.inventory,
            sku: worksheetDetail.targetInventory.product.sku,
            name: worksheetDetail.targetInventory.product.name,
            status: worksheetDetail.status,
            transferQty: worksheetDetail.targetInventory.releaseQty,
            location: worksheetDetail.targetInventory.inventory.location
          }
        })
      }
    }
  }

  _fillupForm(data) {
    for (let key in data) {
      Array.from(this.form.querySelectorAll('input, select, textarea')).forEach(field => {
        if (field.name === key && field.type === 'checkbox') {
          field.checked = data[key]
        } else if (field.name === key) {
          if (data[key] instanceof Object) {
            const objectData = data[key]
            field.value = `${objectData.name} ${objectData.description ? `(${objectData.description})` : ''}`
          } else {
            field.value = data[key]
          }
        }
      })
    }
  }

  async _activateWorksheet() {
    try {
      const result = await CustomAlert({
        title: i18next.t('title.are_you_sure'),
        text: i18next.t('text.activate_picking_replenishment_worksheet'),
        confirmButton: { text: i18next.t('button.confirm') },
        cancelButton: { text: i18next.t('button.cancel') }
      })

      if (!result.value) {
        return
      }

      const response = await client.mutate({
        mutation: gql`
          mutation activatePickingReplenishment($worksheetNo: String!) {
            activatePickingReplenishment(worksheetNo: $worksheetNo) {
              name
            }
          }
        `,
        variables: {
          worksheetNo: this._worksheetNo
        }
      })
      if (!response.errors) {
        this._showToast({ message: i18next.t('text.worksheet_activated') })
        await this.fetchWorksheet()
        this.updateContext()
        navigate(`replenishment_worksheet_list`)
      }
    } catch (e) {
      this._showToast(e)
    }
  }

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

window.customElements.define('worksheet-replenishment', WorksheetReplenishment)
