import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { CircleNotch, DownloadSimple, CheckCircle, WarningCircle, X } from '@phosphor-icons/react';
import { fetchJobStatus, downloadUrl } from './api.js';
import { formatBytes } from './utils/formatBytes.js';
import { fileTypeMeta } from './utils/fileFamily.js';

function extensionOf(fileName) {
  return fileName.split('.').pop();
}

export function FileCard({ fileName, fileSize, targetFormat, jobId, initialError, onRemove }) {
  const { t } = useTranslation();
  const [status, setStatus] = useState(initialError ? 'failed' : 'pending');
  const [errorMessage, setErrorMessage] = useState(initialError ?? null);
  const [outputSize, setOutputSize] = useState(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') setOutputSize(job.outputSizeBytes);
      if (job.status === 'done' || job.status === 'failed') clearInterval(interval);
    }, 1500);

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

  const { Icon, colorVar } = fileTypeMeta(extensionOf(fileName));

  return (
    <li className={`file-card file-card-${status}`}>
      <div className="file-tile-header">
        <span className="file-tile-icon" style={{ '--tile-color': `var(${colorVar})` }}>
          <Icon size={20} weight="regular" />
        </span>
        <span className="file-tile-name">{fileName}</span>
        {targetFormat && <span className="format-badge">{targetFormat.toUpperCase()}</span>}
        <span className="file-tile-size">{formatBytes(fileSize)}</span>
        <button
          type="button"
          className="file-remove-button"
          onClick={onRemove}
          aria-label={t('common.remove')}
        >
          <X size={16} weight="bold" />
        </button>
      </div>
      {(status === 'pending' || status === 'processing') && (
        <div className="job-progress">
          <span className="job-status">
            <CircleNotch size={18} weight="bold" className="spin" />
            {t('job.converting')}
          </span>
          <span className="progress-track" aria-hidden="true">
            <span className="progress-fill" />
          </span>
        </div>
      )}
      {status === 'done' && (
        <a className="download-button" href={downloadUrl(jobId)}>
          <CheckCircle size={18} weight="fill" className="status-icon-success" />
          <DownloadSimple size={20} weight="regular" />
          {t('job.download')} ({formatBytes(outputSize)})
        </a>
      )}
      {status === 'failed' && (
        <span className="error">
          <WarningCircle size={18} weight="fill" />
          {errorMessage}
        </span>
      )}
    </li>
  );
}
