import { useState } from 'react';
import axios from 'axios';

const FileUpload = () => {
  const [file, setFile] = useState(null);
  const [progress, setProgress] = useState(0);

  const handleFileChange = (event) => {
    if (event.target.files) {
      setFile(event.target.files[0]);
    }
  };

  const handleSubmit = async (event) => {
    event.preventDefault();
    if (!file) return;

    const formData = new FormData();
    formData.append('file', file);
    formData.append('title', 'Your document title');
    // Add other fields as needed

    try {
      await axios.post('/api/admin/document', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
        onUploadProgress: (progressEvent) => {
          const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
          setProgress(percentCompleted);
        },
      });

      console.log('Upload successful');
      setProgress(0);
    } catch (error) {
      console.error('Upload failed:', error);
      setProgress(0);
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <input type="file" onChange={handleFileChange} />
      <button type="submit">Upload</button>
      {progress > 0 && (
        <div>
          <progress value={progress} max="100" />
          <p>{progress}% uploaded</p>
        </div>
      )}
    </form>
  );
};

export default FileUpload;