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 LoadByQty extends localize(i18next)(LitElement) {
  static get properties() {
    return {
      _data: Object,
      _executionData: Object
    }
  }

  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;
        }
      `
    ]
  }

  get loadByQtyConfig() {
    return {
      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' }] }
        ]
      },
      columnRight: {
        size: 4,
        fields: [
          {
            type: 'editableValueBox',
            content: { header: 'Load Quantity', field: 'sortedQty', type: 'string' }
          }
        ]
      }
    }
  }

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

  render() {
    return html`
      <!-- Content Section -->
      <div class="content">
        <product-list-view .config=${this.loadByQtyConfig} .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_loading'),
        confirmButton: { text: i18next.t('button.confirm') },
        cancelButton: { text: i18next.t('button.cancel') }
      })

      if (result.value) {
        const updatedData = this.dirtyData.map(data => {
          const qty = parseFloat(data.sortedQty)
          if (isNaN(qty) || qty < 0) {
            throw new Error(`Invalid quantity for product ${data.productName}. Quantity must be a number greater than 0.`)
          }

          const isInventoryDecimal = data.relatedOrderInv?.product?.isInventoryDecimal === true
          if (!isInventoryDecimal && !Number.isInteger(qty)) {
            const sku = data.relatedOrderInv?.product?.sku || data.productSku || data.productName
            throw new Error(
              i18next.t('text.decimal_not_allowed_for_product', { sku }) ||
                `Decimal quantity is not allowed for product ${sku}`
            )
          }

          return {
            ...data,
            loadedQty: qty
          }
        })

        let patch = {
          releaseGoodNo: this._executionData.releaseGoodNo,
          orderInventories: updatedData,
          vehicleNo: this._executionData?.vehicleNo,
          ownCollection: this._executionData?.ownCollection,
          palletQty: this._executionData?.totalPalletQty
        }

        const response = await client.mutate({
          mutation: gql`
            mutation loadByQty($worksheetDetailPatch: LoadingWorksheetDetails) {
              loadByQty(worksheetDetailPatch: $worksheetDetailPatch)
            }
          `,
          variables: {
            worksheetDetailPatch: patch
          }
        })

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

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

window.customElements.define('load-by-qty', LoadByQty)