import { css, html, LitElement } from 'lit-element'
import { connect } from 'pwa-helpers/connect-mixin'

import { MultiColumnFormStyles } from '@things-factory/form-ui'
import { i18next, localize } from '@things-factory/i18n-base'
import { store } from '@things-factory/shell'
import { CONDITION_OF_GOODS } from '../constants'

class UnloadingWorksheetInformationPopup extends connect(store)(localize(i18next)(LitElement)) {
  static get properties() {
    return {
      worksheetInformation: Object,
      unloadedInventories: Array,
      orderProductData: Array
    }
  }

  static get styles() {
    return [
      MultiColumnFormStyles,
      css`
        :host {
          padding: 0 10px 10px 10px;
          display: flex;
          flex-direction: column;
          overflow-x: overlay;
          background-color: var(--main-section-background-color);
        }

        .info-section {
          border-bottom: 1px solid #017E7F;
          padding-bottom: 8px;
        }

        .info-row {
          display: flex;
          flex-direction: row;
          align-items: center;
          padding: 2px 0;
        }

        .info-row:last-child {
          border-bottom: none;
        }

        .info-label {
          font-weight: bold;
          min-width: 150px;
          color: #3a5877;
          text-transform: capitalize;
          font-size: 16px;
        }

        .info-value {
          flex: 1;
          color: #3a5877;
          font-size: 16px;
        }

        .issues-section {
          margin-top: 10px;
        }

        .issues-header {
          font-weight: bold;
          font-size: 22px;
          color: #3a5877;
          margin-bottom: 10px;
        }

        .issue-item {
          padding: 8px 0;
          border-bottom: 1px solid #D9D9D9;
        }

        .issue-field {
          display: flex;
          flex-direction: row;
          margin-bottom: 4px;
        }

        .issue-field-label {
          font-weight: bold;
          min-width: 120px;
          color: #3a5877;
          issue-field-labe
        }

        .issue-field-value {
          flex: 1;
          color: #3a5877;
          issue-field-labe
        }

        .issue-field.sku-field .issue-field-label,
        .issue-field.sku-field .issue-field-value {
          color: #007E7F;
        }
      `
    ]
  }

  firstUpdated() {
    if (this.worksheetInformation) {
      this._processData(this.worksheetInformation)
    }
  }

  updated(changedProperties) {
    if (changedProperties.has('worksheetInformation') && this.worksheetInformation) {
      this._processData(this.worksheetInformation)
    }
  }

  _processData(data) {
    this._processedData = {}
    
    for (let key in data) {
      const value = data[key]
      
      if (key === 'startedAt' && value) {
        const datetime = Number(value)
        const timezoneOffset = new Date(datetime).getTimezoneOffset() * 60000
        const localDate = new Date(datetime - timezoneOffset)
        
        // Format as DD/MM/YYYY, HH:MM:SS AM/PM
        const day = String(localDate.getDate()).padStart(2, '0')
        const month = String(localDate.getMonth() + 1).padStart(2, '0')
        const year = localDate.getFullYear()
        const hours = localDate.getHours()
        const minutes = String(localDate.getMinutes()).padStart(2, '0')
        const seconds = String(localDate.getSeconds()).padStart(2, '0')
        
        const ampm = hours >= 12 ? 'PM' : 'AM'
        const displayHours = hours % 12 || 12
        
        this._processedData[key] = `${day}/${month}/${year}, ${displayHours}:${minutes}:${seconds} ${ampm}`
      } else if (value instanceof Object && !Array.isArray(value)) {
        const objectData = value
        this._processedData[key] = `${objectData.name || ''} ${objectData.description ? `(${objectData.description})` : ''}`.trim()
      } else {
        this._processedData[key] = value
      }
    }
    
    this.requestUpdate()
  }

  _getValue(key) {
    if (!this._processedData) return ''
    return this._processedData[key] || ''
  }

  _getIssues() {
    if (!this.unloadedInventories || !Array.isArray(this.unloadedInventories)) {
      return []
    }

    const orderProductMap = new Map()
    if (this.orderProductData && Array.isArray(this.orderProductData)) {
      this.orderProductData.forEach(op => {
        const key = `${op.sku || ''}_${op.batchId || ''}_${op.packingType || ''}_${op.packingSize || ''}`
        orderProductMap.set(key, op)
      })
    }
    console.log("orderProductMap: ", orderProductMap)

    const badInventories = this.unloadedInventories.filter(
      inventory => inventory.conditionOfGoods && inventory.conditionOfGoods !== CONDITION_OF_GOODS.GOOD.value
    )
    console.log("badInventories: ", badInventories)

    const issueMap = new Map()
    
    badInventories.forEach(inventory => {
      const sku = inventory.product?.sku || ''
      const conditionType = inventory.conditionOfGoods

      if (sku && conditionType) {
        const orderProductKey = `${sku}_${inventory.batchId || ''}_${inventory.packingType || ''}_${inventory.packingSize || ''}`
        const key = `${orderProductKey}_${conditionType}`

        if (!issueMap.has(key)) {
          const matchingOrderProduct = orderProductMap.get(orderProductKey)
          const issue = matchingOrderProduct?.issue || ''

          issueMap.set(key, {
            sku: sku,
            productName: inventory.product?.name || '',
            conditionOfGoods: conditionType,
            issue: issue
          })
        }
      }
    })

    console.log(issueMap.values())

    return Array.from(issueMap.values())
  }

  _formatConditionType(conditionValue) {
    if (!conditionValue) return '-'
    
    const conditionKey = Object.keys(CONDITION_OF_GOODS).find(
      key => CONDITION_OF_GOODS[key].value === conditionValue
    )
    
    if (conditionKey) {
      return i18next.t(`label.${CONDITION_OF_GOODS[conditionKey].name}`)
    }
    
    return conditionValue
  }

  render() {
    const issues = this._getIssues()
    const uniqueSkuCount = issues.length
    return html`
      <div class="info-section">
        <div class="info-row">
          <div class="info-label">${i18next.t('label.company')}</div>
          <div class="info-value">${this._getValue('bizplaceName')}</div>
        </div>
        <div class="info-row">
          <div class="info-label">${i18next.t('label.container_no')}</div>
          <div class="info-value">${this._getValue('containerNo')}</div>
        </div>
        <div class="info-row">
          <div class="info-label">${i18next.t('label.ref_no')}</div>
          <div class="info-value">${this._getValue('refNo')}</div>
        </div>
        <div class="info-row">
          <div class="info-label">${i18next.t('label.ref_no_2')}</div>
          <div class="info-value">${this._getValue('refNo2')}</div>
        </div>
        <div class="info-row">
          <div class="info-label">${i18next.t('label.ref_no_3')}</div>
          <div class="info-value">${this._getValue('refNo3')}</div>
        </div>
        <div class="info-row">
          <div class="info-label">${i18next.t('label.shipping_provider')}</div>
          <div class="info-value">${this._getValue('shippingProvider')}</div>
        </div>
        <div class="info-row">
          <div class="info-label">${i18next.t('label.tracking_no')}</div>
          <div class="info-value">${this._getValue('trackingNo')}</div>
        </div>
        <div class="info-row">
          <div class="info-label">${i18next.t('label.status')}</div>
          <div class="info-value">${this._getValue('marketplaceStatus')}</div>
        </div>
        <div class="info-row">
          <div class="info-label">${i18next.t('label.staging_area')}</div>
          <div class="info-value">${this._getValue('bufferLocation')}</div>
        </div>
        <div class="info-row">
          <div class="info-label">${i18next.t('label.started_at')}</div>
          <div class="info-value">${this._getValue('startedAt')}</div>
        </div>
        <div class="info-row">
          <div class="info-label">${i18next.t('label.reusable_pallet_id')}</div>
          <div class="info-value">${this._getValue('plasticPallet')}</div>
        </div>
      </div>

      ${uniqueSkuCount > 0
        ? html`
            <div class="issues-section">
              <div class="issues-header">Total Issues: ${uniqueSkuCount}</div>
              ${issues.map(issue => html`
                <div class="issue-item">
                  <div class="issue-field sku-field">
                    <div class="issue-field-label">SKU No.</div>
                    <div class="issue-field-value">${issue.sku || '-'}</div>
                  </div>
                  <div class="issue-field">
                    <div class="issue-field-label">Product Name</div>
                    <div class="issue-field-value">${issue.productName || '-'}</div>
                  </div>
                  <div class="issue-field">
                    <div class="issue-field-label">Type of issue</div>
                    <div class="issue-field-value">${this._formatConditionType(issue.conditionOfGoods)}</div>
                  </div>
                  <div class="issue-field">
                    <div class="issue-field-label">Details</div>
                    <div class="issue-field-value">${issue.issue || '-'}</div>
                  </div>
                </div>
              `)}
            </div>
          `
        : html``}
    `
  }
}

window.customElements.define('unloading-worksheet-information-popup', UnloadingWorksheetInformationPopup)

