import { useRef, useState } from 'react'
import { Button, ButtonProps } from '../Button/index.js'
import { useToast } from '../Toast/index.js'

type InlineFileInputProps = {
  multiple?: boolean
  onChange: (value: File[]) => void | Promise<void>
} & Omit<ButtonProps, 'onClick' | 'loading'>

function InlineFileInput({
  multiple = false,
  onChange,
  ...buttonProps
}: InlineFileInputProps) {
  const [loading, setLoading] = useState(false)
  const ref = useRef<HTMLInputElement>()
  const toast = useToast()

  return (
    <>
      <Button
        {...buttonProps}
        onClick={() => {
          ref.current.click()
        }}
        loading={loading}
      />
      <input
        style={{
          position: 'absolute',
          width: 1,
          height: 1,
          padding: 0,
          margin: -1,
          overflow: 'hidden',
          clip: 'rect(0, 0, 0, 0)',
          whiteSpace: 'nowrap',
          borderWidth: 0,
        }}
        ref={ref}
        type="file"
        multiple={multiple}
        onChange={async (e) => {
          if (!e.target.files.length) return
          const files = [...e.target.files]

          try {
            const result = onChange(files)

            if (result instanceof Promise) {
              setLoading(true)
              await result
            }
          } catch {
            toast(`Upload failed: ${e}`, { color: 'red' })
          } finally {
            setLoading(false)
            e.target.value = ''
          }
        }}
      />
    </>
  )
}

export { InlineFileInput }
export type { InlineFileInputProps }
