import { useBlocksQuery } from '../../gql'
import { useState, useEffect } from 'react'
import { TBlock } from '../types'

interface IBlockSelector {
  value?: TBlock
  onChange: GenericEventHandler
  name?: string
  label?: string
}

const BlockSelector = ({
  value,
  onChange,
  name = 'block',
  label = 'Block'
}: IBlockSelector) => {
  const [state, setState] = useState(value?.id ?? '')
  const blocks = useBlocksQuery()

  useEffect(() => {
    setState(value?.id || '')
  }, [value])

  return (
    <>
      <label>{label}</label>
      <select
        id={name}
        name={name}
        value={state}
        onChange={ev => setState(ev.target.value)}
      >
        {blocks.loading && 'loading blocks...'}
        {blocks.error && 'error loading blocks'}
        {blocks.data &&
          blocks.data.blocks.map(block => (
            <option key={block.id} value={block.id}>
              {[block.title, block.description?.slice(0, 60)]
                .filter(block => !!block)
                .join(' - ')}
            </option>
          ))}
      </select>
      <button
        type='button'
        onClick={event => {
          const block =
            blocks.data && blocks.data.blocks.find(block => block.id === state)
          if (!block) return
          const changeEvent: CustomChangeEvent = {
            target: {
              type: 'custom',
              value: block,
              name
            }
          }
          onChange(changeEvent)
        }}
      >
        Use
      </button>
    </>
  )
}

export default BlockSelector
