import React, { memo } from 'react';
import type { DownloadQueueItem } from '../types';
import DownloadQueueItemComponent from './DownloadQueueItem';

interface DownloadQueueStatusProps {
  geId: string; // Deprecated - kept for backward compatibility
  queue: DownloadQueueItem[];
  onCancelJob: (jobId: string) => void;
  downloadingFilesCount?: number; // Số file đang downloading thực tế
}

const DownloadQueueStatus: React.FC<DownloadQueueStatusProps> = ({ queue, onCancelJob, downloadingFilesCount = 0 }) => {
  // Queue items are already sorted by created_at DESC in App.tsx (convertToQueueItems)
  // Newest batches are already at the top, so we just use the queue as-is
  const sortedQueue = React.useMemo(
    () => queue,
    [queue]
  );

  const showDetails = sortedQueue.length > 0;
  const waitingCount = sortedQueue.filter(q => q.status === 'waiting' || q.status === 'pending').length;

  return (
    <div className="bg-slate-800/50 backdrop-blur-sm p-6 rounded-2xl shadow-lg border border-slate-700 flex flex-col h-full">
      <div className="flex justify-between items-center mb-4 border-b border-slate-700 pb-3">
        <h2 className="text-xl font-semibold text-white">Hàng đợi và Trạng thái</h2>
        <div className="flex items-center gap-3 text-sm font-semibold">
          {downloadingFilesCount > 0 && (
            <div className="flex items-center gap-1">
              <div className="h-2 w-2 rounded-full bg-amber-500 animate-pulse"></div>
              <span className="text-amber-400">{downloadingFilesCount} tệp đang tải</span>
            </div>
          )}
          {waitingCount > 0 && (
            <div className="text-slate-400">
              <span className="text-blue-400">{waitingCount}</span> đang chờ
            </div>
          )}
        </div>
      </div>

      {showDetails ? (
        <div className="flex-1 overflow-y-auto pr-2 -mr-2">
          <div className="space-y-3">
            {sortedQueue.map((item, index) => (
              <DownloadQueueItemComponent
                key={item.key}
                item={item}
                queuePosition={item.queuePosition || (item.status === 'waiting' || item.status === 'pending' ? index + 1 : undefined)}
                onCancel={onCancelJob}
              />
            ))}
          </div>
        </div>
      ) : (
        <div className="flex justify-center items-center flex-1">
          <p className="text-slate-500">Không có job nào đang xử lý.</p>
        </div>
      )}
    </div>
  );
};

export default memo(DownloadQueueStatus);