import gql from 'graphql-tag'
import { i18next, localize } from '@things-factory/i18n-base'
import { client, CustomAlert } from '@things-factory/shell'
import { css, html, LitElement } from 'lit-element'
import { SingleColumnFormStyles } from '@things-factory/form-ui'
import { showToast } from '../../../util'

const ISSUE_TYPES = {
  MISSING: 'MISSING',
  EXPIRED: 'EXPIRED'
}

class ReportIssuePopup extends localize(i18next)(LitElement) {
  static get properties() {
    return {
      _palletId: String
    }
  }

  static get styles() {
    return [
      SingleColumnFormStyles,
      css`
        :host {
          display: flex;
          flex-direction: column;
          overflow: hidden;
          background-color: var(--main-section-background-color);
        }
        .container {
          display: flex;
          flex-direction: column;
        }
        .single-column-form select,
        .single-column-form textarea,
        .single-column-form label {
          grid-column: span 12;
        }
        .button-container {
          padding: 20px;
          margin: var(--button-container-margin);
          justify-self: center;
          align-self: center;
        }
        #input-form {
          width: auto;
          grid-gap: 5px;
          margin: 30px;
        }
        .text-left {
          text-align: left !important;
        }
        .mt-5px {
          margin-top: 5px;
        }
      `
    ]
  }

  render() {
    return html`
      <div class="container">
        <form id="input-form" class="single-column-form">
          <fieldset>
            <label class="mt-5px text-left">${i18next.t('label.issue_type')}</label>
            <select name="issue">
              <option value="">${i18next.t('label.select_issue_type')}</option>
              ${Object.entries(ISSUE_TYPES).map(([key, value]) => html`<option value="${value}">${key}</option>`)}
            </select>
            <label class="mt-5px text-left">${i18next.t('label.details')} (Optional)</label>
            <textarea name="details" rows="3"></textarea>
          </fieldset>
        </form>
      </div>
      <div class="button-container">
        <mwc-button
          raised
          @click="${e => {
            this.submit(e)
          }}"
          label="${i18next.t('button.submit')}"
        ></mwc-button>
      </div>
    `
  }

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

  get detailsInput() {
    return this.shadowRoot?.querySelector('textarea[name=details]')
  }

  async submit(e) {
    try {
      if (!this.issueTypeInput.value) throw new Error('Please select an issue type')
      else if (this.issueTypeInput.value == 'OTHER_ISSUE' && !this.detailsInput.value) {
        throw new Error('Details is required for OTHER ISSUE')
      }

      const patch = {
        palletId: this._palletId,
        transactionType: this.issueTypeInput?.value,
        details: this.detailsInput?.value,
        obsolete: this.issueTypeInput.value === ISSUE_TYPES.EXPIRED ? true : false
      }

      const patches = [patch]

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

      if (!result.value) return

      const response = await client.mutate({
        mutation: gql`
          mutation submitInventoryChanges($patches: [InventoryPatch!]!) {
            submitInventoryChanges(patches: $patches)
          }
        `,
        variables: { patches }
      })

      if (!response.error) {
        showToast({ type: 'success', message: 'Issue reported successfully.' })
        this.dispatchEvent(new CustomEvent('submit', { detail: '' }))
      }
    } catch (e) {
      showToast(e)
    }
  }
}

window.customElements.define('report-issue-popup', ReportIssuePopup)
