import { useState } from 'react';
import { Link } from 'react-router-dom';
import { useJobs, useApproveEnglish, useRejectJob, useBulkApproveJobs } from '../../hooks/useJob';
import { StatusBadge } from '../../components/StatusBadge';
import { useToastContext } from '../../contexts/ToastContext';

export function QCList() {
  const [selectedJobs, setSelectedJobs] = useState<Set<string>>(new Set());
  const [bulkAction, setBulkAction] = useState<'approve' | 'reject' | ''>('');
  const [bulkNotes, setBulkNotes] = useState('');
  const toast = useToastContext();

  const { data: jobsResponse, isLoading, error } = useJobs({
    status: 'pending_qc'
  });
  const approveEnglishMutation = useApproveEnglish();
  const rejectJobMutation = useRejectJob();
  const bulkApproveMutation = useBulkApproveJobs();

  if (isLoading) {
    return (
      <div className="container mx-auto px-4 py-8">
        <div className="animate-pulse">
          <div className="h-8 bg-gray-200 rounded w-1/4 mb-8"></div>
          <div className="space-y-4">
            {[...Array(5)].map((_, i) => (
              <div key={i} className="h-16 bg-gray-200 rounded"></div>
            ))}
          </div>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="container mx-auto px-4 py-8">
        <h1 className="text-3xl font-bold text-gray-900 mb-8">Quality Control Queue</h1>
        <div className="bg-red-50 border border-red-200 rounded-md p-4">
          <p className="text-red-600">Failed to load QC queue. Please try again.</p>
        </div>
      </div>
    );
  }

  const jobs = jobsResponse?.jobs || [];

  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(jobs.map(job => job.id)));
  };

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

  const handleBulkAction = async () => {
    if (!bulkAction || selectedJobs.size === 0) return;
    if (bulkAction === 'reject' && !bulkNotes.trim()) {
      toast.toastOnly.error('Please provide notes for rejection');
      return;
    }

    await executeBulkAction();
  };

  const executeBulkAction = async () => {
    const jobCount = selectedJobs.size;
    const actionText = bulkAction === 'approve' ? 'approved' : 'rejected';

    try {
      if (bulkAction === 'approve') {
        // Use bulk approve API
        const result = await bulkApproveMutation.mutateAsync({
          job_ids: Array.from(selectedJobs),
          notes: bulkNotes || undefined,
        });

        if (result.errors.length > 0) {
          toast.toastOnly.warning(`${result.approved_count} jobs approved, ${result.errors.length} failed`);
        } else {
          toast.toastOnly.success(`${result.approved_count} job${result.approved_count > 1 ? 's' : ''} approved successfully`);
        }
      } else {
        // Handle rejection with individual calls
        const promises = Array.from(selectedJobs).map(jobId =>
          rejectJobMutation.mutateAsync({ id: jobId, notes: bulkNotes })
        );
        await Promise.all(promises);
        toast.toastOnly.success(`${jobCount} job${jobCount > 1 ? 's' : ''} ${actionText} successfully`);
      }

      clearSelection();
      setBulkAction('');
      setBulkNotes('');
    } catch (error) {
      console.error('Bulk action failed:', error);
      toast.toastOnly.error(`Failed to ${bulkAction} selected jobs. Some may have been processed.`);
    }
  };

  const isProcessing = approveEnglishMutation.isPending || rejectJobMutation.isPending || bulkApproveMutation.isPending;

  return (
    <div className="container mx-auto px-4 py-8">
      <div className="flex justify-between items-center mb-6">
        <h1 className="text-3xl font-bold text-gray-900">Quality Control Queue</h1>
        <div className="text-sm text-gray-500">
          {jobs.length} job{jobs.length !== 1 ? 's' : ''} pending review
        </div>
      </div>

      {/* Bulk Actions */}
      {jobs.length > 0 && (
        <div className="bg-white border border-gray-200 rounded-lg p-4 mb-6">
          <div className="flex flex-wrap items-center gap-4">
            <div className="flex items-center space-x-2">
              <input
                type="checkbox"
                checked={selectedJobs.size === jobs.length}
                onChange={() => selectedJobs.size === jobs.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>

            {selectedJobs.size > 0 && (
              <>
                <select
                  value={bulkAction}
                  onChange={(e) => setBulkAction(e.target.value as 'approve' | 'reject' | '')}
                  className="text-sm border border-gray-300 rounded px-2 py-1"
                >
                  <option value="">Choose action...</option>
                  <option value="approve">Approve Selected</option>
                  <option value="reject">Reject Selected</option>
                </select>

                {bulkAction && (
                  <input
                    type="text"
                    placeholder={bulkAction === 'reject' ? 'Required: Rejection notes' : 'Optional notes'}
                    value={bulkNotes}
                    onChange={(e) => setBulkNotes(e.target.value)}
                    className="text-sm border border-gray-300 rounded px-2 py-1 flex-1 min-w-48"
                  />
                )}

                <button
                  onClick={handleBulkAction}
                  disabled={!bulkAction || isProcessing || (bulkAction === 'reject' && !bulkNotes.trim())}
                  className="px-3 py-1 text-sm bg-blue-600 text-white rounded hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {isProcessing ? 'Processing...' : 'Apply'}
                </button>

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

      {jobs.length === 0 ? (
        <div className="text-center py-12">
          <div className="text-gray-400 mb-4">
            <svg className="mx-auto h-12 w-12" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
          </div>
          <h3 className="text-lg font-medium text-gray-900 mb-2">No jobs pending review</h3>
          <p className="text-gray-500">All jobs have been reviewed or are still processing.</p>
        </div>
      ) : (
        <div className="bg-white shadow overflow-hidden sm:rounded-md">
          <ul className="divide-y divide-gray-200">
            {jobs.map((job) => (
              <li key={job.id}>
                <div className="flex items-center px-6 py-4 hover:bg-gray-50">
                  <input
                    type="checkbox"
                    checked={selectedJobs.has(job.id)}
                    onChange={() => toggleJobSelection(job.id)}
                    className="mr-4 rounded border-gray-300"
                    onClick={(e) => e.stopPropagation()}
                  />
                  
                  <Link
                    to={`/admin/qc/${job.id}`}
                    className="flex-1 block"
                  >
                    <div className="flex items-center justify-between">
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center justify-between">
                        <h3 className="text-lg font-medium text-gray-900 truncate">
                          {job.title}
                        </h3>
                        <StatusBadge status={job.status} />
                      </div>
                      
                      <div className="mt-2 flex items-center text-sm text-gray-500">
                        <span className="mr-4">
                          Source: {job.source.filename}
                        </span>
                        {job.source.duration_s && (
                          <span className="mr-4">
                            Duration: {Math.round(job.source.duration_s)}s
                          </span>
                        )}
                        <span>
                          Created: {new Date(job.created_at).toLocaleDateString()}
                        </span>
                      </div>
                      
                      <div className="mt-2 flex flex-wrap gap-2">
                        {job.requested_outputs.captions_vtt && (
                          <span className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                            Captions
                          </span>
                        )}
                        {job.requested_outputs.audio_description_vtt && (
                          <span className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-purple-100 text-purple-800">
                            AD Script
                          </span>
                        )}
                        {job.requested_outputs.audio_description_mp3 && (
                          <span className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-green-100 text-green-800">
                            AD Audio
                          </span>
                        )}
                        {job.requested_outputs.languages.length > 0 && (
                          <span className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-orange-100 text-orange-800">
                            {job.requested_outputs.languages.length} language{job.requested_outputs.languages.length !== 1 ? 's' : ''}
                          </span>
                        )}
                      </div>
                    </div>
                    
                    <div className="ml-4 flex-shrink-0">
                      <svg className="h-5 w-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                      </svg>
                    </div>
                  </div>
                  </Link>
                </div>
              </li>
            ))}
          </ul>
        </div>
      )}
    </div>
  );
}