import { useFormatsQuery, FormatCreateOneInput, Format } from '../../gql'
import { useEffect } from 'react'

interface IFormatSelector {
  value: Format
  onChange: GenericEventHandler
  name?: string
  label?: string
}

const FormatSelector = ({
  value,
  onChange,
  name = 'format',
  label = 'Format'
}: IFormatSelector) => {
  const formats = useFormatsQuery()
  const { id } = value

  useEffect(() => {
    if (formats.data && formats.data.formats.length > 0 && !id) {
      console.log('format:', name)
      onChange({
        target: {
          type: 'custom',
          value: formats.data.formats[0],
          name
        }
      })
    }
  }, [formats])

  return (
    <>
      <label>{label}</label>
      <select
        id={name}
        name={name}
        value={id || undefined}
        onChange={event => {
          const copy: CustomChangeEvent = {
            target: {
              type: 'custom',
              value: { connect: { id: event.target.value } },
              name
            }
          }
          onChange(copy)
        }}
      >
        {formats.loading && 'loading formats...'}
        {formats.error && 'error loading formats'}
        {formats.data &&
          formats.data.formats.map(format => (
            <option key={format.id} value={format.id}>
              {format.name}
            </option>
          ))}
      </select>
      <button
        type='button'
        onClick={event => {
          event.preventDefault()
        }}
      >
        Add format
      </button>
    </>
  )
}

export default FormatSelector
