import React, { useState } from 'react';
import { uploadFile } from '../api/fileApi';

function FileUpload({ onUploadSuccess }) {
  const [selectedFile, setSelectedFile] = useState(null);
  const [progress, setProgress] = useState(0);
  const [uploading, setUploading] = useState(false);
  const [error, setError] = useState(null);

  const handleFileChange = event => {
    const file = event.target.files[0];
    setError(null);
    if (file && file.type !== 'application/pdf') {
      setError('Only PDF files are allowed.');
      setSelectedFile(null);
      return;
    }
    setSelectedFile(file);
  };

  const handleUpload = () => {
    if (!selectedFile) {
      setError('Please choose a PDF file first.');
      return;
    }
    setUploading(true);
    setError(null);

    uploadFile(selectedFile, progressEvent => {
      const percent = Math.round((progressEvent.loaded * 100) / progressEvent.total);
      setProgress(percent);
    })
      .then(() => {
        setSelectedFile(null);
        setProgress(0);
        setUploading(false);
        onUploadSuccess();
      })
      .catch(err => {
        setUploading(false);
        setError(
          (err.response && err.response.data && err.response.data.message) ||
            'Upload failed. Please try again.'
        );
      });
  };

  return (
    <div className="upload-box">
      <h3>Upload a PDF</h3>
      <input type="file" accept="application/pdf" onChange={handleFileChange} disabled={uploading} />
      <button onClick={handleUpload} disabled={uploading || !selectedFile}>
        {uploading ? `Uploading... ${progress}%` : 'Upload'}
      </button>
      {error && <div className="error-text">{error}</div>}
    </div>
  );
}

export default FileUpload;
