import '@things-factory/form-ui'
import '@things-factory/grist-ui'

import { css, html, LitElement } from 'lit-element'

import { i18next, localize } from '@things-factory/i18n-base'
import { ScrollbarStyles } from '@things-factory/styles'
import { isMobileDevice } from '@things-factory/utils'
import { ORDER_STATUS } from '../constants'
import { showToast } from '../../util'

class ShowRoListPopup extends localize(i18next)(LitElement) {
  static get properties() {
    return {
      releaseOrders: Array,
      config: Object,
      data: Object,
      sorting: Boolean
    }
  }

  static get styles() {
    return [
      ScrollbarStyles,
      css`
        :host {
          display: flex;
          flex-direction: column;
          overflow: hidden;
          background-color: white;
        }
        .grist {
          display: flex;
          flex-direction: column;
          flex: 1;
          overflow-y: auto;
        }
        .grist-container {
          overflow-y: hidden;
          display: flex;
          flex: 1;
        }
        data-grist {
          overflow-y: hidden;
          flex: 1;
        }
        h2 {
          padding: var(--subtitle-padding);
          font: var(--subtitle-font);
          color: var(--subtitle-text-color);
          border-bottom: var(--subtitle-border-bottom);
        }
        .grist h2 {
          font: var(--grist-title-font);
        }
        .button-container {
          padding: var(--button-container-padding);
          margin: var(--button-container-margin);
          text-align: var(--button-container-align);
          background-color: var(--button-container-background);
          height: var(--button-container-height);
        }
        .button-container button {
          background-color: var(--button-container-button-background-color);
          border-radius: var(--button-container-button-border-radius);
          height: var(--button-container-button-height);
          border: var(--button-container-button-border);
          margin: var(--button-container-button-margin);

          padding: var(--button-padding);
          color: var(--theme-white-color);
          font: var(--button-font);
          text-transform: var(--button-text-transform);
        }
        .button-container button:hover,
        .button-container button:active {
          background-color: var(--button-background-focus-color);
        }
      `
    ]
  }

  get grist() {
    return this.shadowRoot.querySelector('data-grist')
  }

  get searchForm() {
    return this.shadowRoot.querySelector('search-form')
  }

  get searchInput() {
    return this.searchForm.shadowRoot.querySelector('input[name="orderInfo"]')
  }

  render() {
    return html`
      <search-form id="search-form" .fields=${this._searchFields} @submit=${e => this.filterData(e)}></search-form>

      <div class="grist-container">
        <div class="grist">
          <data-grist
            .mode=${isMobileDevice() ? 'LIST' : 'GRID'}
            .config=${this.config}
            .data="${this.data}"
          ></data-grist>
        </div>
      </div>

      <div class="button-container">
        <mwc-button raised @click=${this._selectReleaseOrder.bind(this)}>${i18next.t('button.confirm')}</mwc-button>
      </div>
    `
  }

  filterData(e) {
    const searchValue = this.searchInput.value
    this.data = {
      records: this.releaseOrders.filter(ro =>
        Object.values(ro).some(value => String(value).toLowerCase().includes(searchValue.toLowerCase()))
      )
    }
  }

  updated(changeProps) {
    if (changeProps.has('releaseOrders')) {
      if (this.releaseOrders && this.releaseOrders.length) {
        const processedRecords = this.releaseOrders.map(ro => {
          const completed = ro.itemCounts ? ro.itemCounts.total - ro.itemCounts.pending : 0
          const total = ro.itemCounts?.total || 0
          return {
            ...ro,
            itemCounts: ro.itemCounts ? `${completed}/${total}` : '0/0'
          }
        })
        this.data = { records: processedRecords }
      }
    }
  }

  firstUpdated() {
    this._searchFields = [
      {
        type: 'string',
        name: 'orderInfo',
        label: i18next.t('field.order_info')
      }
    ]

    this.config = {
      rows: { selectable: { multiple: false }, appendable: false },
      pagination: { infinite: true },
      list: {
        fields: ['name', 'refNo', 'refNo2', 'district', 'attentionCompany', 'address', 'status', 'sortedByUser', 'itemCounts']
      },
      columns: [
        { type: 'gutter', gutterName: 'sequence' },
        { type: 'gutter', gutterName: 'row-selector', multiple: false },
        {
          type: 'string',
          name: 'name',
          header: i18next.t('field.name'),
          label: true,
          width: 180
        },
        {
          type: 'string',
          name: 'refNo',
          header: i18next.t('field.ref_no'),
          label: true,
          width: 120
        },
        {
          type: 'string',
          name: 'refNo2',
          header: i18next.t('field.ref_no_2'),
          label: true,
          width: 120
        },
        {
          type: 'string',
          name: 'district',
          header: i18next.t('field.district'),
          label: true,
          width: 120
        },
        {
          type: 'string',
          name: 'attentionCompany',
          header: i18next.t('field.attention_company'),
          label: true,
          width: 120
        },
        {
          type: 'string',
          name: 'address',
          header: i18next.t('field.address'),
          label: true,
          width: 200
        },
        {
          type: 'string',
          name: 'status',
          header: i18next.t('field.status'),
          label: true,
          width: 120
        },
        {
          type: 'string',
          name: 'sortedByUser',
          header: i18next.t('field.sorted_by'),
          label: true,
          width: 120
        },
        {
          type: 'string',
          name: 'itemCounts',
          header: i18next.t('field.completed_items'),
          label: true,
          width: 150
        }
      ]
    }
  }

  _selectReleaseOrder() {
    const selectedRO = this.grist.selected[0]
    if (selectedRO && selectedRO.status != ORDER_STATUS.SORTING.value) {
      if (this.sorting) {
        document.dispatchEvent(
          new CustomEvent('notify', { detail: { message: i18next.t('text.sorting_is_completed') } })
        )
      } else {
        this.dispatchEvent(new CustomEvent('ro-selected-loading', { detail: { ro: selectedRO } }))
        history.back()
      }
    } else if (selectedRO && selectedRO.status === ORDER_STATUS.SORTING.value) {
      if (this.sorting) {
        this.dispatchEvent(new CustomEvent('ro-selected-sorting', { detail: { ro: selectedRO } }))
        history.back()
      } else {
        document.dispatchEvent(
          new CustomEvent('notify', { detail: { message: i18next.t('text.order_in_sorting_status') } })
        )
      }
    } else {
      const msg = i18next.t('text.no_orders_selected', {
        defaultValue: 'Please select a Release Order'
      })
      showToast(new Error(msg))
    }
  }
}

window.customElements.define('show-ro-list-popup', ShowRoListPopup)
