import React from 'react';
import { getDownloadUrl } from '../api/fileApi';

function formatBytes(bytes) {
  if (!bytes) return '0 B';
  const units = ['B', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(1024));
  return `${(bytes / Math.pow(1024, i)).toFixed(1)} ${units[i]}`;
}

function formatDate(isoString) {
  if (!isoString) return '';
  const d = new Date(isoString);
  return d.toLocaleString();
}

function FileList({ files, onPreview, onDelete }) {
  if (!files || files.length === 0) {
    return <p className="empty-state">No files uploaded yet.</p>;
  }

  return (
    <table className="file-table">
      <thead>
        <tr>
          <th>File name</th>
          <th>Size</th>
          <th>Uploaded</th>
          <th>Actions</th>
        </tr>
      </thead>
      <tbody>
        {files.map(file => (
          <tr key={file.id}>
            <td>{file.fileName}</td>
            <td>{formatBytes(file.fileSize)}</td>
            <td>{formatDate(file.uploadDate)}</td>
            <td className="actions-cell">
              <button onClick={() => onPreview(file)}>Preview</button>
              <a href={getDownloadUrl(file.id)}>
                <button>Download</button>
              </a>
              <button className="danger" onClick={() => onDelete(file.id)}>
                Delete
              </button>
            </td>
          </tr>
        ))}
      </tbody>
    </table>
  );
}

export default FileList;
