import '@things-factory/grist-ui'

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'

class WorksheetInformationPopup extends connect(store)(localize(i18next)(LitElement)) {
  static get properties() {
    return {
      worksheetInformation: Object,
      _expanded: Boolean
    }
  }

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

        .expandable {
          text-overflow: ellipsis;
          overflow: hidden;
          white-space: nowrap;
          cursor: pointer;
        }

        textarea.expandable {
          resize: none;
          white-space: pre-wrap;
          overflow: hidden;
          font-family: inherit;
          font-size: inherit;
          padding: var(--input-padding, 4px);
          border: var(--input-border, 1px solid #ccc);
          border-radius: var(--input-border-radius, 2px);
          background: var(--input-background-color, #fff);
          color: var(--input-color, #333);
          width: 100%;
          box-sizing: border-box;
          cursor: pointer;
        }

      `
    ]
  }

  get infoForm() {
    return this.shadowRoot.querySelector('form#info-form')
  }

  _expandableField(name) {
    const value = this.worksheetInformation?.[name] || ''
    if (this._expanded) {
      return html`<textarea class="expandable" name="${name}" readonly @click="${this._toggleExpand}">${value.replace(/, /g, ',\n')}</textarea>`
    }
    return html`<input class="expandable" name="${name}" .value="${value}" readonly @click="${this._toggleExpand}" />`
  }

  render() {
    return html`
      <form id="info-form" class="multi-column-form">
        <fieldset>
          <label>${i18next.t('label.company')}</label>
          <input name="bizplaceName" readonly />

          <label>${i18next.t('label.container_no')}</label>
          ${this._expandableField('containerNo')}

          <label>${i18next.t('label.ref_no')}</label>
          ${this._expandableField('refNo')}

          <label>${i18next.t('label.ref_no_2')}</label>
          ${this._expandableField('refNo2')}

          <label>${i18next.t('label.ref_no_3')}</label>
          ${this._expandableField('refNo3')}

          <label>${i18next.t('field.rtm')}</label>
          ${this._expandableField('rtm')}

          <label>${i18next.t('label.shipping_provider')}</label>
          ${this._expandableField('shippingProvider')}

          <label>${i18next.t('label.tracking_no')}</label>
          ${this._expandableField('trackingNo')}

          <label>${i18next.t('label.status')}</label>
          ${this._expandableField('marketplaceStatus')}

          <label>${i18next.t('label.staging_area')}</label>
          <input name="bufferLocation" readonly />

          <label>${i18next.t('label.started_at')}</label>
          <input name="startedAt" type="datetime-local" readonly />

          <label>${i18next.t('label.reusable_pallet_id')}</label>
          <input name="plasticPallet" readonly />

          
        </fieldset>
      </form>
    `
  }

  firstUpdated() {
    if (this.worksheetInformation) this._fillUpForm(this.infoForm, this.worksheetInformation)
  }

  _toggleExpand() {
    this._expanded = !this._expanded
  }

  updated(changedProps) {
    if (changedProps.has('_expanded') && this._expanded) {
      this.shadowRoot.querySelectorAll('textarea.expandable').forEach(textarea => {
        textarea.style.height = '100%'
        textarea.style.minHeight = textarea.scrollHeight + 'px'
      })
    }
  }

  _fillUpForm(form, data) {
    for (let key in data) {
      Array.from(form.querySelectorAll('input')).forEach(field => {
        if (field.name === key && field.type === 'checkbox') {
          field.checked = data[key]
        } else if (field.name === key && field.type === 'datetime-local') {
          const datetime = Number(data[key])
          const timezoneOffset = new Date(datetime).getTimezoneOffset() * 60000
          field.value = new Date(datetime - timezoneOffset).toISOString().slice(0, -1).split('.')[0]
        } else if (field.name === key) {
          if (data[key] instanceof Object) {
            const objectData = data[key]
            field.value = `${objectData.name} ${objectData.description ? `(${objectData.description})` : ''}`
          } else {
            field.value = data[key]
          }
        }
      })
    }
  }
}

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