import '@things-factory/grist-ui'

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

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

class GenerateManifestPopup extends localize(i18next)(LitElement) {
  static get styles() {
    return [
      ScrollbarStyles,
      css`
        :host {
          display: flex;
          flex-direction: column;
          overflow: hidden;
          background-color: white;
          width: 300px;
          height: 200px;
        }

        #courier {
          width: 150px;
          height: 30px;
        }

        .container {
          display: flex;
          justify-content: center;
          align-items: center;
        }

        .select-courier {
          margin-top: 13px;
        }

        .button-container {
          position: absolute;
          left: 50%;
          transform: translateX(-50%);
          display: flex;
          justify-content: center;
          align-items: center;
          margin-top: 120px;
        }

        .button-container input {
          margin: 0 5px;
        }

        .button-container input[class='cancel'] {
          background-color: white;
          color: red;
          padding: 10px 20px;
          border: 2px solid red;
          border-radius: 5px;
          cursor: pointer;
          font-weight: bold;
          padding: 8px 15px;
          margin-right: 10px;
        }

        .button-container input[class='confirm'] {
          background-color: #117e7f;
          color: white;
          padding: 10px 20px;
          border: 1px solid white;
          border-radius: 5px;
          cursor: pointer;
          font-weight: bold;
          display: flex;
          justify-content: center;
          align-items: center;
        }
      `
    ]
  }

  static get properties() {
    return {
      shippingData: Object,
      isManifestNew: Boolean
    }
  }

  render() {
    return html` <div class="container">
      <div class="select-courier">
        <label for="courier-name">Courier:</label>
        <select id="courier" name="courierSelector"></select>
      </div>
      <div class="button-container">
        <input type="button" value="Confirm" class="confirm" @click=${() => this._createLoadingManifest()} />
        <input type="button" value="Cancel" class="cancel" @click=${this.closePopup} />
      </div>
    </div>`
  }

  closePopup() {
    history.back()
  }

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

  async handleCourierChange() {
    try {
      const response = await client.query({
        query: gql`
          query fetchTransport {
            fetchTransport
          }
        `
      })

      const couriers = response.data.fetchTransport

      this.courierSelector.innerHTML = ''

      // Create new options based on fetched data
      couriers.forEach(courier => {
        const option = document.createElement('option')
        option.value = courier
        option.textContent = courier
        this.courierSelector.appendChild(option)
      })
    } catch (e) {
      this._showToast(e)
    }
  }

  async _createLoadingManifest() {
    try {
      const selectedCourier = this.shadowRoot.getElementById('courier').value
      let manifestSelect = this.isManifestNew

      let manifest = {
        transporter: selectedCourier == 'EFMX' ? 'EMS' : selectedCourier
      }

      const response = await client.mutate({
        mutation: gql`
          mutation generateManifest($manifest: NewManifest!) {
            generateManifest(manifest: $manifest) {
              id
              name
              shippingProvider
            }
          }
        `,
        variables: { manifest }
      })

      if (!response.errors) {
        let generatedManifest = response.data.generateManifest
        generatedManifest = {
          ...generatedManifest,
          shippingProvider: generatedManifest.shippingProvider == 'EMS' ? 'EFMX' : generatedManifest.shippingProvider
        }
        this._showToast({ message: i18next.t('text.manifest_has_been_generated') })
        this.dispatchEvent(
          new CustomEvent('manifestGenerated', { detail: { generatedManifest }, bubbles: true, composed: true })
        )
      }
      if (manifestSelect) {
        history.go(-2)
      } else {
        history.back()
      }
    } catch (e) {
      this._showToast(e)
    }
  }

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

  async connectedCallback() {
    super.connectedCallback()
    // Call the fetch function when the component is connected to the DOM
    await this.handleCourierChange()
  }
}

window.customElements.define('generate-manifest-popup', GenerateManifestPopup)
