import React, { useState, useEffect, useCallback } from 'react';
import FileList from './components/FileList';
import FileUpload from './components/FileUpload';
import FilePreview from './components/FilePreview';
import { fetchFiles, deleteFile } from './api/fileApi';
import './App.css';

function App() {
  const [files, setFiles] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [previewFile, setPreviewFile] = useState(null);

  const loadFiles = useCallback(() => {
    setLoading(true);
    fetchFiles()
      .then(data => {
        setFiles(data);
        setError(null);
      })
      .catch(() => setError('Could not load files. Is the backend running?'))
      .finally(() => setLoading(false));
  }, []);

  useEffect(() => {
    loadFiles();
  }, [loadFiles]);

  const handleDelete = id => {
    if (!window.confirm('Delete this file?')) return;
    deleteFile(id).then(loadFiles);
  };

  return (
    <div className="app-container">
      <h1>PDF File Manager</h1>

      <FileUpload onUploadSuccess={loadFiles} />

      <h3>Stored files</h3>
      {loading && <p>Loading...</p>}
      {error && <p className="error-text">{error}</p>}
      {!loading && !error && (
        <FileList files={files} onPreview={setPreviewFile} onDelete={handleDelete} />
      )}

      <FilePreview file={previewFile} onClose={() => setPreviewFile(null)} />
    </div>
  );
}

export default App;
