import '@things-factory/grist-ui'

import { css, html } from 'lit'

import { i18next } from '@things-factory/i18n-base'
import { PageView } from '@things-factory/shell'
import { ScrollbarStyles } from '@things-factory/styles'
import { isMobileDevice } from '@things-factory/utils'

export class StickyTestPage extends PageView {
  static get properties() {
    return {}
  }

  static get styles() {
    return [
      ScrollbarStyles,
      css`
        :host {
          display: block;
          position: relative;

          overflow: auto;
        }

        /* The sticky class is added to the header with JS when it reaches its scroll position */
        .sticky {
          position: absolute;
          width: 100%;

          z-index: 1;
        }
      `
    ]
  }

  get context() {
    return {
      title: 'sticky test',
      actions: []
    }
  }

  render() {
    return html`
      <div>
        <div style="height: 200px; width: 100%; background-color:blue;color:white;">Scroll Area</div>
      </div>

      <div id="header" style="height: 100px; width: 100%; background-color:red;color:white;">Fixed Area</div>

      <data-grist
        .mode=${isMobileDevice() ? 'LIST' : 'GRID'}
        .config=${this.gristConfig}
        .fetchHandler=${this.fetchHandler.bind(this)}
      >
      </data-grist>
    `
  }

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

  async firstUpdated() {
    // Get the header
    var header = this.renderRoot.querySelector('#header')
    var grist = this.renderRoot.querySelector('data-grist')

    var stickyTop = header.offsetTop
    var stickyHeight = header.offsetHeight

    this.addEventListener('scroll', e => {
      if (this.scrollTop > stickyTop) {
        header.classList.add('sticky')
        grist.style.paddingTop = stickyHeight + 'px'
        header.style.top = this.scrollTop + 'px'
      } else {
        header.classList.remove('sticky')
        grist.style.paddingTop = 0
      }
    })
  }

  async pageInitialized(lifecycle) {
    this.searchConfig = [
      {
        name: 'name',
        type: 'text',
        props: {
          placeholder: i18next.t('field.name'),
          searchOper: 'like'
        }
      },
      {
        name: 'type',
        type: 'text',
        props: {
          placeholder: i18next.t('field.type'),
          searchOper: 'eq'
        }
      },
      {
        name: 'description',
        type: 'text',
        props: {
          placeholder: i18next.t('field.description'),
          searchOper: 'like'
        }
      }
    ]

    this._updateSearchConfig(lifecycle)

    this.gristConfig = {
      list: { fields: ['name', 'description', 'state'] },
      columns: [
        { type: 'gutter', gutterName: 'sequence' },
        { type: 'gutter', gutterName: 'row-selector', multiple: true },
        {
          type: 'string',
          name: 'name',
          header: i18next.t('field.name'),
          record: {
            editable: true
          },
          sortable: true,
          width: 150
        },
        {
          type: 'string',
          name: 'description',
          header: i18next.t('field.description'),
          record: {
            editable: true
          },
          width: 200
        },
        {
          type: 'checkbox',
          name: 'active',
          header: i18next.t('field.active'),
          record: {
            editable: true
          },
          sortable: true,
          width: 60
        },
        {
          type: 'object',
          name: 'updater',
          header: i18next.t('field.updater'),
          record: {
            editable: false
          },
          sortable: true,
          width: 120
        },
        {
          type: 'datetime',
          name: 'updatedAt',
          header: i18next.t('field.updated_at'),
          record: {
            editable: false
          },
          sortable: true,
          width: 180
        }
      ],
      rows: {
        selectable: {
          multiple: true
        }
      },
      sorters: [
        {
          name: 'name'
        }
      ]
    }

    await this.updateComplete

    this.dataGrist.fetch()
  }

  async pageUpdated(changes, lifecycle) {
    if (this.active) {
      // update with url params value
      this._updateSearchConfig(lifecycle)
      await this.updateComplete

      this.dataGrist.fetch()
    }
  }

  async fetchHandler({ page, limit, sorters = [] }) {
    return {
      total: 30,
      records: new Array(30).fill('').map((_, idx) => {
        return {
          name: idx,
          description: idx,
          active: true
        }
      })
    }
  }

  async stateChanged(state) {}

  // update with url params value
  _updateSearchConfig(lifecycle) {
    this.searchConfig = this.searchConfig.map(conf => {
      if (conf.name in lifecycle.params) {
        conf.value = lifecycle.params[conf.name]
      } else {
        delete conf.value
      }
      return conf
    })
  }
}

window.customElements.define('sticky-test-page', StickyTestPage)
