import { i18next, localize } from '@things-factory/i18n-base'
import { css, html, LitElement } from 'lit-element'
import { flattenObject } from '@things-factory/utils'

class ProductListView extends localize(i18next)(LitElement) {
  static get styles() {
    return [
      css`
        :host {
          --product-item-selected-bg: transparent;
        }
        .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;
        }
        .product-item {
          padding: 8px;
          display: grid;
          grid-template-columns: repeat(12, 1fr);
          grid-gap: 3px;
          color: #3a5877;
          border-bottom: solid 0.5px #3a5877;
          cursor: pointer;
        }
        .product-item[selected] {
          background-color: var(--product-item-selected-bg);
        }
        .product-item-info {
          grid-column: span 8;
          font-size: 12px;
        }
        .product-item-info-title {
          font-weight: bold;
        }
        .product-item-info-details {
          display: -webkit-box;
          -webkit-line-clamp: 1;
          -webkit-box-orient: vertical;
          overflow: hidden;
        }
        .product-item-action {
          grid-column: span 4;
          text-align: center;
          font-size: 14px;
        }

        .qty-box {
          margin: 0 15px;
          border: solid 0.5px #3a5877;
          border-radius: 4px;
          padding: 4px;
          color: #3a5877;
          font-size: 16px;
          font-weight: bold;
        }
        .qty-box > hr {
          margin: 0;
          border: none;
          background-color: #3a5877;
          height: 0.5px;
        }

        .action-box {
          flex-grow: 1;
          align-content: center;
        }

        .btn {
          border: none;
          padding: 5px 10px;
          border-radius: 3px;
          cursor: pointer;
          min-width: 70px;
          height: 35px;
        }

        .btn-issue {
          background-color: #cd4946;
          color: #f3f2f7;
        }

        .btn-success {
          background-color: #007e7f;
          color: #f3f2f7;
        }

        .btn-common {
          background-color: white;
          color: #007e7f;
          border: 1px solid #007e7f;
        }

        .checkbox-wrapper {
          display: flex;
          align-items: center;
          justify-content: center;
          height: 100%;
        }

        .checkbox-wrapper input[type='checkbox'] {
          accent-color: #007e7f;
          width: 16px;
          height: 16px;
          cursor: pointer;
        }

        .select-all-header {
          display: flex;
          align-items: center;
          padding: 8px;
          color: #007e7f;
          font-weight: 700;
          border-bottom: 1px solid #d9d9d9;
        }

        .select-all-header span {
          cursor: pointer;
          margin-left: 4px;
        }

        .select-all-header input[type='checkbox'] {
          accent-color: #007e7f;
          width: 16px;
          height: 16px;
          cursor: pointer;
        }

        .input-field {
          width: 80%;
          height: 80%;
          border: none;
          font-size: 14px;
          color: #3a5877;
          background-color: #f4f7fb;
          text-align: center;
        }
      `
    ]
  }

  static get properties() {
    return {
      data: Object,
      config: Object,
      callback: Object,
      _show: Boolean,
      selectedItems: { type: Array },
      selectAll: { type: Boolean },
      selectedRecordId: { type: String, attribute: false },
      highlightedIds: { type: Array, attribute: false }
    }
  }

  constructor() {
    super()
    this.selectedItems = []
    this.selectAll = false
    this.highlightedIds = []
  }

  render() {
    return html`
      ${this.config?.selectable
        ? html`
            <div class="select-all-header">
              <input type="checkbox" .checked=${this.selectAll} @change=${this._handleSelectAll} />
              <span @click=${this._handleSelectAllClick}>Select All</span>
            </div>
          `
        : ''}
      ${this?.data.map((itm, index) => {
        try {
          itm = flattenObject(itm, '.')

          const isSelected =
            (this.selectedRecordId && itm.id === this.selectedRecordId) ||
            (this.highlightedIds?.length > 0 && this.highlightedIds.includes(itm.id))

          return html`
            <div
              class="product-item"
              ?selected=${isSelected}
              style="grid-template-columns: repeat(${
                this.config.columnLeft.size + this.config.columnRight.size + (this.config?.selectable ? 1 : 0)
              }, 1fr) !important;"
              @click=${e => {
                if (e.target.closest('button') || e.target.closest('input') || e.target.closest('.action-box')) {
                  return
                }
                if (this.highlightedIds?.length > 0) {
                  this.highlightedIds = []
                }
                if (typeof this.config?.onRecordClick === 'function') {
                  this.config.onRecordClick(itm, e, index)
                }
              }}
            >
              ${
                this.config?.selectable
                  ? html`
                      <div class="checkbox-wrapper">
                        <input
                          type="checkbox"
                          .checked=${this.selectedItems.includes(itm.id)}
                          @change=${e => this._handleSelect(e, itm)}
                        />
                      </div>
                    `
                  : ''
              }
              <div class="product-item-info" style="grid-column: span ${this.config.columnLeft.size} !important;">
                ${this.config.columnLeft.fields.map(cfg => {
                  const field = cfg.content
                  const fieldSize = field.length

                  switch (cfg.type) {
                    case 'row':
                      return html`<div class="flex-row">
                        ${field.map(f => {
                          return rowType(fieldSize, f.header, itm[f.field], f.style)
                        })}
                      </div>`
                      break
                    case 'valueBox':
                      return valueBoxType(f.header, itm[f.field], itm[f.field2])
                    default:
                      break
                  }
                })}
              </div>

              <div
                class="flex-col product-item-action"
                style="grid-column: span ${this.config.columnRight.size} !important;"
              >
                ${this.config.columnRight.fields.map(cfg => {
                  const field = cfg.content
                  const fieldSize = field.length

                  switch (cfg.type) {
                    case 'row':
                      return field.map(f => {
                        return rowType(fieldSize, f.header, itm[f.field], f.style)
                      })
                      break
                    case 'valueBox':
                      return valueBoxType(field.header, itm[field.field], itm[field.field2])
                    case 'editableValueBox':
                      const data = itm[field.field]
                      const header = field.header
                      const placeholder = field.placeholder || ''
                      const defaultValue = field.defaultValue !== undefined ? field.defaultValue : 0
                      return html`
                        <div class="flex-col mt-5px">
                          ${header != null || header != undefined ? html` <label class="product-item-info-title">${header}</label> ` : ``}
                          <div class="qty-box">
                            <input
                              class="input-field"
                              placeholder="${placeholder}"
                              .value="${data ? data : defaultValue}"
                              @change=${e => {
                                const val = e.target.value.trim()
                                this._handleValueChange(field.field, val === '' ? null : parseFloat(val), index)
                              }}
                            />
                          </div>
                        </div>`
                    case 'actionBox':
                      return field.map(f => {
                        return actionBoxType(
                          f.header,
                          typeof f.callback === 'function' ? e => f.callback(itm, e) : null, // This captures itm in the closure
                          // f.callback, // Directly pass the callback
                          f?.btnClass,
                          typeof f.condition === 'function' ? () => f.condition(itm) : () => true // This captures itm in the closure
                          // f.condition // Pass the condition directly
                        )
                      })
                    default:
                      break
                  }
                })}
              </div>
            </div>
          </div>
        `
        } catch (e) {
          console.log(e)
          return html``
        }
      })}
    `
  }

  _handleSelectAll(e) {
    this.selectAll = e.target.checked
    if (this.selectAll) {
      this.selectedItems = this.data.map(item => item.id)
    } else {
      this.selectedItems = []
    }
    this.dispatchEvent(
      new CustomEvent('selection-changed', {
        detail: { selectedItems: this.selectedItems }
      })
    )
  }

  _handleSelect(e, item) {
    if (e.target.checked) {
      this.selectedItems = [...this.selectedItems, item.id]
    } else {
      this.selectedItems = this.selectedItems.filter(id => id !== item.id)
    }
    this.selectAll = this.selectedItems.length === this.data.length
    this.dispatchEvent(
      new CustomEvent('selection-changed', {
        detail: { selectedItems: this.selectedItems }
      })
    )
  }

  _handleSelectAllClick(e) {
    this._handleSelectAll({ target: { checked: !this.selectAll } })
  }
  
  _handleValueChange(field, newValue, index) {
    this.data = this.data.map((item, i) => {
      if (i === index) {
        return {
          ...item,
          [field]: newValue
        }
      }
      return item
    })
  }

  scrollToId(id) {
    const dataIndex = (this.data || []).findIndex(item => item.id === id)
    if (dataIndex === -1) return
    this.updateComplete.then(() => {
      const allItems = this.shadowRoot?.querySelectorAll('.product-item')
      allItems?.[dataIndex]?.scrollIntoView({ behavior: 'smooth', block: 'nearest' })
    })
  }
}

window.customElements.define('product-list-view', ProductListView)

function rowType(fieldSize, header, data, style = '') {
  return html`
    <div class="flex-col ${fieldSize > 1 ? 'flex-50' : ''} mt-5px">
      ${header != null || header != undefined ? html` <label class="product-item-info-title">${header}</label> ` : ``}
      <label class="product-item-info-details" style="${style}"> ${data ? data : '-'} </label>
    </div>
  `
}

function valueBoxType(header, data, data2) {
  return html`
    <div class="flex-col mt-5px">
      ${header != null || header != undefined ? html` <label class="product-item-info-title">${header}</label> ` : ``}
      <div class="qty-box">
        <label class="product-item-info-details">${data ? data : 0}</label>
        ${data2 != null || data2 != undefined
          ? html` <hr />
              <label class="product-item-info-details">${data2 ? data2 : 0}</label>`
          : ``}
      </div>
    </div>
  `
}

function actionBoxType(header, callback, btnClass = 'btn-issue', condition = null) {
  // Check if condition is a function and evaluate it
  const showButton = typeof condition === 'function' ? condition() : true // Call the condition function

  // Only render the button if the condition allows
  if (!showButton) {
    return html`` // Don't render if the condition is not met
  }

  return html`
    <div class="action-box mt-5px">
      <button
        class="btn ${btnClass}"
        @click=${e => {
          if (typeof callback === 'function') {
            callback(e) // Pass the event to the callback if it exists
          }
        }}
      >
        ${header}
      </button>
    </div>
  `
}
