import { useFilesQuery, File, FilesQueryVariables } from '../../gql'
import { ChangeEvent, useState } from 'react'
import { customEvent } from '../../lib/customEvent'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faUpload } from '@fortawesome/free-solid-svg-icons'
import { Modal } from '../../modal'
import { UploadFile } from '../index'

const FileSelector = ({
  name,
  value,
  onChange,
  queryConf,
}: {
  name: string
  value?: File
  queryConf?: FilesQueryVariables
  onChange: (event: CustomChangeEvent) => void
}) => {
  const { data, error, loading, refetch } = useFilesQuery({ variables: queryConf })
  const [modal, setModal] = useState(false)

  if (error) return <p>Error loading files.</p>
  if (loading) return <p>Loading files.</p>
  if (!data) return <p>No data found.</p>

  function handleChange(event: ChangeEvent<HTMLSelectElement>) {
    if (data?.files)
      onChange(
        customEvent(
          name,
          data.files.find((file) => file.id === event.target.value)
        )
      )
  }

  return (
    <>
      <select name={name} value={value?.id} onChange={handleChange}>
        <option>Please select a file.</option>
        {data.files.map((file) => (
          <option key={file.id} value={file.id}>
            {file.filename}
          </option>
        ))}
      </select>
      <button type='button' onClick={() => setModal(true)}>
        <FontAwesomeIcon icon={faUpload} height={14} />
      </button>
      <Modal state={[modal, setModal]}>
        <UploadFile
          callback={(file) => {
            refetch()
            setModal(false)
            onChange(customEvent('file', file))
          }}
        />
      </Modal>
    </>
  )
}

export default FileSelector
