import '@things-factory/barcode-ui'
import '@things-factory/grist-ui'
import { css, html } from 'lit-element'
import { MultiColumnFormStyles, SingleColumnFormStyles } from '@things-factory/form-ui'
import { i18next } from '@things-factory/i18n-base'
import { isMobileDevice } from '@things-factory/utils'
import { PickingExecutionBase } from './picking-execution-base'
import '../../components/list-view/product-list-view'

export class PickingExecution extends PickingExecutionBase {
  static get styles() {
    return [
      MultiColumnFormStyles,
      SingleColumnFormStyles,
      css`
        :host {
          display: flex;
          flex-direction: column;
          overflow: hidden;
          padding: 0;
          flex: 1;
        }
        // data-grist {
        //   overflow: auto;
        //   flex: 1;
        // }
        h2 {
          padding: var(--subtitle-padding);
          font: var(--subtitle-font);
          color: var(--subtitle-text-color);
          border-bottom: var(--subtitle-border-bottom);
        }
        legend mwc-icon {
          vertical-align: middle;
          margin: var(--grist-title-icon-margin);
          font-size: var(--grist-title-icon-size);
          color: var(--grist-title-icon-color);
          cursor: pointer;
        }
        .flex-col {
          display: flex;
          flex-direction: column;
        }
        .flex-row {
          display: flex;
          flex-direction: row;
        }
        .flex-50 {
          flex: 50%;
        }
        .mt-5px {
          margin-top: 5px;
        }
        .font-bold {
          font-weight: bold !important;
        }
        .text-14 {
          font-size: 14px !important;
          line-height: 1.5 !important;
        }
        .text-center {
          display: flex;
          align-items: center;
        }
        @media screen and (max-width: 460px) {
          .single-column-form {
            max-width: 100%;
            grid-gap: 5px;
          }
        }
        .scanning-form > * {
          grid-column: span 12;
          padding: 0 10px;
        }
        /* Set icon size */
        mwc-icon {
          font-size: 24px;
        }
        .issue-btn,
        .back-btn {
          background-color: #3a8eab;
          color: #f3f2f7;
          border: none;
          padding: 5px 10px;
          border-radius: 3px;
          cursor: pointer;
        }
        .issue-btn:hover,
        .back-btn:hover {
          background-color: #357d92;
        }
        .tabs {
          display: flex;
          justify-content: space-between;
        }
        .tab-info {
          display: flex;
          justify-content: space-between;
          color: #f3f2f7;
          background-color: #007e7f;
          padding: 10px;
        }
        .tab-button {
          flex: 1;
          padding: 10px;
          background-color: #d2d1d6;
          color: #007e7f;
          border: none;
          cursor: pointer;
          text-align: center;
          border-radius: 10px 10px 0 0;
          font-weight: bold;
        }
        .tab-button.active {
          color: #f3f2f7;
          background-color: #007e7f; /* Darker shade for active tab */
        }
        .tab-content {
          display: none; /* Hide all tab content by default */
        }
        .tab-content.active {
          display: block; /* Show active tab content */
          flex: 1;
          overflow-y: auto;
        }
        .worksheet-name {
          display: -webkit-box;
          -webkit-line-clamp: 1;
          -webkit-box-orient: vertical;
          overflow: hidden;
        }
        .worksheet-info {
          border: none;
          background: none;
          display: flex; /* Use flexbox */
          justify-content: space-between; /* Space between items */
          align-items: center; /* Center items vertically */
          padding: 0 12px 8px; /* Optional: Add some padding */
        }
        .bin-info {
          border: none;
          background: none;
          color: #f3f2f7;
        }
        .picking-banner {
          background-color: #fff3cd;
          border: 1px solid #ffc107;
          border-radius: 4px;
          padding: 12px 16px;
          margin: 10px;
          display: flex;
          justify-content: space-between;
          align-items: center;
          color: #856404;
        }
        .picking-banner button {
          background-color: #007e7f;
          color: white;
          border: none;
          padding: 6px 12px;
          border-radius: 4px;
          cursor: pointer;
          font-weight: bold;
        }
        .picking-banner button:hover {
          background-color: #005f60;
        }
      `
    ]
  }

  get pickingListItemConfig() {
    return {
      columnLeft: {
        size: 8,
        fields: [
          {
            type: 'row',
            content: [
              {
                header: 'Product Name',
                field: 'product.name',
                type: 'string',
                style: '-webkit-line-clamp: 2;'
              },
              { header: 'SKU', field: 'product.sku', type: 'string' }
            ]
          },
          {
            type: 'row',
            content: [
              { header: 'Packing Type', field: 'packingType', type: 'string' },
              ...(this._displayConversion ? [{ header: 'Pack Conversion', field: 'conversion', type: 'string' }] : [])
            ]
          },
          {
            type: 'row',
            content: [
              { header: 'Exp Date', field: 'expirationDate', type: 'string' },
              { header: 'Batch No', field: 'batchId', type: 'string' }
            ]
          },
          {
            type: 'row',
            content: [
              { header: 'Lot ID', field: 'palletId', type: 'string' },
              { header: 'Carton ID', field: 'cartonId', type: 'string' }
            ]
          }
        ]
      },
      columnRight: {
        size: 4,
        fields: [
          {
            type: 'row',
            content: [{ header: 'Location', field: 'location.name', type: 'string', style: '-webkit-line-clamp: 2;' }]
          },
          {
            type: 'valueBox',
            content: { header: 'Picked Qty', field: 'pickedQty', field2: 'releaseQty', type: 'string' }
          },
          {
            type: 'actionBox',
            content: [
              {
                header: 'Issue',
                callback: rowData => {
                  this.openReportIssuePopup(rowData['palletId'])
                }
              }
            ]
          }
        ]
      }
    }
  }

  /**
   * Determines if the "Go to PICKED" banner should be shown.
   * Banner appears when:
   * - Current tab is PICKING
   * - PICKING tab has no items (pickingData.length === 0) - uses SAME source as Total SKU
   * - PICKED tab has items (pickedData.length > 0)
   *
   * Uses the same data source as Total SKU display to ensure consistency.
   */
  _shouldShowPickingBanner() {
    // Banner only shows on PICKING tab
    if (this.state?.activeTab !== 'PICKING') {
      return false
    }

    // Use the SAME source as Total SKU display: this.pickingData?.length
    const pickingItemCount = this.pickingData?.length || 0
    const pickedItemCount = this.pickedData?.length || 0

    // Show banner when PICKING is empty but PICKED has items
    const shouldShow = pickingItemCount === 0 && pickedItemCount > 0

    // Console assert: catch mismatch if Total SKU > 0 but banner shows
    if (shouldShow && pickingItemCount > 0) {
      console.error('BANNER MISMATCH: Banner showing but Total SKU > 0', {
        pickingItemCount,
        pickedItemCount,
        pickingDataLength: this.pickingData?.length,
        pickedDataLength: this.pickedData?.length
      })
    }

    return shouldShow
  }

  get pickedListItemConfig() {
    return {
      columnLeft: {
        size: 8,
        fields: [
          {
            type: 'row',
            content: [
              {
                header: 'Product Name',
                field: 'product.name',
                type: 'string',
                style: '-webkit-line-clamp: 2;'
              }
            ]
          },
          {
            type: 'row',
            content: [
              { header: 'SKU', field: 'product.sku', type: 'string' },
              { header: 'Packing Type', field: 'packingType', type: 'string' }
            ]
          },
          {
            type: 'row',
            content: [
              { header: 'Exp Date', field: 'expirationDate', type: 'string' },
              { header: 'Batch No', field: 'batchId', type: 'string' }
            ]
          },
          {
            type: 'row',
            content: [
              { header: 'Lot ID', field: 'palletId', type: 'string' },
              { header: 'Carton ID', field: 'cartonId', type: 'string' }
            ]
          }
        ]
      },
      columnRight: {
        size: 4,
        fields: [
          {
            type: 'row',
            content: [{ header: 'Location', field: 'location.name', type: 'string', style: '-webkit-line-clamp: 2;' }]
          },
          {
            type: 'valueBox',
            content: { header: 'Picked Qty', field: 'pickedQty', type: 'string' }
          }
        ]
      }
    }
  }

  render() {
    if (!this.state) this.resetView()

    return html`
      <!-- Header Form Section -->
      <div class="scanning-form ${isMobileDevice() ? 'single-column-form' : 'multi-column-form'}">
        <form>
          <fieldset>
            ${
              this._executionData?.binNo
                ? html`<!-- carton Id scanning -->
                    <label class="font-bold">${i18next.t('label.carton_id')}</label>
                    <barcode-scanable-input
                      name="cartonId"
                      }
                      custom-input
                      @keypress="${e => {
                        this.picking(e)
                      }}"
                    >
                    </barcode-scanable-input>
                    <!-- product barcode scanning -->
                    <label class="font-bold">${i18next.t('label.product_barcode')}</label>
                    <barcode-scanable-input
                      name="productBarcode"
                      }
                      custom-input
                      @keypress="${e => {
                        this.picking(e)
                      }}"
                    >
                    </barcode-scanable-input>
                    <!-- quantity scanning -->
                    <label class="font-bold">${i18next.t('label.quantity')}</label>
                    <barcode-scanable-input
                      name="quantity"
                      }
                      custom-input
                      @keypress="${e => {
                        this.picking(e)
                      }}"
                    >
                    </barcode-scanable-input>`
                : html`<label class="font-bold">${i18next.t('label.bin_location')}</label>
                    <barcode-scanable-input
                      name="binNo"
                      }
                      custom-input
                      @keypress="${e => {
                        this.binNoScanHandler(e)
                      }}"
                    >
                    </barcode-scanable-input>`
            }
          </fieldset>
        </form>
      </div>
      <!-- Header Form Section End -->

      <button
        class="worksheet-info text-center"
        @click=${e => {
          this.showWorksheetInfo(this.data)
        }}
      >
        <label class="text-14 font-bold worksheet-name">Worksheet No.: ${this.data?.worksheetInfo.name}</label>
        <mwc-icon style="color:#007E7F;">info</mwc-icon>
      </button>

      <div class="tabs">
        <button
          class="font-bold tab-button ${this.state?.activeTab == 'PICKING' ? 'active' : ''}"
          @click=${e => {
            this.openTab(e, 'PICKING')
          }}
        >
          Picking
        </button>
        <button
          class="font-bold tab-button ${this.state?.activeTab == 'PICKED' ? 'active' : ''}"
          @click=${e => {
            this.openTab(e, 'PICKED')
          }}
        >
          Picked
        </button>
      </div>
      <!-- Tab Info Section -->
      <div class="tab-info">
        <div class="text-center">
          <label class="text-14 font-bold">Total SKU: ${this._getTotalSku()}</label>
        </div>
        <button
          class="text-center bin-info"
          @click="${e => {
            this.changeBinNoPopup(e)
          }}"
        >
          <label class="text-14 font-bold">BIN: ${this._executionData?.binNo}</label>
          <mwc-icon style="margin-left:4px;">qr_code_scanner</mwc-icon>
        </button>
      </div>
      <!-- Tab Info Section End -->

      ${
        this._shouldShowPickingBanner()
          ? html`
              <div class="picking-banner">
                <span
                  >${i18next.t('text.all_items_picked_proceed_to_picked', {
                    defaultValue: 'All items picked. Proceed to PICKED to complete picking.'
                  })}</span
                >
                <button @click=${async e => await this.openTab(e, 'PICKED')}>
                  ${i18next.t('button.go_to_picked', { defaultValue: 'Go to PICKED' })}
                </button>
              </div>
            `
          : ''
      }

      <!-- Picking Item Section -->
      <div id="picking" class="tab-content ${this.state?.activeTab == 'PICKING' ? 'active' : ''}">
        <product-list-view .config=${this.pickingListItemConfig} .data=${this.pickingData}
        ></product-list-view>
      </div>
      <!-- Picking Item Section End -->

      <!-- Picked Item Section -->
      <div id="picked" class="tab-content ${this.state?.activeTab == 'PICKED' ? 'active' : ''}">
        <product-list-view .config=${this.pickedListItemConfig} .data=${this.pickedData}></product-list-view>
      </div>
      <!-- Picked Item Section End -->
    </div>
    `
  }
}

customElements.define('picking-execution', PickingExecution)
