import { useEffect, useState } from 'react';
import { fetchJobStatus, downloadUrl } from './api.js';

export function FileCard({ fileName, jobId, initialError }) {
  const [status, setStatus] = useState(initialError ? 'failed' : 'pending');
  const [errorMessage, setErrorMessage] = useState(initialError ?? null);

  useEffect(() => {
    if (!jobId || initialError) return undefined;

    let cancelled = false;
    const interval = setInterval(async () => {
      const job = await fetchJobStatus(jobId);
      if (cancelled) return;
      setStatus(job.status);
      if (job.status === 'failed') setErrorMessage(job.errorMessage);
      if (job.status === 'done' || job.status === 'failed') clearInterval(interval);
    }, 1500);

    return () => {
      cancelled = true;
      clearInterval(interval);
    };
  }, [jobId, initialError]);

  return (
    <li className="file-card">
      <span className="file-name">{fileName}</span>
      {(status === 'pending' || status === 'processing') && <span>Conversion en cours...</span>}
      {status === 'done' && <a href={downloadUrl(jobId)}>Télécharger</a>}
      {status === 'failed' && <span className="error">{errorMessage}</span>}
    </li>
  );
}
