import { createPopper } from '@popperjs/core'
import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  static targets = ['list']

  connect() {
    this.element[this.identifier] = this
    this.cursor = 0
    this.listTarget.style.display = 'none'
  }

  setProps (props) {
    this.props = props
  }

  start () {
    this.popup = createPopper(this.props.decorationNode, this.listTarget, {
      placement: 'bottom-start',
      modifiers: [
        {
          name: 'offset',
          options: {
            offset: [0, 10],
          },
        }
      ]
    })
  }

  show () {
    this.listTarget.style.display = 'block'
  }

  up () {
    this.cursor = ((this.cursor + this.length) - 1) % this.length
    this.highlight()
    return true
  }

  down () {
    this.cursor = (this.cursor === null) ? 0 : (this.cursor + 1) % this.length
    this.highlight()
    return true
  }

  highlight () {
    Array.from(this.listTarget.children).forEach(
      item => item.style.background = 'transparent'
    )

    if (! this.current) {
      return
    }

    this.current.style.background = 'red'
  }

  render () {
    this.listTarget.innerHTML = this.props.items.map((item) => `
    <button type="button" data-suggestions-id-param="${item}" data-action="suggestions#selectOnClick">
     ${item}
    </button>
    `).join('')
    this.cursor = 0
    this.highlight()
  }

  hide () {
    this.listTarget.style.display = 'none'
    return true
  }

  exit () {
    this.popup.destroy()
    this.hide()
  }

  select () {
    this.props.command({
      id: this.current.dataset.suggestionsIdParam,
    })
    return true
  }

  selectOnClick ({ params }) {
    this.props.command({ id: params.id })
  }

  get length () {
    return this.listTarget.children.length
  }

  get current () {
    return this.listTarget.children[this.cursor]
  }
}