import React, { memo } from 'react';
import type { DownloadHistoryEntry, DownloadedFile } from '../types';
import DownloadHistoryItem from './DownloadHistoryItem';
import { naturalSort } from '../utils/naturalSort';

interface DownloadHistoryProps {
  history: DownloadHistoryEntry[];
  onDelete: (id: string) => void;
  onRetry: (entry: DownloadHistoryEntry) => void;
  onErrorClick: (details: string) => void;
}

const DownloadHistory: React.FC<DownloadHistoryProps> = ({ history, onDelete, onRetry, onErrorClick }) => {
  // Sort files within each history entry by natural sort
  const sortedHistory = React.useMemo(() => {
    return history.map(entry => ({
      ...entry,
      files: naturalSort<DownloadedFile>(
        entry.files,
        (file: DownloadedFile) => file.file_name || file.name || ''
      )
    }));
  }, [history]);

  // Chỉ hiển thị 30 records mới nhất để tối ưu hiệu suất
  const displayedHistory = React.useMemo(() => sortedHistory.slice(0, 30), [sortedHistory]);

  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">Lịch sử tải xuống</h2>
        <span className="text-sm text-slate-400">
          {displayedHistory.length} / {history.length} bản ghi
        </span>
      </div>
      <div className="flex-1 overflow-y-auto pr-2 -mr-2">
        {displayedHistory.length > 0 ? (
          <div className="space-y-4">
            {displayedHistory.map((entry) => (
              <DownloadHistoryItem
                key={entry.id}
                entry={entry}
                onDelete={onDelete}
                onRetry={onRetry}
                onErrorClick={onErrorClick}
              />
            ))}
          </div>
        ) : (
          <div className="flex justify-center items-center flex-1">
            <p className="text-slate-400">Chưa có lịch sử tải xuống.</p>
          </div>
        )}
      </div>
    </div>
  );
};

export default memo(DownloadHistory);