import { useState, useMemo, useEffect } from 'react';
import { Link, useSearchParams } from 'react-router-dom';
import { formatDistanceToNow } from 'date-fns';
import { useAuthStore } from '../../lib/auth';
import { useJobs, useBulkDeleteJobs, useReprocessJob } from '../../hooks/useJob';
import { StatusBadge } from '../../components/StatusBadge';
import { useToastContext } from '../../contexts/ToastContext';
import { useGlobalWebSocket } from '../../contexts/GlobalWebSocketContext';
import { apiClient } from '../../lib/api';
import type { Job } from '../../types/api';

// Statuses eligible for bulk download (approved or completed)
const DOWNLOADABLE_STATUSES = ['completed', 'approved_english', 'approved_source'];

const STATUS_OPTIONS = [
  { value: '', label: 'All Statuses' },
  { value: 'created,ingesting,ai_processing', label: 'Processing' },
  { value: 'pending_qc,qc_feedback', label: 'In QC Review' },
  { value: 'approved_english,translating,tts_generating', label: 'Translation' },
  { value: 'pending_final_review', label: 'Final Review' },
  { value: 'completed', label: 'Completed' },
  { value: 'rejected', label: 'Rejected' },
];

const SORT_OPTIONS = [
  { value: 'created_at_desc', label: 'Newest First' },
  { value: 'created_at_asc', label: 'Oldest First' },
  { value: 'title_asc', label: 'Title A-Z' },
  { value: 'title_desc', label: 'Title Z-A' },
  { value: 'status_asc', label: 'Status A-Z' },
];

export function JobsList() {
  const { user } = useAuthStore();
  const toast = useToastContext();
  const [searchParams] = useSearchParams();
  const [searchTerm, setSearchTerm] = useState('');
  const [statusFilter, setStatusFilter] = useState(searchParams.get('status') || '');
  const [sortBy, setSortBy] = useState('created_at_desc');
  const [currentPage, setCurrentPage] = useState(1);
  const [selectedJobs, setSelectedJobs] = useState<Set<string>>(new Set());
  const [bulkAction, setBulkAction] = useState<'delete' | 'reprocess' | 'download' | ''>('');
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  const [showReprocessConfirm, setShowReprocessConfirm] = useState(false);
  const [showDownloadConfirm, setShowDownloadConfirm] = useState(false);
  const [downloadProgress, setDownloadProgress] = useState<{ current: number; total: number } | null>(null);
  const pageSize = 20;

  // Update filters from URL params
  useEffect(() => {
    const status = searchParams.get('status');
    if (status && status !== statusFilter) {
      setStatusFilter(status);
    }
  }, [searchParams, statusFilter]);

  // Fetch jobs based on current filters
  const { data: jobsData, isLoading, error } = useJobs({
    status: statusFilter || undefined,
    mine: user?.role === 'client',
    page: currentPage,
    size: pageSize,
  });

  const bulkDeleteMutation = useBulkDeleteJobs();
  const reprocessMutation = useReprocessJob();

  // Get connection status from global WebSocket
  const { connectionStatus } = useGlobalWebSocket();

  // Client-side filtering and sorting for search term
  const filteredAndSortedJobs = useMemo(() => {
    let jobs = jobsData?.jobs || [];
    
    // Filter by search term
    if (searchTerm) {
      jobs = jobs.filter((job: Job) =>
        job.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
        job.source?.original_filename?.toLowerCase().includes(searchTerm.toLowerCase())
      );
    }

    // Sort jobs
    jobs.sort((a: Job, b: Job) => {
      switch (sortBy) {
        case 'created_at_asc':
          return new Date(a.created_at).getTime() - new Date(b.created_at).getTime();
        case 'created_at_desc':
          return new Date(b.created_at).getTime() - new Date(a.created_at).getTime();
        case 'title_asc':
          return a.title.localeCompare(b.title);
        case 'title_desc':
          return b.title.localeCompare(a.title);
        case 'status_asc':
          return a.status.localeCompare(b.status);
        default:
          return 0;
      }
    });

    return jobs;
  }, [jobsData?.jobs, searchTerm, sortBy]);

  const totalPages = Math.ceil((jobsData?.total || 0) / pageSize);

  // Selection functions
  const toggleJobSelection = (jobId: string) => {
    const newSelected = new Set(selectedJobs);
    if (newSelected.has(jobId)) {
      newSelected.delete(jobId);
    } else {
      newSelected.add(jobId);
    }
    setSelectedJobs(newSelected);
  };

  const selectAll = () => {
    setSelectedJobs(new Set(filteredAndSortedJobs.map(job => job.id)));
  };

  const clearSelection = () => {
    setSelectedJobs(new Set());
    setBulkAction('');
  };

  const handleDeleteConfirm = async () => {
    if (selectedJobs.size === 0) return;

    const jobCount = selectedJobs.size;
    
    try {
      const result = await bulkDeleteMutation.mutateAsync({ 
        job_ids: Array.from(selectedJobs) 
      });
      
      if (result.errors.length > 0) {
        toast.toastOnly.warning(`${result.deleted_count}/${jobCount} jobs deleted. Some errors occurred: ${result.errors.join(', ')}`);
      } else {
        toast.toastOnly.success(`${jobCount} job${jobCount > 1 ? 's' : ''} deleted successfully`);
      }
      
      clearSelection();
      setShowDeleteConfirm(false);
    } catch (error) {
      console.error('Bulk delete failed:', error);
      toast.toastOnly.error('Failed to delete jobs. Please try again.');
    }
  };

  const handleReprocessConfirm = async () => {
    if (selectedJobs.size === 0) return;

    const jobIds = Array.from(selectedJobs);
    let successCount = 0;
    let errorCount = 0;
    const errors: string[] = [];

    try {
      // Process jobs sequentially to avoid overwhelming the system
      for (const jobId of jobIds) {
        try {
          await reprocessMutation.mutateAsync(jobId);
          successCount++;
        } catch (error) {
          errorCount++;
          errors.push(jobId);
          console.error(`Failed to reprocess job ${jobId}:`, error);
        }
      }

      // Show appropriate feedback
      if (successCount === jobIds.length) {
        toast.success(`${successCount} job${successCount > 1 ? 's' : ''} queued for reprocessing`);
      } else if (successCount > 0) {
        toast.warning(`${successCount}/${jobIds.length} jobs queued for reprocessing. ${errorCount} failed.`);
      } else {
        toast.error('Failed to queue jobs for reprocessing. Please try again.');
      }
      
      clearSelection();
      setShowReprocessConfirm(false);
      setBulkAction('');
    } catch (error) {
      console.error('Bulk reprocess failed:', error);
      toast.error('Failed to reprocess jobs. Please try again.');
    }
  };

  // Check if a job is eligible for bulk download
  const isDownloadableStatus = (status: string) => DOWNLOADABLE_STATUSES.includes(status);

  // Get counts for download confirmation modal
  const getDownloadEligibility = () => {
    const selectedJobsList = filteredAndSortedJobs.filter(job => selectedJobs.has(job.id));
    const eligibleJobs = selectedJobsList.filter(job => isDownloadableStatus(job.status));
    const ineligibleJobs = selectedJobsList.filter(job => !isDownloadableStatus(job.status));
    return { selectedJobsList, eligibleJobs, ineligibleJobs };
  };

  const handleBulkDownload = async () => {
    setShowDownloadConfirm(false);

    // Filter to eligible jobs
    const eligibleJobs = filteredAndSortedJobs.filter(
      job => selectedJobs.has(job.id) && isDownloadableStatus(job.status)
    );

    if (eligibleJobs.length === 0) {
      toast.error('No eligible jobs to download');
      return;
    }

    // Collect all files to download
    const allFiles: { url: string; filename: string }[] = [];

    for (const job of eligibleJobs) {
      try {
        const downloads = await apiClient.getJobDownloads(job.id);

        // Sanitize job title for filename
        const safeTitle = job.title.replace(/[^a-zA-Z0-9-_]/g, '_').substring(0, 50);

        // Add source video
        if (downloads.downloads.source_video) {
          allFiles.push({
            url: downloads.downloads.source_video as string,
            filename: `${safeTitle}_source.mp4`
          });
        }

        // Add per-language assets
        for (const [lang, assets] of Object.entries(downloads.downloads)) {
          if (lang === 'source_video') continue;
          const langAssets = assets as Record<string, string>;

          if (langAssets.captions_vtt) {
            allFiles.push({
              url: langAssets.captions_vtt,
              filename: `${safeTitle}_${lang}_captions.vtt`
            });
          }
          if (langAssets.audio_description_vtt) {
            allFiles.push({
              url: langAssets.audio_description_vtt,
              filename: `${safeTitle}_${lang}_audio_description.vtt`
            });
          }
          if (langAssets.audio_description_mp3) {
            allFiles.push({
              url: langAssets.audio_description_mp3,
              filename: `${safeTitle}_${lang}_audio_description.mp3`
            });
          }
        }
      } catch (error) {
        console.error(`Failed to get downloads for job ${job.id}:`, error);
      }
    }

    if (allFiles.length === 0) {
      toast.error('No files available to download');
      return;
    }

    // Sequential download with progress
    setDownloadProgress({ current: 0, total: allFiles.length });

    let successCount = 0;
    for (let i = 0; i < allFiles.length; i++) {
      const { url, filename } = allFiles[i];
      setDownloadProgress({ current: i + 1, total: allFiles.length });

      try {
        // Fetch and trigger download
        const response = await fetch(url);
        const blob = await response.blob();
        const blobUrl = URL.createObjectURL(blob);

        const link = document.createElement('a');
        link.href = blobUrl;
        link.download = filename;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        URL.revokeObjectURL(blobUrl);
        successCount++;

        // Small delay between downloads to avoid overwhelming browser
        await new Promise(resolve => setTimeout(resolve, 500));
      } catch (error) {
        console.error(`Failed to download ${filename}:`, error);
      }
    }

    setDownloadProgress(null);

    if (successCount === allFiles.length) {
      toast.success(`Downloaded ${allFiles.length} files from ${eligibleJobs.length} job(s)`);
    } else {
      toast.warning(`Downloaded ${successCount}/${allFiles.length} files. Some downloads failed.`);
    }

    clearSelection();
  };

  const isAdmin = user?.role === 'admin';
  const isProduction = user?.role === 'production';
  const canManageJobs = isAdmin || isProduction;
  const canBulkDelete = canManageJobs && selectedJobs.size > 0;
  const canBulkReprocess = canManageJobs && selectedJobs.size > 0;

  const getActionButton = (job: Job) => {
    const isReviewer = ['reviewer', 'production', 'admin'].includes(user?.role || '');
    
    switch (job.status) {
      case 'pending_qc':
        return isReviewer ? (
          <Link
            to={`/admin/qc/${job.id}`}
            className="inline-flex items-center px-3 py-1 border border-transparent text-sm font-medium rounded-md text-yellow-700 bg-yellow-100 hover:bg-yellow-200"
          >
            Review
          </Link>
        ) : null;
      case 'pending_final_review':
        return isReviewer ? (
          <Link
            to={`/admin/final/${job.id}`}
            className="inline-flex items-center px-3 py-1 border border-transparent text-sm font-medium rounded-md text-green-700 bg-green-100 hover:bg-green-200"
          >
            Final Review
          </Link>
        ) : null;
      case 'completed':
        return (
          <Link
            to={`/downloads/${job.id}`}
            className="inline-flex items-center px-3 py-1 border border-transparent text-sm font-medium rounded-md text-indigo-700 bg-indigo-100 hover:bg-indigo-200"
          >
            <svg className="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
            </svg>
            Download
          </Link>
        );
      default:
        return null;
    }
  };

  const getConnectionStatusIcon = () => {
    switch (connectionStatus) {
      case 'connected':
        return <span className="inline-block w-2 h-2 bg-green-400 rounded-full" title="Connected - real-time updates enabled" />;
      case 'connecting':
        return <span className="inline-block w-2 h-2 bg-yellow-400 rounded-full animate-pulse" title="Connecting..." />;
      case 'disconnected':
        return <span className="inline-block w-2 h-2 bg-gray-400 rounded-full" title="Disconnected - using cached data" />;
      case 'error':
        return <span className="inline-block w-2 h-2 bg-red-400 rounded-full" title="Connection error" />;
      default:
        return null;
    }
  };

  return (
    <div className="container mx-auto px-4 py-8">
      {/* Header */}
      <div className="flex justify-between items-center mb-8">
        <div>
          <div className="flex items-center gap-3">
            <h1 className="text-3xl font-bold text-gray-900">All Jobs</h1>
            {getConnectionStatusIcon()}
          </div>
          <p className="text-gray-600 mt-1">
            {user?.role === 'client' ? 'Your video processing jobs' : 'System-wide job management'}
          </p>
        </div>
        
        {['client', 'production', 'admin'].includes(user?.role || '') && (
          <Link
            to="/jobs/new"
            className="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition-colors inline-flex items-center"
          >
            <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
            </svg>
            New Job
          </Link>
        )}
      </div>

      {/* Filters and Search */}
      <div className="bg-white rounded-lg border border-gray-200 p-6 mb-6">
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
          {/* Search */}
          <div className="md:col-span-2">
            <label htmlFor="search" className="block text-sm font-medium text-gray-700 mb-2">
              Search Jobs
            </label>
            <input
              type="text"
              id="search"
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              placeholder="Search by title or filename..."
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
          </div>

          {/* Status Filter */}
          <div>
            <label htmlFor="status" className="block text-sm font-medium text-gray-700 mb-2">
              Status
            </label>
            <select
              id="status"
              value={statusFilter}
              onChange={(e) => {
                setStatusFilter(e.target.value);
                setCurrentPage(1);
              }}
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
              {STATUS_OPTIONS.map((option) => (
                <option key={option.value} value={option.value}>
                  {option.label}
                </option>
              ))}
            </select>
          </div>

          {/* Sort */}
          <div>
            <label htmlFor="sort" className="block text-sm font-medium text-gray-700 mb-2">
              Sort By
            </label>
            <select
              id="sort"
              value={sortBy}
              onChange={(e) => setSortBy(e.target.value)}
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
              {SORT_OPTIONS.map((option) => (
                <option key={option.value} value={option.value}>
                  {option.label}
                </option>
              ))}
            </select>
          </div>
        </div>
      </div>

      {/* Bulk Actions - Only show for production/admin users */}
      {canManageJobs && filteredAndSortedJobs.length > 0 && (
        <div className="bg-white border border-gray-200 rounded-lg p-4 mb-4">
          <div className="flex flex-wrap items-center gap-4">
            <div className="flex items-center space-x-2">
              <input
                type="checkbox"
                checked={selectedJobs.size === filteredAndSortedJobs.length}
                onChange={() => selectedJobs.size === filteredAndSortedJobs.length ? clearSelection() : selectAll()}
                className="rounded border-gray-300"
              />
              <span className="text-sm text-gray-700">
                {selectedJobs.size > 0 ? `${selectedJobs.size} selected` : 'Select all'}
              </span>
            </div>

            {(canBulkDelete || canBulkReprocess) && (
              <>
                <select
                  value={bulkAction}
                  onChange={(e) => setBulkAction(e.target.value as 'delete' | 'reprocess' | 'download' | '')}
                  className="text-sm border border-gray-300 rounded px-2 py-1"
                >
                  <option value="">Choose action...</option>
                  <option value="delete">Delete Selected</option>
                  <option value="reprocess">Reprocess Selected</option>
                  <option value="download">Download All Files</option>
                </select>

                {bulkAction === 'delete' && (
                  <button
                    onClick={() => setShowDeleteConfirm(true)}
                    disabled={bulkDeleteMutation.isPending}
                    className="px-3 py-1 text-sm bg-red-600 text-white rounded hover:bg-red-700 disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    {bulkDeleteMutation.isPending ? 'Deleting...' : 'Delete'}
                  </button>
                )}

                {bulkAction === 'reprocess' && (
                  <button
                    onClick={() => setShowReprocessConfirm(true)}
                    disabled={reprocessMutation.isPending}
                    className="px-3 py-1 text-sm bg-orange-600 text-white rounded hover:bg-orange-700 disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    {reprocessMutation.isPending ? 'Reprocessing...' : 'Reprocess'}
                  </button>
                )}

                {bulkAction === 'download' && (
                  <button
                    onClick={() => setShowDownloadConfirm(true)}
                    disabled={downloadProgress !== null}
                    className="px-3 py-1 text-sm bg-blue-600 text-white rounded hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    Download Files
                  </button>
                )}

                <button
                  onClick={clearSelection}
                  className="px-3 py-1 text-sm text-gray-600 hover:text-gray-800"
                >
                  Clear
                </button>
              </>
            )}
          </div>
        </div>
      )}

      {/* Results Summary */}
      <div className="flex justify-between items-center mb-4">
        <p className="text-sm text-gray-600">
          Showing {filteredAndSortedJobs.length} of {jobsData?.total || 0} jobs
        </p>
        {searchTerm && (
          <button
            onClick={() => setSearchTerm('')}
            className="text-sm text-blue-600 hover:text-blue-700"
          >
            Clear search
          </button>
        )}
      </div>

      {/* Jobs List */}
      <div className="bg-white rounded-lg border border-gray-200">
        {isLoading ? (
          <div className="p-6">
            <div className="animate-pulse space-y-4">
              {[...Array(5)].map((_, i) => (
                <div key={i} className="h-20 bg-gray-200 rounded"></div>
              ))}
            </div>
          </div>
        ) : error ? (
          <div className="p-6 text-center text-red-600">
            Error loading jobs. Please try again.
          </div>
        ) : filteredAndSortedJobs.length === 0 ? (
          <div className="p-8 text-center text-gray-500">
            {searchTerm ? (
              <>
                <p>No jobs found matching "{searchTerm}"</p>
                <button
                  onClick={() => setSearchTerm('')}
                  className="mt-2 text-blue-600 hover:text-blue-700"
                >
                  Clear search to see all jobs
                </button>
              </>
            ) : (
              <p>
                No jobs found.{' '}
                {['client', 'production', 'admin'].includes(user?.role || '') && (
                  <Link to="/jobs/new" className="text-blue-600 hover:text-blue-700">
                    Upload your first video to get started!
                  </Link>
                )}
              </p>
            )}
          </div>
        ) : (
          <>
            <div className="divide-y divide-gray-200">
              {filteredAndSortedJobs.map((job: Job) => (
                <div key={job.id} className="px-6 py-4 hover:bg-gray-50">
                  <div className="flex items-center">
                    {/* Selection checkbox - for production/admin users */}
                    {canManageJobs && (
                      <input
                        type="checkbox"
                        checked={selectedJobs.has(job.id)}
                        onChange={() => toggleJobSelection(job.id)}
                        className="mr-4 rounded border-gray-300"
                        onClick={(e) => e.stopPropagation()}
                      />
                    )}
                    
                    <div className="flex-1 flex items-center justify-between">
                      <div className="flex-1 min-w-0">
                        <Link
                          to={`/jobs/${job.id}`}
                          className="block hover:text-blue-600"
                        >
                          <h3 className="text-lg font-medium text-gray-900 truncate">
                            {job.title}
                          </h3>
                          <div className="mt-1 flex items-center space-x-4 text-sm text-gray-500">
                            <span>{job.source?.original_filename || 'Unknown file'}</span>
                            <span>•</span>
                            <span>Created {formatDistanceToNow(new Date(job.created_at))} ago</span>
                            {job.requested_outputs?.languages && job.requested_outputs.languages.length > 0 && (
                              <>
                                <span>•</span>
                                <span>{job.requested_outputs.languages.length} languages</span>
                              </>
                            )}
                          </div>
                        </Link>
                      </div>
                      
                      <div className="flex items-center space-x-3 ml-4">
                        <StatusBadge status={job.status} />
                        {getActionButton(job)}
                      </div>
                    </div>
                  </div>
                </div>
              ))}
            </div>

            {/* Pagination */}
            {totalPages > 1 && (
              <div className="px-6 py-3 bg-gray-50 border-t border-gray-200 flex items-center justify-between">
                <p className="text-sm text-gray-600">
                  Page {currentPage} of {totalPages}
                </p>
                <div className="flex space-x-2">
                  <button
                    onClick={() => setCurrentPage(prev => Math.max(1, prev - 1))}
                    disabled={currentPage === 1}
                    className="px-3 py-1 text-sm border border-gray-300 rounded hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    Previous
                  </button>
                  <button
                    onClick={() => setCurrentPage(prev => Math.min(totalPages, prev + 1))}
                    disabled={currentPage === totalPages}
                    className="px-3 py-1 text-sm border border-gray-300 rounded hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    Next
                  </button>
                </div>
              </div>
            )}
          </>
        )}
      </div>

      {/* Delete Confirmation Modal */}
      {showDeleteConfirm && (
        <div className="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50">
          <div className="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white">
            <div className="mt-3 text-center">
              <div className="mx-auto flex items-center justify-center h-12 w-12 rounded-full bg-red-100">
                <svg 
                  className="h-6 w-6 text-red-600" 
                  fill="none" 
                  stroke="currentColor" 
                  viewBox="0 0 24 24"
                >
                  <path 
                    strokeLinecap="round" 
                    strokeLinejoin="round" 
                    strokeWidth="2" 
                    d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L4.082 16.5c-.77.833.192 2.5 1.732 2.5z"
                  />
                </svg>
              </div>
              <h3 className="text-lg font-medium text-gray-900 mt-4">
                Delete {selectedJobs.size} Job{selectedJobs.size !== 1 ? 's' : ''}?
              </h3>
              <div className="mt-2 px-7 py-3">
                <p className="text-sm text-gray-500">
                  Are you sure you want to delete the selected job{selectedJobs.size !== 1 ? 's' : ''}? 
                  This will permanently remove:
                </p>
                <ul className="mt-2 text-sm text-gray-500 text-left">
                  <li>• All video files and assets</li>
                  <li>• Generated captions and audio descriptions</li>
                  <li>• Translation files</li>
                  <li>• Processing history</li>
                </ul>
                <p className="mt-2 text-sm text-red-600 font-medium">
                  This action cannot be undone.
                </p>
              </div>
              <div className="items-center px-4 py-3 flex flex-col space-y-2 sm:flex-row sm:space-y-0 sm:space-x-3">
                <button
                  onClick={() => setShowDeleteConfirm(false)}
                  className="px-4 py-2 bg-gray-500 text-white text-base font-medium rounded-md w-full shadow-sm hover:bg-gray-600 focus:outline-none focus:ring-2 focus:ring-gray-300 sm:w-auto"
                >
                  Cancel
                </button>
                <button
                  onClick={handleDeleteConfirm}
                  disabled={bulkDeleteMutation.isPending}
                  className="px-4 py-2 bg-red-600 text-white text-base font-medium rounded-md w-full shadow-sm hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-red-300 disabled:opacity-50 sm:w-auto"
                >
                  {bulkDeleteMutation.isPending ? 'Deleting...' : 'Delete'}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Reprocess Confirmation Modal */}
      {showReprocessConfirm && (
        <div className="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50">
          <div className="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white">
            <div className="mt-3 text-center">
              <div className="mx-auto flex items-center justify-center h-12 w-12 rounded-full bg-orange-100">
                <svg 
                  className="h-6 w-6 text-orange-600" 
                  fill="none" 
                  stroke="currentColor" 
                  viewBox="0 0 24 24"
                >
                  <path 
                    strokeLinecap="round" 
                    strokeLinejoin="round" 
                    strokeWidth="2" 
                    d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"
                  />
                </svg>
              </div>
              <h3 className="text-lg font-medium text-gray-900 mt-4">
                Reprocess {selectedJobs.size} Job{selectedJobs.size !== 1 ? 's' : ''}?
              </h3>
              <div className="mt-2 px-7 py-3">
                <p className="text-sm text-gray-500">
                  This will reset the selected job{selectedJobs.size !== 1 ? 's' : ''} and restart processing from the beginning.
                </p>
                <div className="mt-3 p-3 bg-yellow-50 rounded-md">
                  <div className="text-sm text-yellow-800">
                    <strong>⚠️ Warning:</strong> This will:
                  </div>
                  <ul className="mt-2 text-sm text-yellow-700 text-left">
                    <li>• Reset job status to "created"</li>
                    <li>• Restart AI processing from scratch</li>
                    <li>• Overwrite existing results</li>
                    <li>• Require re-review and re-approval</li>
                  </ul>
                </div>
                <p className="mt-2 text-sm text-orange-600 font-medium">
                  Use this only for stuck or failed jobs.
                </p>
              </div>
              <div className="items-center px-4 py-3 flex flex-col space-y-2 sm:flex-row sm:space-y-0 sm:space-x-3">
                <button
                  onClick={() => setShowReprocessConfirm(false)}
                  className="px-4 py-2 bg-gray-500 text-white text-base font-medium rounded-md w-full shadow-sm hover:bg-gray-600 focus:outline-none focus:ring-2 focus:ring-gray-300 sm:w-auto"
                >
                  Cancel
                </button>
                <button
                  onClick={handleReprocessConfirm}
                  disabled={reprocessMutation.isPending}
                  className="px-4 py-2 bg-orange-600 text-white text-base font-medium rounded-md w-full shadow-sm hover:bg-orange-700 focus:outline-none focus:ring-2 focus:ring-orange-300 disabled:opacity-50 sm:w-auto"
                >
                  {reprocessMutation.isPending ? 'Reprocessing...' : 'Reprocess'}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Download Confirmation Modal */}
      {showDownloadConfirm && (() => {
        const { eligibleJobs, ineligibleJobs } = getDownloadEligibility();
        return (
          <div className="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50">
            <div className="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white">
              <div className="mt-3 text-center">
                <div className="mx-auto flex items-center justify-center h-12 w-12 rounded-full bg-blue-100">
                  <svg
                    className="h-6 w-6 text-blue-600"
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      strokeWidth="2"
                      d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"
                    />
                  </svg>
                </div>
                <h3 className="text-lg font-medium text-gray-900 mt-4">
                  Download All Files
                </h3>
                <div className="mt-2 px-4 py-3">
                  <p className="text-sm text-gray-700">
                    You have selected <span className="font-semibold">{selectedJobs.size}</span> job{selectedJobs.size !== 1 ? 's' : ''}.{' '}
                    <span className="font-semibold text-blue-600">{eligibleJobs.length}</span>{' '}
                    {eligibleJobs.length === 1 ? 'is' : 'are'} eligible for download.
                  </p>

                  {ineligibleJobs.length > 0 && (
                    <div className="mt-3 p-3 bg-yellow-50 rounded-md">
                      <p className="text-sm text-yellow-800">
                        <strong>{ineligibleJobs.length}</strong> job{ineligibleJobs.length !== 1 ? 's are' : ' is'} not in approved/completed status and will be skipped.
                      </p>
                    </div>
                  )}

                  {eligibleJobs.length > 0 && (
                    <div className="mt-3 text-left">
                      <p className="text-sm text-gray-600 mb-2">Files to be downloaded per eligible job:</p>
                      <ul className="text-sm text-gray-500 space-y-1">
                        <li>• Source video (MP4)</li>
                        <li>• Captions (VTT) for all languages</li>
                        <li>• Audio descriptions (VTT + MP3) for all languages</li>
                      </ul>
                    </div>
                  )}
                </div>
                <div className="items-center px-4 py-3 flex flex-col space-y-2 sm:flex-row sm:space-y-0 sm:space-x-3">
                  <button
                    onClick={() => setShowDownloadConfirm(false)}
                    className="px-4 py-2 bg-gray-500 text-white text-base font-medium rounded-md w-full shadow-sm hover:bg-gray-600 focus:outline-none focus:ring-2 focus:ring-gray-300 sm:w-auto"
                  >
                    Cancel
                  </button>
                  <button
                    onClick={handleBulkDownload}
                    disabled={eligibleJobs.length === 0}
                    className="px-4 py-2 bg-blue-600 text-white text-base font-medium rounded-md w-full shadow-sm hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-300 disabled:opacity-50 disabled:cursor-not-allowed sm:w-auto"
                  >
                    Download
                  </button>
                </div>
              </div>
            </div>
          </div>
        );
      })()}

      {/* Download Progress Indicator */}
      {downloadProgress && (
        <div className="fixed bottom-4 right-4 bg-white rounded-lg shadow-lg p-4 z-50 border border-gray-200">
          <div className="flex items-center gap-3">
            <div className="animate-spin h-5 w-5 border-2 border-blue-600 border-t-transparent rounded-full" />
            <span className="text-sm text-gray-700">
              Downloading {downloadProgress.current} of {downloadProgress.total} files...
            </span>
          </div>
        </div>
      )}
    </div>
  );
}