import * as React from 'react'

const { useCallback } = React

interface FilepickerResponse {
  url: string
  key: string
}

interface FilepickerProps {
  mimetype?: string
  uploadUrl: string
  onChange: (res: FilepickerResponse) => void
}

const pick = (mimetype?: string) => new Promise<FilepickerResponse>((resolve) => {
  const args = {
    storeTo: {
      location: 's3'
    },
    maxSize: 1024 * 1024 * 5,
    services: ['COMPUTER'],
    debug: window.FILEPICKER_DEBUG
  }
  if (mimetype) {
    args['mimetype'] = mimetype
  }
  window.filepicker.pick(args, resolve)
})

export const Filepicker = ({ mimetype, uploadUrl, onChange }: FilepickerProps) => {
  const onClickUpload = useCallback(() => {
    pick(mimetype).then(onChange)
  }, [mimetype])

  const onClickRemove = useCallback(() => {
    onChange({
      key: '',
      url: ''
    })
  }, [])

  return (
    <>
      <p>{uploadUrl}</p>
      <a className="change-upload" onClick={onClickUpload}>Upload File</a>
      <a className="remove-upload" onClick={onClickRemove}>Remove File</a>
    </>
  )
}
