import gql from 'graphql-tag'

import { html, css, LitElement } from 'lit-element'
import { client, 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 LoadingPackageInfoPopup extends localize(i18next)(LitElement) {
  static get properties() {
    return {
      _data: Array,
      _packageName: String,
      _packageId: String,
      _packageNumber: Number
    }
  }

  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;
        }
        .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 packageItemsConfig() {
    return {
      selectable: false,
      columnLeft: {
        size: 8,
        fields: [
          {
            type: 'row',
            content: [
              {
                header: 'SKU No.',
                field: 'sku',
                type: 'string'
              }
            ]
          },
          {
            type: 'row',
            content: [
              {
                header: 'Product Name',
                field: 'productName',
                type: 'string',
                style: '-webkit-line-clamp: 2;'
              }
            ]
          },
          {
            type: 'row',
            content: [
              {
                header: 'Packing Type',
                field: 'packingType',
                type: 'string'
              }
            ]
          }
        ]
      },
      columnRight: {
        size: 4,
        fields: [
          {
            type: 'valueBox',
            content: {
              header: 'Qty:',
              field: 'qty',
              type: 'number'
            }
          }
        ]
      }
    }
  }

  render() {
    return html`
      <!-- Content Section -->
      <label class="text-14 font-bold order-no">${i18next.t('field.packing_label_no')}: ${this._packageNumber}</label>
      <div class="tab-info text-center">
        <label class="text-14 font-bold">${i18next.t('label.total_sku')}: ${this._getTotalItems()}</label>
      </div>
      <div class="content">
        <product-list-view .config=${this.packageItemsConfig} .data=${this._data}></product-list-view>
      </div>
      <div class="button-container">
        <mwc-button raised @click=${e => this.closePopup(e)}>${i18next.t('button.back')}</mwc-button>
        <mwc-button raised style="--mdc-theme-primary: #CD4946; --mdc-theme-on-primary: white;" @click=${e => this.undo(e)}>${i18next.t('button.undo')}</mwc-button>
      </div>
      <!-- Content Section End -->
    `
  }

  async undo(e) {
    try {
      if (!this._packageId) {
        throw new Error('Package ID is not available')
      }

      const response = await client.mutate({
        mutation: gql`
          mutation undoLoadingPackages($id: String!) {
            undoLoadingPackages(id: $id)
          }
        `,
        variables: { id: this._packageId }
      })

      if (!response.errors) {
        this.dispatchEvent(
          new CustomEvent('undo', {
            detail: { packageId: this._packageId },
            bubbles: true,
            composed: true
          })
        )
        showToast({ type: 'success', message: i18next.t('text.undo_loading_package_success') || 'Loading package undone successfully' })
        setTimeout(() => history.back(), 100)
      } else {
        throw new Error(response.errors[0]?.message || 'Failed to undo loading package')
      }
    } catch (e) {
      showToast({ type: 'error', message: e.message || 'Failed to undo loading package' })
    }
  }

  _getTotalItems() {
    return this._data?.length || 0
  }

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

window.customElements.define('loading-package-info-popup', LoadingPackageInfoPopup)
