import { useApiDownloaderStatsRetrieve } from '@/api/generated/public/downloader';
import Piechart from './Piechart';

function formatBytes(bytes: number | null): string {
  if (bytes === null) return 'N/A';
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
  if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
  return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`;
}

function formatDuration(seconds: number | null): string {
  if (seconds === null) return 'N/A';
  const m = Math.floor(seconds / 60);
  const s = Math.round(seconds % 60);
  return `${m}:${String(s).padStart(2, '0')}`;
}

export default function Statistics() {
  const { data, isLoading, isError } = useApiDownloaderStatsRetrieve();

  if (isLoading) {
    return (
      <div className="mt-12 border-t pt-10 text-center text-gray-400 text-sm animate-pulse">
        Loading statistics...
      </div>
    );
  }

  if (isError || !data) return null;

  const pieData = data.downloads_by_platform.map((p) => ({
    label: p.platform,
    count: p.count,
  }));

  const statCards = [
    { label: 'Total Downloads', value: data.total_downloads.toLocaleString() },
    { label: 'Success Rate', value: `${data.success_rate.toFixed(1)}%` },
    { label: 'Avg File Size', value: formatBytes(data.avg_file_size) },
    { label: 'Avg Duration', value: formatDuration(data.avg_length_of_media) },
    { label: 'Most Common Format', value: data.most_common_format?.toUpperCase() ?? 'N/A' },
    { label: 'Video Downloads', value: data.video_count.toLocaleString() },
    { label: 'Audio Only', value: data.audio_only_count.toLocaleString() },
    { label: 'Total Media Time', value: formatDuration(data.total_length_of_media) },
  ];

  return (
    <div className="mt-12 border-t pt-10">
      <h2 className="text-xl font-bold mb-6 text-gray-800">Downloader Statistics</h2>

      <div className="grid grid-cols-2 sm:grid-cols-4 gap-4 mb-10">
        {statCards.map((s) => (
          <div key={s.label} className="p-4 bg-gray-50 rounded-lg border text-center">
            <div className="text-2xl font-bold text-blue-600">{s.value}</div>
            <div className="text-xs text-gray-500 mt-1">{s.label}</div>
          </div>
        ))}
      </div>

      {pieData.length > 0 && (
        <div className="flex justify-center">
          <Piechart data={pieData} title="Downloads by Platform" />
        </div>
      )}
    </div>
  );
}
