import { SelectEntry } from '@bpmn-io/properties-panel'
import { useEffect, useState } from '@bpmn-io/properties-panel/preact/hooks'
import { useService } from 'bpmn-js-properties-panel'
import { html } from 'htm/preact'

export default function FunctionSelect(props) {
  const { element, id, property } = props

  const commandStack = useService('commandStack')
  const translate = useService('translate')

  const getValue = () => {
    return property?.value
  }

  const setValue = (value) => {
    return commandStack.execute('element.updateModdleProperties', {
      element,
      moddleElement: property,
      properties: {
        value,
      },
    })
  }

  const [functionList, setFunctionList] = useState([])
  const [fetching, setFetching] = useState(false)

  useEffect(() => {
    function fetch() {
      setFetching(true)
      new Promise((resolve) => {
        setTimeout(resolve, 5000)
      }).then(() => {
        setFunctionList(Array.from({ length: 10 }, (v, k) => `Function ${k}`))
      }).finally(() => {
        setFetching(false)
      })
    }

    fetch()
  }, [setFunctionList])

  const getOptions = () => {
    return functionList.map(functionName => ({
      label: functionName,
      value: functionName.toLowerCase().replace(/\s/, '_'),
    }))
  }

  return html`<${SelectEntry}
    id=${id}
    element=${element}
    label=${translate('Function name')}
    description=${fetching ? translate('Loading...') : undefined}
    disabled=${fetching}
    getValue=${getValue}
    setValue=${setValue}
    getOptions=${getOptions}
  />`
}
