import { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { useJob, useApproveEnglish, useRejectJob, useJobVttContent, useUpdateJobVtt, useJobDownloads, useAdjustVttTiming } from '../../hooks/useJob';
import { StatusBadge } from '../../components/StatusBadge';
import { VttEditor } from '../../components/VttEditor/VttEditor';
import { VideoWithCaptions } from '../../components/VideoWithCaptions';
import { VoiceSelector } from '../../components/VoiceSelector';
import { useToastContext } from '../../contexts/ToastContext';
import type { TTSPreferences } from '../../types/api';

export function QCDetail() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const toast = useToastContext();
  const { data: job, isLoading, error } = useJob(id!);
  // Get source language from job (default to 'en' for backwards compatibility)
  const sourceLanguage = job?.source?.language || 'en';
  const { data: vttContent, isLoading: vttLoading } = useJobVttContent(id!, sourceLanguage);
  const { data: downloads } = useJobDownloads(id!);
  const approveEnglishMutation = useApproveEnglish();
  const rejectJobMutation = useRejectJob();
  const updateVttMutation = useUpdateJobVtt();
  const adjustTimingMutation = useAdjustVttTiming();
  
  const [reviewNotes, setReviewNotes] = useState('');
  const [showRejectForm, setShowRejectForm] = useState(false);
  const [captionsVtt, setCaptionsVtt] = useState('');
  const [adVtt, setAdVtt] = useState('');
  const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);
  const [viewMode, setViewMode] = useState<'side-by-side' | 'video-only' | 'editor-only'>('side-by-side');
  const [showTimingAdjustment, setShowTimingAdjustment] = useState(false);
  const [timingOffset, setTimingOffset] = useState(0);
  const [adjustCaptions, setAdjustCaptions] = useState(true);
  const [adjustAudioDescription, setAdjustAudioDescription] = useState(true);
  const [showVoiceSettings, setShowVoiceSettings] = useState(false);
  const [ttsPreferences, setTtsPreferences] = useState<TTSPreferences>({
    provider: 'gemini',
    default_voice: 'Kore',
    voices_per_language: {},
    model: 'flash',
    speed: 1.0,
    style_preset: 'neutral',
    custom_style_prompt: undefined
  });

  const isProcessing = approveEnglishMutation.isPending || rejectJobMutation.isPending || updateVttMutation.isPending || adjustTimingMutation.isPending;

  // Get video URL from downloads
  const videoUrl = typeof downloads?.downloads?.source_video === 'string'
    ? downloads.downloads.source_video
    : '';

  // Load VTT content when fetched
  useEffect(() => {
    if (vttContent) {
      setCaptionsVtt(vttContent.captions_vtt || '');
      setAdVtt(vttContent.audio_description_vtt || '');
      setHasUnsavedChanges(false);
    }
  }, [vttContent]);

  // Initialize TTS preferences from job when loaded
  useEffect(() => {
    if (job?.requested_outputs?.tts_preferences) {
      setTtsPreferences(job.requested_outputs.tts_preferences);
    }
  }, [job]);

  // Keyboard shortcuts
  useEffect(() => {
    const handleKeyPress = (event: KeyboardEvent) => {
      // Only handle shortcuts when not typing in input fields
      if (event.target instanceof HTMLInputElement || event.target instanceof HTMLTextAreaElement) {
        return;
      }

      switch (event.key.toLowerCase()) {
        case 'a':
          if (event.ctrlKey || event.metaKey) return; // Don't interfere with Ctrl+A
          event.preventDefault();
          if (!isProcessing) {
            handleApprove();
          }
          break;
        case 'r':
          if (event.ctrlKey || event.metaKey) return; // Don't interfere with Ctrl+R
          event.preventDefault();
          if (!isProcessing && !showRejectForm) {
            setShowRejectForm(true);
          }
          break;
        case 's':
          if (event.ctrlKey || event.metaKey) {
            event.preventDefault();
            if (hasUnsavedChanges && !isProcessing) {
              saveVttChanges();
            }
          }
          break;
        case 'escape':
          if (showRejectForm) {
            setShowRejectForm(false);
          }
          break;
        case '1':
          setViewMode('side-by-side');
          break;
        case '2':
          setViewMode('video-only');
          break;
        case '3':
          setViewMode('editor-only');
          break;
      }
    };

    document.addEventListener('keydown', handleKeyPress);
    return () => document.removeEventListener('keydown', handleKeyPress);
  }, [isProcessing, showRejectForm, hasUnsavedChanges]);

  const saveVttChanges = async () => {
    if (!id || !hasUnsavedChanges) return;

    try {
      await updateVttMutation.mutateAsync({
        id,
        data: {
          captions_vtt: captionsVtt,
          audio_description_vtt: adVtt,
          language: sourceLanguage  // Use source language instead of hardcoded 'en'
        }
      });
      setHasUnsavedChanges(false);
      toast.toastOnly.success('VTT content saved successfully');
    } catch (error) {
      console.error('Failed to save VTT changes:', error);
      toast.toastOnly.error('Failed to save VTT content. Please try again.');
    }
  };

  const handleCaptionsChange = (content: string) => {
    setCaptionsVtt(content);
    setHasUnsavedChanges(true);
  };

  const handleAdChange = (content: string) => {
    setAdVtt(content);
    setHasUnsavedChanges(true);
  };

  const handleApprove = async () => {
    if (!id) return;

    // Save any pending changes first
    if (hasUnsavedChanges) {
      await saveVttChanges();
    }

    try {
      // Only pass TTS preferences if MP3 generation is requested
      const ttsPrefsToSend = job?.requested_outputs?.audio_description_mp3 ? ttsPreferences : undefined;

      await approveEnglishMutation.mutateAsync({
        id,
        notes: reviewNotes,
        tts_preferences: ttsPrefsToSend
      });
      toast.toastOnly.success('Job approved successfully');
      navigate('/admin/qc');
    } catch (error) {
      console.error('Approval failed:', error);
      toast.toastOnly.error('Failed to approve job. Please try again.');
    }
  };

  const handleReject = async () => {
    if (!id || !reviewNotes.trim()) return;
    
    try {
      await rejectJobMutation.mutateAsync({ 
        id, 
        notes: reviewNotes 
      });
      toast.toastOnly.success('Job rejected and returned for revision');
      navigate('/admin/qc');
    } catch (error) {
      console.error('Rejection failed:', error);
      toast.toastOnly.error('Failed to reject job. Please try again.');
    }
  };

  const handleTimingAdjustment = async () => {
    if (!id || timingOffset === 0) return;

    try {
      await adjustTimingMutation.mutateAsync({
        id,
        offsetSeconds: timingOffset,
        language: sourceLanguage,  // Use source language instead of hardcoded 'en'
        adjustCaptions,
        adjustAudioDescription,
      });
      toast.toastOnly.success(`Timing adjusted by ${timingOffset > 0 ? '+' : ''}${timingOffset} seconds`);
      setShowTimingAdjustment(false);
      setTimingOffset(0);
    } catch (error) {
      console.error('Timing adjustment failed:', error);
      toast.toastOnly.error('Failed to adjust timing. Please try again.');
    }
  };

  if (isLoading || vttLoading) {
    return (
      <div className="container mx-auto px-4 py-8">
        <div className="animate-pulse">
          <div className="h-8 bg-gray-200 rounded w-1/3 mb-8"></div>
          <div className="space-y-4">
            <div className="h-64 bg-gray-200 rounded"></div>
            <div className="h-64 bg-gray-200 rounded"></div>
          </div>
        </div>
      </div>
    );
  }

  if (error || !job) {
    return (
      <div className="container mx-auto px-4 py-8">
        <h1 className="text-3xl font-bold text-gray-900 mb-8">Quality Control Detail</h1>
        <div className="bg-red-50 border border-red-200 rounded-md p-4">
          <p className="text-red-600">Job not found or failed to load.</p>
        </div>
      </div>
    );
  }

  return (
    <div className="container mx-auto px-4 py-8 max-w-6xl">
      {/* Header */}
      <div className="flex justify-between items-start mb-8">
        <div>
          <h1 className="text-3xl font-bold text-gray-900 mb-2">{job.title}</h1>
          <div className="flex items-center gap-4 text-sm text-gray-500">
            <StatusBadge status={job.status} />
            <span>Source: {job.source.filename}</span>
            <span>Language: {sourceLanguage.toUpperCase()}</span>
            {job.source.duration_s && (
              <span>Duration: {Math.round(job.source.duration_s)}s</span>
            )}
          </div>
        </div>
        
        <button
          onClick={() => navigate('/admin/qc')}
          className="text-gray-500 hover:text-gray-700"
        >
          ← Back to Queue
        </button>
      </div>

      {/* AI Confidence Score */}
      {job.ai?.confidence && (
        <div className="mb-6 p-4 bg-blue-50 border border-blue-200 rounded-md">
          <div className="flex items-center justify-between">
            <span className="font-medium text-blue-900">AI Confidence Score</span>
            <span className="text-blue-700 font-mono">
              {(job.ai.confidence * 100).toFixed(1)}%
            </span>
          </div>
        </div>
      )}

      {/* View Mode Toggle and Shortcuts */}
      <div className="mb-6 flex items-center justify-between">
        <div className="flex items-center space-x-4">
          <span className="text-sm font-medium text-gray-700">View Mode:</span>
          <div className="flex rounded-lg border border-gray-300">
            <button
              onClick={() => setViewMode('side-by-side')}
              className={`px-3 py-1 text-sm rounded-l-lg ${
                viewMode === 'side-by-side'
                  ? 'bg-blue-600 text-white'
                  : 'bg-white text-gray-700 hover:bg-gray-50'
              }`}
            >
              Side by Side <span className="text-xs opacity-75">(1)</span>
            </button>
            <button
              onClick={() => setViewMode('video-only')}
              className={`px-3 py-1 text-sm border-l border-gray-300 ${
                viewMode === 'video-only'
                  ? 'bg-blue-600 text-white'
                  : 'bg-white text-gray-700 hover:bg-gray-50'
              }`}
            >
              Video Only <span className="text-xs opacity-75">(2)</span>
            </button>
            <button
              onClick={() => setViewMode('editor-only')}
              className={`px-3 py-1 text-sm rounded-r-lg border-l border-gray-300 ${
                viewMode === 'editor-only'
                  ? 'bg-blue-600 text-white'
                  : 'bg-white text-gray-700 hover:bg-gray-50'
              }`}
            >
              Editor Only <span className="text-xs opacity-75">(3)</span>
            </button>
          </div>
        </div>
        
        <div className="text-xs text-gray-500">
          <span className="font-medium">Shortcuts:</span> A=Approve, R=Reject, Ctrl+S=Save
        </div>
      </div>

      {/* Video Preview */}
      {(viewMode === 'side-by-side' || viewMode === 'video-only') && (
        <div className="mb-8">
          <div className="bg-white border border-gray-200 rounded-lg p-6">
            <h3 className="text-lg font-medium text-gray-900 mb-4">Video Preview</h3>
            {videoUrl ? (
              <VideoWithCaptions
                videoUrl={videoUrl}
                captionsVtt={captionsVtt}
                audioDescriptionVtt={adVtt}
                sourceLanguage={sourceLanguage}
              />
            ) : (
              <div className="text-center py-8 text-gray-500">
                <svg className="w-12 h-12 mx-auto mb-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z" />
                </svg>
                <p>Video preview will be available once processing begins</p>
              </div>
            )}
          </div>
        </div>
      )}

      {/* VTT Editors */}
      {viewMode !== 'video-only' && (
        <div className={`mb-8 ${viewMode === 'side-by-side' ? 'grid grid-cols-1 lg:grid-cols-2 gap-6' : ''}`}>
          {job.requested_outputs.captions_vtt && (
            <VttEditor
              vttContent={captionsVtt}
              onChange={handleCaptionsChange}
              title="Closed Captions"
              readOnly={isProcessing}
            />
          )}
          
          {job.requested_outputs.audio_description_vtt && (
            <VttEditor
              vttContent={adVtt}
              onChange={handleAdChange}
              title="Audio Description"
              readOnly={isProcessing}
            />
          )}
        </div>
      )}

      {/* Timing Adjustment */}
      <div className="mb-6 p-4 bg-gray-50 border border-gray-200 rounded-lg">
        <div className="flex items-center justify-between mb-4">
          <h3 className="text-lg font-medium text-gray-900">VTT Timing Adjustment</h3>
          <button
            onClick={() => setShowTimingAdjustment(!showTimingAdjustment)}
            className="px-3 py-1 text-sm bg-blue-600 text-white rounded-md hover:bg-blue-700"
          >
            {showTimingAdjustment ? 'Hide' : 'Adjust Timing'}
          </button>
        </div>
        
        {showTimingAdjustment && (
          <div className="space-y-4">
            <div className="text-sm text-gray-600">
              Move captions forward or backward in time if they're not synchronized with the video.
            </div>
            
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Time Offset (seconds)
                </label>
                <div className="flex items-center space-x-2">
                  <input
                    type="number"
                    step="0.1"
                    min="-30"
                    max="30"
                    value={timingOffset}
                    onChange={(e) => setTimingOffset(parseFloat(e.target.value) || 0)}
                    className="w-24 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                    disabled={isProcessing}
                  />
                  <div className="flex space-x-1">
                    <button
                      onClick={() => setTimingOffset(prev => Math.max(-30, prev - 0.5))}
                      className="px-2 py-1 text-sm bg-gray-200 text-gray-700 rounded hover:bg-gray-300"
                      disabled={isProcessing}
                    >
                      -0.5s
                    </button>
                    <button
                      onClick={() => setTimingOffset(prev => Math.min(30, prev + 0.5))}
                      className="px-2 py-1 text-sm bg-gray-200 text-gray-700 rounded hover:bg-gray-300"
                      disabled={isProcessing}
                    >
                      +0.5s
                    </button>
                    <button
                      onClick={() => setTimingOffset(prev => Math.max(-30, prev - 1))}
                      className="px-2 py-1 text-sm bg-gray-200 text-gray-700 rounded hover:bg-gray-300"
                      disabled={isProcessing}
                    >
                      -1s
                    </button>
                    <button
                      onClick={() => setTimingOffset(prev => Math.min(30, prev + 1))}
                      className="px-2 py-1 text-sm bg-gray-200 text-gray-700 rounded hover:bg-gray-300"
                      disabled={isProcessing}
                    >
                      +1s
                    </button>
                  </div>
                </div>
                <div className="mt-1 text-xs text-gray-500">
                  Positive = move later, Negative = move earlier
                </div>
              </div>
              
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Apply to:
                </label>
                <div className="space-y-2">
                  {job?.requested_outputs.captions_vtt && (
                    <label className="flex items-center">
                      <input
                        type="checkbox"
                        checked={adjustCaptions}
                        onChange={(e) => setAdjustCaptions(e.target.checked)}
                        className="mr-2"
                        disabled={isProcessing}
                      />
                      <span className="text-sm">Closed Captions</span>
                    </label>
                  )}
                  {job?.requested_outputs.audio_description_vtt && (
                    <label className="flex items-center">
                      <input
                        type="checkbox"
                        checked={adjustAudioDescription}
                        onChange={(e) => setAdjustAudioDescription(e.target.checked)}
                        className="mr-2"
                        disabled={isProcessing}
                      />
                      <span className="text-sm">Audio Description</span>
                    </label>
                  )}
                </div>
              </div>
            </div>
            
            <div className="flex items-center justify-between pt-4 border-t border-gray-200">
              <div className="text-xs text-gray-500">
                This will adjust all cue timings by the specified amount
              </div>
              <div className="flex space-x-2">
                <button
                  onClick={() => {
                    setShowTimingAdjustment(false);
                    setTimingOffset(0);
                  }}
                  disabled={isProcessing}
                  className="px-4 py-2 text-sm bg-gray-300 text-gray-700 rounded-md hover:bg-gray-400"
                >
                  Cancel
                </button>
                <button
                  onClick={handleTimingAdjustment}
                  disabled={isProcessing || timingOffset === 0 || (!adjustCaptions && !adjustAudioDescription)}
                  className="px-4 py-2 text-sm bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50"
                >
                  {adjustTimingMutation.isPending ? 'Adjusting...' : `Apply ${timingOffset > 0 ? '+' : ''}${timingOffset}s`}
                </button>
              </div>
            </div>
          </div>
        )}
      </div>

      {/* Save Changes */}
      {hasUnsavedChanges && (
        <div className="mb-6 p-4 bg-yellow-50 border border-yellow-200 rounded-md">
          <div className="flex justify-between items-center">
            <div className="text-yellow-800">
              <strong>Unsaved Changes:</strong> You have unsaved VTT edits
            </div>
            <button
              onClick={saveVttChanges}
              disabled={updateVttMutation.isPending}
              className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50"
            >
              {updateVttMutation.isPending ? 'Saving...' : 'Save Changes'}
            </button>
          </div>
        </div>
      )}

      {/* Voice Settings - Only show if MP3 generation is requested */}
      {job?.requested_outputs?.audio_description_mp3 && (
        <div className="mb-6 border border-gray-200 rounded-lg overflow-hidden">
          <button
            type="button"
            onClick={() => setShowVoiceSettings(!showVoiceSettings)}
            className="w-full flex items-center justify-between px-4 py-3 bg-gray-50 hover:bg-gray-100 transition-colors"
          >
            <div className="flex items-center gap-2">
              <svg
                className={`w-4 h-4 text-gray-500 transition-transform ${showVoiceSettings ? 'rotate-90' : ''}`}
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
              </svg>
              <span className="text-sm font-medium text-gray-700">Voice Settings for Audio Description</span>
              {job.requested_outputs.tts_preferences && (
                <span className="text-xs text-blue-600">(Configured)</span>
              )}
            </div>
            <span className="text-xs text-gray-500">
              {showVoiceSettings ? 'Click to collapse' : 'Click to customize or override TTS voice'}
            </span>
          </button>
          {showVoiceSettings && (
            <div className="p-4 border-t border-gray-200">
              <VoiceSelector
                selectedLanguages={[sourceLanguage, ...(job.requested_outputs.languages || []).filter(l => l !== sourceLanguage)]}
                preferences={ttsPreferences}
                onChange={setTtsPreferences}
                disabled={isProcessing}
              />
            </div>
          )}
        </div>
      )}

      {/* Review Notes */}
      <div className="mb-6">
        <label className="block text-sm font-medium text-gray-700 mb-2">
          Review Notes
        </label>
        <textarea
          value={reviewNotes}
          onChange={(e) => setReviewNotes(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"
          rows={3}
          placeholder="Add any notes about this review..."
          disabled={isProcessing}
        />
      </div>

      {/* Action Buttons */}
      <div className="flex gap-4">
        {!showRejectForm ? (
          <>
            <button
              onClick={handleApprove}
              disabled={isProcessing}
              className="px-6 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 disabled:opacity-50"
            >
              {approveEnglishMutation.isPending ? 'Approving...' : `Approve ${sourceLanguage.toUpperCase()} Version`}
            </button>
            
            <button
              onClick={() => setShowRejectForm(true)}
              disabled={isProcessing}
              className="px-6 py-2 bg-red-600 text-white rounded-md hover:bg-red-700 disabled:opacity-50"
            >
              Reject
            </button>
          </>
        ) : (
          <div className="flex items-center gap-4">
            <div className="text-sm text-red-600 font-medium">
              Rejection notes are required:
            </div>
            <button
              onClick={handleReject}
              disabled={isProcessing || !reviewNotes.trim()}
              className="px-6 py-2 bg-red-600 text-white rounded-md hover:bg-red-700 disabled:opacity-50"
            >
              {rejectJobMutation.isPending ? 'Rejecting...' : 'Confirm Rejection'}
            </button>
            <button
              onClick={() => setShowRejectForm(false)}
              disabled={isProcessing}
              className="px-6 py-2 bg-gray-300 text-gray-700 rounded-md hover:bg-gray-400"
            >
              Cancel
            </button>
          </div>
        )}
      </div>
    </div>
  );
}