import gql from 'graphql-tag'

import { html, css, LitElement } from 'lit-element'
import { PageView, client, store, CustomAlert } from '@things-factory/shell'
import { i18next, localize } from '@things-factory/i18n-base'
import { ScrollbarStyles } from '@things-factory/styles'
import { showToast } from '../../../util'
import '../../components/list-view/product-list-view'

class WarehouseReturnPopup extends localize(i18next)(LitElement) {
  static get properties() {
    return {
      _data: Object,
      _releaseGoodNo: String
    }
  }

  static get styles() {
    return [
      ScrollbarStyles,
      css`
        :host {
          padding: 12px;
          display: flex;
          flex-direction: column;
          overflow: hidden;
          background-color: var(--main-section-background-color);
          position: relative; /* Ensure the host element is positioned */
        }
        .content {
          display: flex;
          flex-direction: column;
          flex: 1;
          overflow: auto;
        }
        .button-container {
          position: absolute;
          bottom: 12px;
          right: 12px;
          display: flex;
          gap: 8px;
        }
        .tab-info {
          display: flex;
          justify-content: space-between;
          color: #f3f2f7;
          background-color: #007e7f;
          padding: 10px;
        }
        .text-center {
          display: flex;
          align-items: center;
        }
        .text-14 {
          font-size: 14px !important;
          line-height: 1.5 !important;
        }
        .font-bold {
          font-weight: bold !important;
        }
      `
    ]
  }

  get returnConfig() {
    return {
      selectable: true,
      columnLeft: {
        size: 8,
        fields: [
          {
            type: 'row',
            content: [
              {
                header: 'Product Name',
                field: 'productName',
                type: 'string',
                style: '-webkit-line-clamp: 2;'
              }
            ]
          },
          { type: 'row', content: [{ header: 'SKU No.', field: 'productSku', type: 'string' }] },
          {
            type: 'row',
            content: [
              { header: 'Exp Date', field: 'expirationDate', type: 'string' },
              { header: 'Batch No.', field: 'relatedOrderInv.batchId', type: 'string' }
            ]
          },
          { type: 'row', content: [{ header: 'Packing Type', field: 'relatedOrderInv.packingType', type: 'string' }] }
        ]
      },
      columnRight: {
        size: 4,
        fields: [
          {
            type: 'row',
            content: [{ header: 'Total Qty.', field: 'sortedQty', type: 'string' }]
          },
          {
            type: 'editableValueBox',
            content: { header: 'Return Qty.', field: 'returnQty', type: 'string' }
          }
        ]
      }
    }
  }

  get dirtyData() {
    return this.shadowRoot.querySelector('product-list-view').data
  }

  get returnData() {
    return this.shadowRoot.querySelector('product-list-view')
  }

  render() {
    return html`
      <!-- Content Section -->
      <div class="tab-info text-center">
        <label class="text-14 font-bold"> Total SKU: ${this._getTotalSku()}</label>
      </div>
      <div class="content">
        <product-list-view .config=${this.returnConfig} .data=${this._data}></product-list-view>
      </div>
      <div class="button-container">
        <mwc-button raised @click=${e => this.confirm(e)}>${i18next.t('button.confirm')}</mwc-button>
        <mwc-button outlined @click=${e => this.closePopup(e)}>${i18next.t('button.back')}</mwc-button>
      </div>
      <!-- Content Section End -->
    `
  }

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

      if (result.value) {
        let updatedData = this.dirtyData.map(data => {
          const qty = Number(data.returnQty)
          if (isNaN(qty) || qty <= 0) {
            throw new Error(
              `Oops! Invalid quantity. Please enter a number greater than 0.`
            )
          }
          return {
            ...data,
            returnQty: data.returnQty
          }
        })

        let returnData = updatedData.filter(data => this.returnData.selectedItems.includes(data.id))

        if (returnData.length < 1) returnData = updatedData

        const response = await client.mutate({
          mutation: gql`
            mutation warehouseReturn($releaseGoodNo: String!, $worksheetDetails: [Object!]) {
              warehouseReturn(releaseGoodNo: $releaseGoodNo, worksheetDetails: $worksheetDetails) {
                id
              }
            }
          `,
          variables: {
            releaseGoodNo: this._releaseGoodNo,
            worksheetDetails: returnData
          }
        })

        if (!response.errors) {
          this.dispatchEvent(new CustomEvent('warehouse-return', { detail: { success: true } }))
          history.back()
        }
      }
    } catch (e) {
      showToast(e)
    }
  }

  _getTotalSku() {
    return this._data.length || 0
  }

  async closePopup(e) {
    history.back()
  }
}

window.customElements.define('warehouse-return-popup', WarehouseReturnPopup)
