// https://github.com/YelyseiLukin/react-files-drag-and-drop/tree/c290a4bfc216db17137fcb9e31757ef437934025
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

import { useId, useRef, useState } from "react"

interface FilesDragAndDropProps {
  className?: string
  label?: React.ReactNode
  multiple?: boolean
  onUpload(files: File[]): void
  onError(message: string): void
  extensions?: string[]
  children(props: { dragging: boolean; labelId: string }): React.ReactElement
}

export function FileInput({
  className,
  children,
  multiple,
  onError,
  onUpload,
  extensions: formats,
}: FilesDragAndDropProps): React.ReactElement {
  const labelId = useId()
  const [dragging, setDragging] = useState(false)

  const input = useRef<HTMLInputElement>(null)

  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault()
    e.stopPropagation()
  }

  const handleDragEnter = (e: React.DragEvent) => {
    e.preventDefault()
    e.stopPropagation()

    if (e.target !== e.currentTarget) {
      setDragging(true)
    }
  }

  const handleDragLeave = (e: React.DragEvent) => {
    e.preventDefault()
    e.stopPropagation()

    // if (e.target === e.currentTarget) {
    setDragging(false)
    // }
  }

  const handleUpload = (files: File[]) => {
    if (
      formats &&
      files.some(
        file =>
          !formats.some(format => file.name.toLowerCase().endsWith(format.toLowerCase())),
      )
    ) {
      onError(`Only following file formats are acceptable: ${formats?.join(", ")}`)
      return
    }

    if (files?.length) {
      onUpload(files)
    }
  }

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault()
    e.stopPropagation()

    setDragging(false)

    const files = e.dataTransfer?.files ? [...e.dataTransfer.files] : []

    handleUpload(files)
  }

  const handleSelectFiles = (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = [...e.target.files!]
    handleUpload(files)
  }

  const openFileDialog = () => {
    input.current?.click()
  }

  return (
    <div
      onDragOver={handleDragOver}
      onDrop={handleDrop}
      onDragEnter={handleDragEnter}
      onDragLeave={handleDragLeave}
      onClick={openFileDialog}
      onKeyDown={e => {
        if (e.key === "Enter") {
          openFileDialog()
        }
      }}
      className={className}
      aria-label="Upload files"
      role="button"
      tabIndex={0}
    >
      {children({ dragging, labelId })}
      <input
        type="file"
        id={labelId}
        style={{ display: "none" }}
        accept={formats ? formats.map(format => `.${format}`).join(", ") : undefined}
        multiple={multiple}
        onChange={handleSelectFiles}
      />
    </div>
  )
}
