import { useUploadFileMutation, File, FilesDocument } from '../../gql'
import { useForm, TextInput } from '../../form'
import { customEvent } from '../../lib/customEvent'

const UploadFile = ({ callback }: { callback?: (file: File) => void }) => {
  const [uploadFile, { error, loading }] = useUploadFileMutation()
  const { values, onChange } = useForm({ file: undefined, comment: '' })

  return (
    <>
      <form
        onSubmit={async (event) => {
          event.preventDefault()
          const file = await uploadFile({ variables: values })
          callback && callback(file.data.uploadFile)
        }}
      >
        <h2>File Upload</h2>
        <input
          name='file'
          type='file'
          accept='video/*'
          onChange={(event) => {
            console.log(event.target.files, event.target.files?.item(0))
            onChange(customEvent('file', event.target.files?.item(0)))
          }}
        />
        <TextInput
          name='comment'
          value={values.comment}
          placeholder='Comment'
          onChange={onChange}
        />
        <button type='submit' disabled={loading}>
          Upload
        </button>
        {error && <div className='error'>Error</div>}
      </form>
    </>
  )
}

export default UploadFile
