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 { isMobileDevice } from '@things-factory/utils'

class DraftReleaseGoodCard extends localize(i18next)(LitElement) {
  closeCard() {
    this.dispatchEvent(new CustomEvent('remove-card', { detail: null, bubbles: true, composed: true }))
    this.parentElement.removeChild(this)
  }

  handleInputChange(event) {
    const checkbox = this.shadowRoot.querySelector('input[id="selectDraftOrder"]')
    const radioValue = this.shadowRoot.querySelector('input[name="orderType"]:checked')?.value || ''

    const value = {
      valueInfo: checkbox.value,
      valueRadio: radioValue,
      valueCheckBox: checkbox.checked
    }

    this.dispatchEvent(new CustomEvent('value-change', { detail: value, bubbles: true, composed: true }))
  }

  updated(changedProperties) {
    super.updated(changedProperties)
    if (changedProperties.has('selected') && this.selected) {
      this.handleInputChange()
    }
  }

  static get properties() {
    return {
      config: Object,
      fetchHandler: Object,
      draftInfo: Object,
      draftOrder: Object,
      checkDisable: Object,
      selected: Boolean,
      checkReleaseType: Boolean,
      checkStatus: Boolean,
      checkAvailableQty: Boolean
    }
  }

  static get styles() {
    return [
      css`
        :host {
          display: flex;
          flex-direction: column;
          width: 100%;
        }

        table {
          padding: 18px;
        }

        th,
        td {
          padding-top: 5px;
          padding-bottom: 5px;
          padding-left: 5x;
          padding-right: 5px;
        }

        td {
          text-align: center;
        }

        table,
        th,
        td {
          border: 1px solid black;
        }

        .card {
          width: 1300px;
          margin: auto;
          background-color: rgb(255, 255, 249);
          min-height: 200px;
          position: relative;
          border-radius: 10px;
          border: 2px solid rgb(20, 154, 155);
        }

        #close {
          float: right;
          display: inline-block;
          padding: 2px 5px;
          margin-top: 3px;
          margin-right: 3px;
          background: #696969;
          border-radius: 50%;
          font-size: 8px;
          color: white;
        }

        .topLeft {
          color: rgb(20, 155, 155);
          font-size: 14px;
          display: flex;
          margin-left: 7px;
        }

        .selectOption {
          position: absolute;
          left: 5px;
          top: 30px;
          margin-top: 10px;
        }

        label {
          color: #3a5877;
        }

        .grist {
          margin-top: 13px;
          margin-left: auto;
          margin-right: auto;
          width: 95%;
          height: 125px;
        }

        .border1 {
          border-top: 1px solid black;
          width: 100%;
          margin-top: 10px;
        }

        .center {
          margin-left: auto;
          margin-right: auto;
          margin-top: 40px;
          border-collapse: collapse;
        }

        .button button {
          width: 20px;
          height: 20px;
          border-radius: 50%;
          background-color: #909090;
          color: white;
          border: none;
          outline: none;
          cursor: pointer;
          display: flex;
          justify-content: center;
          align-items: center;
          float: right;
          margin-right: 10px;
          margin-top: 5px;
        }
      `
    ]
  }

  constructor() {
    super()

    this.properties = {
      config: {},
      fetchHandler: () => {},
      draftInfo: {},
      checkStatus: false,
      checkAvailableQty: false
    }
    this.selected = false
  }

  render() {
    return html`
      <div class="card">
        <div class="button">
          <button @click=${() => this.closeCard()} ${this.closeCard}>X</button>
        </div>
        <div class="topLeft">
          <h3>
            <input
              type="checkbox"
              id="selectDraftOrder"
              value="${this.draftInfo.id}"
              .checked=${this.selected ? true : false}
              @change=${(this.selected ? this.handleInputChange : null) || this.handleInputChange}
              ?disabled="${this.draftInfo.status === 'SUBMITTED'}"
            />
            <b> ${this.draftInfo.name} [${this.draftInfo.status}]</b>
          </h3>
        </div>
        <div class="selectOption">
          <input
            type="radio"
            id="releaseOrder"
            name="orderType"
            value="release"
            .checked="${!this.checkStatus}"
            @change=${this.handleInputChange}
            ?hidden=${this.checkStatus}
          />
          <label ?hidden=${this.checkStatus}><b> Release Order </b></label>
          <input
            type="radio"
            id="partialReleaseOrder"
            name="orderType"
            value="partial"
            .checked="${this.draftInfo.source === 'OTHERS' && this.checkStatus && !this.checkAvailableQty}"
            @change=${this.handleInputChange}
            ?hidden="${!(this.draftInfo.source === 'OTHERS' && this.checkStatus)}"
            ?disabled="${this.checkAvailableQty}"
          />
          <label ?hidden="${!(this.draftInfo.source === 'OTHERS' && this.checkStatus)}"
            ><b> Partial Release Order </b></label
          >
        </div>
        <data-grist
          class="grist"
          .mode=${isMobileDevice() ? 'LIST' : 'GRID'}
          .config=${this.config}
          .fetchHandler=${this.draftReleaseGoodInfo.bind(this, this.draftOrder)}
        ></data-grist>
      </div>
    `
  }

  async draftReleaseGoodInfo() {
    const orderItem = this.draftOrder
    const response = await client.query({
      query: gql`
        query draftReleaseGoodByName($id: String) {
          draftReleaseGoodByName(id: $id) {
            id
            name
            type
            status
            bizplace {
              id
              name
              description
            }
            orderProducts {
              id
              name
              product {
                id
                name
                sku
              }
              uomValue
              uom
              releaseQty
              remainQty
              remainUomValue
              groupType
              remainUomValueWithUom
              status
            }
            createdAt
            updatedAt
          }
        }
      `,
      variables: { id: orderItem.id }
    })

    if (!response.errors) {
      const items = response.data.draftReleaseGoodByName

      this.draftOrderStatus = response.data.draftReleaseGoodByName.status
      const records = items.orderProducts.map(itm => {
        return {
          sku: itm.product.sku,
          groupType: itm.groupType,
          releaseQty: itm.releaseQty,
          bizplace: items.bizplace.name,
          availableQty: itm.remainQty,
          status: itm.status
        }
      })

      this.checkStatus = records.some(itm => itm.status === 'INSUFFICIENT')
      this.checkAvailableQty = records.every(itm => itm.availableQty == 0)

      return {
        records
      }
    }
  }
}

window.customElements.define('draft-release-good-card', DraftReleaseGoodCard)
