import { useRef, useEffect } from 'react';
import Button from './Button';

interface FilesUploaderProps {
  label: string;
  onFilesUpload: (files: File[]) => void;
}

export default function FilesUploader({ label, onFilesUpload }: FilesUploaderProps) {
  const fileInputRef = useRef<HTMLInputElement>(null);

  // enable folder picking
  useEffect(() => {
    const el = fileInputRef.current;
    if (!el) return;

    el.setAttribute("webkitdirectory", "");
    el.setAttribute("directory", "");
  }, []);

  const handleButtonClick = () => {
    fileInputRef.current?.click();
  };

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = e.target.files;

    if (!files) {
      return;
    }

    const fileList = Array.from(files);
    onFilesUpload(fileList);
    e.target.value = "";
  };

  return (
    <>
      <input
        type="file"
        ref={fileInputRef}
        onChange={handleFileChange}
        className="hidden"
        multiple
      />

      <Button label={label} onClick={handleButtonClick} />
    </>
  );
}