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

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

import { GhostPrint } from '@operato/ghost-print'
import { SingleColumnFormStyles } from '@things-factory/form-ui'
import { i18next, localize } from '@things-factory/i18n-base'
import { client } from '@things-factory/shell'
import { ScrollbarStyles } from '@things-factory/styles'

class PrintAirwayBillPopup extends localize(i18next)(LitElement) {
  static get properties() {
    return {
      releaseGoodId: String,
      bizplaceId: String,
      _orderPackages: Array
    }
  }

  static get styles() {
    return [
      SingleColumnFormStyles,
      ScrollbarStyles,
      css`
        :host {
          display: flex;
          flex-direction: column;
          overflow: hidden;
          background-color: white;
          max-width: var(--content-container-max-width);
          padding: var(--padding-default) var(--padding-wide);
        }
        .label-container {
          padding: var(--search-form-box-padding);
        }
        .grid-container {
          position: relative;
          display: grid;
          grid-template-columns: repeat(3, 1fr);
          grid-auto-rows: minmax(24px, auto);
          grid-gap: var(--form-grid-gap);
          grid-auto-rows: minmax(24px, auto);
          padding: var(--search-form-box-padding);
          overflow: scroll;
        }
        .grid-container label {
          grid-column: span 2 / auto;
          text-align: left;
          align-self: center;
        }
        .grid-container mwc-button {
          grid-column: span 1 / auto;
          text-align: right;
          align-self: center;
        }
      `
    ]
  }

  render() {
    return html`
      <div class="grid-container">
        <label>${i18next.t('title.tracking_number')}</label>
        ${this._orderPackages?.length
          ? this._orderPackages.map((op, idx) => {
              return html`
                <label>${op.trackingNo}</label>
                <mwc-button
                  label="${`${i18next.t('button.preview')}`}"
                  @click="${e => this.printDocument(op)}"
                  raised
                ></mwc-button>
              `
            })
          : ''}
      </div>
    `
  }

  async firstUpdated() {
    await this.fetchOrderPackages()
  }

  async printDocument(record) {
    if (record.airwayBill) {
      let convertedPdfUrl = ''
      if (record.airwayBill.includes('partner.shopeemobile.com')) {
        convertedPdfUrl = `/pdf/merge?urls=${record.airwayBill}`
      } else {
        let url = new URL(window.location)
        convertedPdfUrl = `${url.origin}/proxy?url=${record.airwayBill}`
      }
      this._callPrintDialog(convertedPdfUrl, true)
    } else {
      this._showToast({ message: i18next.t('text.there_is_no_airway_bill_for_this_ro') })
    }
  }

  async fetchOrderPackages() {
    const filters = [
      { name: 'releaseGoodId', operator: 'eq', value: this.releaseGoodId },
      { name: 'bizplaceId', operator: 'eq', value: this.bizplaceId }
    ]

    const response = await client.query({
      query: gql`
        query orderPackages($filters: [Filter!]!) {
          orderPackages(filters: $filters) {
            items {
              id
              name
              packageId
              trackingNo
              airwayBill
              invoice
            }
            total
          }
        }
      `,
      variables: { filters }
    })
    if (!response.errors) {
      this._orderPackages = response.data.orderPackages.items || []
    }
  }

  async _callPrintDialog(contentSource, isSellerCraft = false) {
    if (isSellerCraft) {
      GhostPrint.print({
        src: contentSource,
        onfinish: () => {
          this._showToast({ message: i18next.t('text.document_has_been_generated') })
        }
      })
    } else {
      GhostPrint.print({
        srcdoc: contentSource,
        onfinish: () => {
          this._showToast({ message: i18next.t('text.document_has_been_generated') })
        }
      })
    }
  }

  _showToast({ type, message }) {
    document.dispatchEvent(
      new CustomEvent('notify', {
        detail: {
          type,
          message
        }
      })
    )
  }
}
window.customElements.define('print-airway-bill-popup', PrintAirwayBillPopup)
