import React from 'react';
import type { ImportProgressSnapshot } from '../../../api/server/importer';
import { ImporterStatistics } from '../../../api/server/importer/statistics';

const statusStyles: Record<ImportProgressSnapshot['status'], string> = {
  queued: 'text-neutral-300',
  installing: 'text-cyan-300',
  scanning: 'text-yellow-300',
  transferring: 'text-blue-300',
  completed: 'text-green-300',
  failed: 'text-red-300',
};

const statusLabels: Record<ImportProgressSnapshot['status'], string> = {
  queued: 'queued',
  installing: 'installing',
  scanning: 'scanning',
  transferring: 'importing',
  completed: 'completed',
  failed: 'failed',
};

const formatBytes = (bytes: number) => {
  if (bytes < 0) return null;
  if (bytes < 1024) return `${bytes} B`;
  const units = ['KB', 'MB', 'GB', 'TB'];
  let value = bytes / 1024;
  let unit = units[0];
  for (let i = 1; i < units.length && value >= 1024; i++) {
    value /= 1024;
    unit = units[i];
  }

  return `${value.toFixed(value >= 10 ? 1 : 2)} ${unit}`;
};

export default ({
  statistics,
  importProgress,
}: {
  statistics: ImporterStatistics | null;
  importProgress: ImportProgressSnapshot | null;
}) => {
  const profiles = statistics?.profiles ?? 0;
  const scanSize = importProgress?.mode === 'scan' ? formatBytes(importProgress.total_bytes) : null;
  const hasScanTotals = importProgress?.mode === 'scan' && importProgress.total_files >= 0;

  return (
    <div
      className={'flex flex-wrap items-center gap-x-4 gap-y-1 text-[10px] uppercase tracking-wider text-neutral-500'}
    >
      <span>
        {profiles} profile{profiles === 1 ? '' : 's'}
      </span>
      <span className={'text-green-400'}>{statistics?.successful_imports ?? 0} imported</span>
      <span className={'text-red-400'}>{statistics?.failed_imports ?? 0} failed</span>
      {importProgress && (
        <span className={statusStyles[importProgress.status]}>{statusLabels[importProgress.status]}</span>
      )}
      {hasScanTotals && <span className={'text-neutral-300'}>{importProgress.total_files} remote files</span>}
      {scanSize && <span className={'text-neutral-400'}>{scanSize}</span>}
    </div>
  );
};
