import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { File as FileIcon, CircleNotch, DownloadSimple } from '@phosphor-icons/react';
import { fetchJobStatus, downloadUrl } from './api.js';
import { formatBytes } from './utils/formatBytes.js';

export function FileCard({ fileName, fileSize, 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">
      <div className="file-tile-header">
        <FileIcon size={24} weight="regular" />
        <span className="file-tile-name">{fileName}</span>
        <span className="file-tile-size">{formatBytes(fileSize)}</span>
      </div>
      {(status === 'pending' || status === 'processing') && (
        <span className="job-status">
          <CircleNotch size={18} weight="bold" className="spin" />
          {t('job.converting')}
        </span>
      )}
      {status === 'done' && (
        <a className="download-button" href={downloadUrl(jobId)}>
          <DownloadSimple size={20} weight="regular" />
          {t('job.download')} ({formatBytes(fileSize)})
        </a>
      )}
      {status === 'failed' && <span className="error">{errorMessage}</span>}
    </li>
  );
}
