/**
 * DownloadProgressPanel Component
 *
 * Shows progress of all active downloads with pause/resume/cancel controls.
 * Similar to hoboken's VideoOptimizationDropdown pattern.
 */

import React from 'react';
import {
  mdiPause,
  mdiPlay,
  mdiClose,
  mdiCheck,
  mdiAlertCircle,
  mdiLoading,
} from '@mdi/js';
import Icon from '@mdi/react';
import { usePreloadProgress } from '../../hooks/usePreloadProgress';

interface DownloadProgressPanelProps {
  className?: string;
  maxItems?: number;
  showWhenEmpty?: boolean;
}

export function DownloadProgressPanel({
  className = '',
  maxItems = 5,
  showWhenEmpty = false,
}: DownloadProgressPanelProps) {
  const {
    jobs,
    activeCount,
    completedCount,
    errorCount,
    totalProgress,
    isActive,
    clearJob,
    clearAllCompleted,
    clearAllErrors,
  } = usePreloadProgress();

  // Don't render if empty and not configured to show
  if (!showWhenEmpty && jobs.length === 0) {
    return null;
  }

  const visibleJobs = jobs.slice(0, maxItems);
  const hiddenCount = jobs.length - maxItems;

  return (
    <div
      className={`bg-white border border-gray-200 rounded-lg shadow-lg p-3 min-w-[280px] ${className}`}
    >
      {/* Header */}
      <div className='flex items-center justify-between mb-2 pb-2 border-b border-gray-100'>
        <div className='flex items-center gap-2'>
          <span className='text-sm font-medium text-gray-700'>Downloads</span>
          {isActive && (
            <span className='text-xs text-blue-600'>{activeCount} active</span>
          )}
        </div>
        <div className='flex items-center gap-1'>
          {completedCount > 0 && (
            <button
              onClick={clearAllCompleted}
              className='text-xs text-gray-500 hover:text-gray-700'
            >
              Clear completed
            </button>
          )}
          {errorCount > 0 && (
            <button
              onClick={clearAllErrors}
              className='text-xs text-red-500 hover:text-red-700 ml-2'
            >
              Clear errors
            </button>
          )}
        </div>
      </div>

      {/* Overall progress */}
      {isActive && (
        <div className='mb-3'>
          <div className='flex items-center justify-between text-xs text-gray-500 mb-1'>
            <span>Overall progress</span>
            <span>{totalProgress}%</span>
          </div>
          <div className='w-full h-1.5 bg-gray-200 rounded-full overflow-hidden'>
            <div
              className='h-full bg-blue-500 transition-all duration-300'
              style={{ width: `${totalProgress}%` }}
            />
          </div>
        </div>
      )}

      {/* Job list */}
      <div className='space-y-2'>
        {visibleJobs.map((job) => (
          <div
            key={job.id}
            className='flex items-center gap-2 p-2 bg-gray-50 rounded'
          >
            {/* Status icon */}
            <div className='flex-shrink-0'>
              {job.status === 'downloading' && (
                <Icon
                  path={mdiLoading}
                  size={0.7}
                  className='text-blue-500 animate-spin'
                />
              )}
              {job.status === 'completed' && (
                <Icon path={mdiCheck} size={0.7} className='text-green-500' />
              )}
              {job.status === 'error' && (
                <Icon
                  path={mdiAlertCircle}
                  size={0.7}
                  className='text-red-500'
                />
              )}
              {job.status === 'queued' && (
                <Icon path={mdiPause} size={0.7} className='text-gray-400' />
              )}
            </div>

            {/* Info */}
            <div className='flex-1 min-w-0'>
              <div className='text-xs font-medium text-gray-700 truncate'>
                {job.filename}
              </div>
              {job.status === 'downloading' && (
                <div className='w-full h-1 bg-gray-200 rounded-full mt-1 overflow-hidden'>
                  <div
                    className='h-full bg-blue-500 transition-all duration-300'
                    style={{ width: `${job.progress}%` }}
                  />
                </div>
              )}
              {job.status === 'error' && job.error && (
                <div className='text-xs text-red-500 truncate'>{job.error}</div>
              )}
            </div>

            {/* Progress/size */}
            <div className='flex-shrink-0 text-xs text-gray-500'>
              {job.status === 'downloading' && `${job.progress}%`}
              {job.status === 'completed' && formatBytes(job.totalBytes)}
            </div>

            {/* Close button */}
            <button
              onClick={() => clearJob(job.id)}
              className='flex-shrink-0 p-0.5 text-gray-400 hover:text-gray-600'
            >
              <Icon path={mdiClose} size={0.5} />
            </button>
          </div>
        ))}

        {hiddenCount > 0 && (
          <div className='text-xs text-gray-500 text-center py-1'>
            +{hiddenCount} more items
          </div>
        )}

        {jobs.length === 0 && showWhenEmpty && (
          <div className='text-xs text-gray-400 text-center py-2'>
            No active downloads
          </div>
        )}
      </div>
    </div>
  );
}

/**
 * Format bytes to human-readable string
 */
function formatBytes(bytes: number): string {
  if (bytes === 0) return '0 B';

  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));

  return `${parseFloat((bytes / Math.pow(k, i)).toFixed(1))} ${sizes[i]}`;
}

export default DownloadProgressPanel;
