import { useFormatsQuery, FormatCreateOneInput, Format } from '../../gql'
import { useEffect, useState } from 'react'
import CreateFormat from './CreateFormat'
import { Modal } from '../../modal'

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

const FormatSelector = ({
  value,
  onChange,
  name = 'format',
  label = 'Format'
}: IFormatSelector) => {
  const [modalState, setModalState] = useState(false)
  const formats = useFormatsQuery()
  const id = value?.id

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

  return (
    <>
      <label>{label}</label>
      <select
        id={name}
        name={name}
        value={id}
        onChange={event => {
          const changeEvent: CustomChangeEvent = {
            target: {
              type: 'custom',
              value: { connect: { id: event.target.value } },
              name
            }
          }
          onChange(changeEvent)
        }}
      >
        {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 => {
          setModalState(true)
        }}
      >
        Add format
      </button>
      <Modal state={[modalState, setModalState]}>
        <CreateFormat
          onSuccess={result => {
            if (result.data) {
              const changeEvent: CustomChangeEvent = {
                target: {
                  type: 'custom',
                  value: { connect: { id: result.data.createFormat.id } },
                  name
                }
              }
              onChange(changeEvent)
            }
            setModalState(false)
          }}
        />
      </Modal>
    </>
  )
}

export default FormatSelector
