import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { DownloadSimple } from '@phosphor-icons/react';
import { fetchJobStatus, downloadUrl } from './api.js';

export function FileCard({ fileName, jobId, initialError }) {
  const { t } = useTranslation();
  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-config-name">{fileName}</span>
      {(status === 'pending' || status === 'processing') && <span>{t('job.converting')}</span>}
      {status === 'done' && (
        <a href={downloadUrl(jobId)}>
          <DownloadSimple size={20} weight="regular" /> {t('job.download')}
        </a>
      )}
      {status === 'failed' && <span className="error">{errorMessage}</span>}
    </li>
  );
}
