import { ChangeEvent, useRef } from "react";

export type FileUploadProps = {
  label: string;
  accept?: string;
  multiple?: boolean;
  maxBytes?: number;
  onFileSelect: (files: File[]) => void;
  disabled?: boolean;
  helperText?: string;
  resetToken?: number;
};

export default function FileUpload({
  label,
  accept,
  multiple,
  maxBytes,
  onFileSelect,
  disabled,
  helperText,
  resetToken
}: FileUploadProps) {
  const inputRef = useRef<HTMLInputElement | null>(null);

  const onChange = (event: ChangeEvent<HTMLInputElement>) => {
    const targetFiles = Array.from(event.target.files ?? []);
    const files = maxBytes ? targetFiles.filter((file) => file.size <= maxBytes) : targetFiles;
    onFileSelect(files);
    event.target.value = "";
  };

  return (
    <label className="d-block">
      <span className="form-label">{label}</span>
      <input
        key={resetToken}
        ref={inputRef}
        type="file"
        accept={accept}
        multiple={multiple}
        disabled={disabled}
        className="form-control"
        onChange={onChange}
      />
      {helperText && <small className="text-muted">{helperText}</small>}
    </label>
  );
}
