import { useBlocksQuery } from '../../gql'
import { ChangeEvent } 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 blocks = useBlocksQuery()

  function handleChange(event: ChangeEvent<HTMLSelectElement>) {
    const { name, value } = event.target
    onChange({
      target: {
        type: 'custom',
        name,
        value: blocks.data?.blocks.find((block) => block.id === value),
      },
    })
  }

  return (
    <>
      <label>{label}</label>
      <select id={name} name={name} value={value?.id} onChange={handleChange}>
        {blocks.loading && 'loading blocks...'}
        {blocks.error && 'error loading blocks'}
        {blocks.data && (
          <>
            <option key='not-selected'>Please select a block.</option>
            {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>
    </>
  )
}

export default BlockSelector
