import { useRef, useState } from 'react'
import { useWaste } from '../store'

export function FolderPicker() {
  const { setSharedFiles } = useWaste()
  const inputRef = useRef<HTMLInputElement>(null)
  const [label, setLabel] = useState<string | null>(null)

  function onChange(e: React.ChangeEvent<HTMLInputElement>) {
    const fileList = e.target.files
    if (!fileList || fileList.length === 0) return
    const map = new Map<string, File>()
    for (let i = 0; i < fileList.length; i++) {
      const f = fileList[i]
      map.set(f.name, f)
    }
    setSharedFiles(map)
    const first = fileList[0]
    const parts = (first.webkitRelativePath || first.name).split('/')
    setLabel(`${parts[0]} (${map.size} file${map.size !== 1 ? 's' : ''})`)
  }

  return (
    <div className="folder-picker">
      <input
        ref={inputRef}
        type="file"
        // @ts-expect-error webkitdirectory is non-standard
        webkitdirectory=""
        multiple
        style={{ display: 'none' }}
        onChange={onChange}
      />
      <button
        className="folder-picker-btn"
        onClick={() => inputRef.current?.click()}
        title="Share a folder with peers"
      >
        {label ?? '+ Share folder'}
      </button>
    </div>
  )
}
