import { useParams, useNavigate } from 'react-router-dom';
import { useState } from 'react';
import { useJob, useCompleteJob, useJobVttContent, useRejectFinalReview, useJobValidation, useJobDownloads } from '../../hooks/useJob';
import { StatusBadge } from '../../components/StatusBadge';
import { VttEditor } from '../../components/VttEditor/VttEditor';

import type { LangOutput } from '../../types/api';

interface LanguagePreviewProps {
  language: string;
  assets: LangOutput;
  jobId: string;
  audioUrl?: string;
}

const LanguagePreview = ({ 
  language, 
  assets, 
  jobId,
  audioUrl
}: LanguagePreviewProps) => {
  const [previewType, setPreviewType] = useState<'captions' | 'ad'>('captions');
  const { data: vttContent } = useJobVttContent(jobId, language);

  return (
    <div className="border rounded-lg p-4 mb-4">
      <div className="flex items-center justify-between mb-4">
        <div className="flex items-center space-x-3">
          <h3 className="text-lg font-medium text-gray-900">
            {language.toUpperCase()}
          </h3>
          <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${
            assets.origin === 'transcreate' ? 'bg-purple-100 text-purple-800' : 'bg-blue-100 text-blue-800'
          }`}>
            {assets.origin === 'transcreate' ? 'Transcreated' : 'Translated'}
          </span>
          {assets.qa_notes && (
            <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800">
              Has Issues
            </span>
          )}
        </div>
        
        <div className="flex space-x-2">
          <button
            onClick={() => setPreviewType('captions')}
            className={`px-3 py-1 text-sm rounded ${
              previewType === 'captions' 
                ? 'bg-indigo-100 text-indigo-700'
                : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
            }`}
          >
            Captions
          </button>
          <button
            onClick={() => setPreviewType('ad')}
            className={`px-3 py-1 text-sm rounded ${
              previewType === 'ad' 
                ? 'bg-indigo-100 text-indigo-700'
                : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
            }`}
          >
            Audio Descriptions
          </button>
        </div>
      </div>

      {assets.qa_notes && (
        <div className="mb-4 p-3 bg-red-50 border border-red-200 rounded">
          <p className="text-sm text-red-800">
            <strong>Quality Issues:</strong> {assets.qa_notes}
          </p>
        </div>
      )}

      <div className="bg-gray-50 rounded-lg p-4">
        {previewType === 'captions' && vttContent?.captions_vtt && (
          <VttEditor
            vttContent={vttContent.captions_vtt}
            onChange={() => {}} // Read-only in final review
            title={`${language.toUpperCase()} Captions`}
            readOnly={true}
          />
        )}
        
        {previewType === 'ad' && vttContent?.audio_description_vtt && (
          <VttEditor
            vttContent={vttContent.audio_description_vtt}
            onChange={() => {}} // Read-only in final review
            title={`${language.toUpperCase()} Audio Description`}
            readOnly={true}
          />
        )}
      </div>

      <div className="mt-4 flex items-center justify-between text-sm text-gray-600">
        <div className="flex space-x-4">
          <span>Captions: {assets.captions_vtt_gcs ? '✓' : '✗'}</span>
          <span>Audio Descriptions: {assets.ad_vtt_gcs ? '✓' : '✗'}</span>
          {assets.ad_mp3_gcs && (
            <span>MP3 Audio: ✓</span>
          )}
        </div>
        
        {assets.ad_mp3_gcs && (
          audioUrl ? (
            <audio controls className="max-w-xs">
              <source src={audioUrl} type="audio/mpeg" />
              Your browser does not support the audio element.
            </audio>
          ) : (
            <div className="flex items-center p-3 bg-blue-50 border border-blue-200 rounded-lg max-w-xs">
              <div className="animate-spin h-4 w-4 border-2 border-blue-600 border-t-transparent rounded-full mr-2"></div>
              <span className="text-sm text-blue-700">Generating audio...</span>
            </div>
          )
        )}
      </div>
    </div>
  );
};

export function FinalDetail() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const [selectedAction, setSelectedAction] = useState<'approve' | 'reject' | null>(null);
  const [reviewNotes, setReviewNotes] = useState('');

  const { data: job, isLoading, error } = useJob(id!);
  const { data: validation } = useJobValidation(id!);
  const { data: downloads } = useJobDownloads(id!);
  const completeJobMutation = useCompleteJob();
  const rejectFinalMutation = useRejectFinalReview();

  const handleSubmitReview = async () => {
    if (!selectedAction || !id) return;
    
    try {
      if (selectedAction === 'approve') {
        await completeJobMutation.mutateAsync({ id, notes: reviewNotes });
      } else {
        await rejectFinalMutation.mutateAsync({ id, notes: reviewNotes });
      }
      navigate('/admin/final');
    } catch (error) {
      console.error('Final review action failed:', error);
    }
  };

  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/3 mb-8"></div>
          <div className="space-y-4">
            <div className="h-64 bg-gray-200 rounded"></div>
            <div className="h-32 bg-gray-200 rounded"></div>
          </div>
        </div>
      </div>
    );
  }

  if (error || !job) {
    return (
      <div className="container mx-auto px-4 py-8">
        <div className="bg-red-50 border border-red-200 rounded-md p-4">
          <p className="text-red-800">Failed to load job details</p>
          <button
            onClick={() => navigate('/admin/final')}
            className="mt-2 text-sm text-indigo-600 hover:text-indigo-500"
          >
            ← Back to Final Review Queue
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="container mx-auto px-4 py-8">
      <div className="mb-8">
        <button
          onClick={() => navigate('/admin/final')}
          className="text-sm text-indigo-600 hover:text-indigo-500 mb-4"
        >
          ← Back to Final Review Queue
        </button>
        
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-3xl font-bold text-gray-900">
              {job.title}
            </h1>
            <p className="text-gray-600 mt-2">
              Source: {job.source.original_filename || job.source.filename}
              {job.source.duration_s && ` • Duration: ${Math.round(job.source.duration_s)}s`}
            </p>
          </div>
          
          <div className="text-right">
            <StatusBadge status={job.status} />
          </div>
        </div>
      </div>

      {/* Asset Validation Summary */}
      <div className={`mb-6 p-4 border rounded-md ${
        validation?.is_valid ? 'bg-green-50 border-green-200' : 'bg-red-50 border-red-200'
      }`}>
        <h3 className={`font-medium mb-2 ${
          validation?.is_valid ? 'text-green-900' : 'text-red-900'
        }`}>
          Asset Validation {validation?.is_valid ? '✓ Passed' : '✗ Failed'}
        </h3>
        
        {validation?.errors && validation.errors.length > 0 && (
          <div className="mb-3">
            <p className="text-sm font-medium text-red-800 mb-1">Validation Errors:</p>
            <ul className="text-sm text-red-700 space-y-1">
              {validation.errors.map((error, i) => (
                <li key={i}>• {error}</li>
              ))}
            </ul>
          </div>
        )}
        
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
          <div>
            <span className={validation?.is_valid ? 'text-green-700' : 'text-red-700'}>Languages:</span>
            <span className="ml-1 font-medium">{Object.keys(job.outputs || {}).length}</span>
          </div>
          <div>
            <span className={validation?.is_valid ? 'text-green-700' : 'text-red-700'}>VTT Files:</span>
            <span className="ml-1 font-medium">{_countVttFiles(job.outputs || {})}</span>
          </div>
          <div>
            <span className={validation?.is_valid ? 'text-green-700' : 'text-red-700'}>MP3 Files:</span>
            <span className="ml-1 font-medium">{_countMp3Files(job.outputs || {})}</span>
          </div>
          <div>
            <span className={validation?.is_valid ? 'text-green-700' : 'text-red-700'}>AI Confidence:</span>
            <span className="ml-1 font-medium">{job.ai?.confidence ? `${(job.ai.confidence * 100).toFixed(1)}%` : 'N/A'}</span>
          </div>
        </div>
      </div>

      {/* Languages Preview */}
      <div className="mb-8">
        <h2 className="text-xl font-semibold text-gray-900 mb-4">
          Language Assets ({Object.keys(job.outputs || {}).length} languages)
        </h2>
        
        {Object.entries(job.outputs || {}).map(([language, assets]) => (
          <LanguagePreview
            key={language}
            language={language}
            assets={assets}
            jobId={id!}
            audioUrl={typeof downloads?.downloads?.[language] === 'object' ? downloads?.downloads?.[language]?.audio_description_mp3 : undefined}
          />
        ))}
      </div>

      {/* Final Review Actions */}
      {job.status === 'pending_final_review' && (
        <div className="bg-white border border-gray-200 rounded-lg p-6">
          <h3 className="text-lg font-medium text-gray-900 mb-4">Final Review Decision</h3>
          
          <div className="space-y-4">
            <div>
              <label className="text-sm font-medium text-gray-700 mb-2 block">
                Review Decision
              </label>
              <div className="flex space-x-4">
                <label className="flex items-center">
                  <input
                    type="radio"
                    name="action"
                    value="approve"
                    checked={selectedAction === 'approve'}
                    onChange={(e) => setSelectedAction(e.target.value as 'approve')}
                    className="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300"
                  />
                  <span className="ml-2 text-sm text-gray-900">Approve for Client Delivery</span>
                </label>
                <label className="flex items-center">
                  <input
                    type="radio"
                    name="action"
                    value="reject"
                    checked={selectedAction === 'reject'}
                    onChange={(e) => setSelectedAction(e.target.value as 'reject')}
                    className="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300"
                  />
                  <span className="ml-2 text-sm text-gray-900">Return for Quality Control</span>
                </label>
              </div>
            </div>

            <div>
              <label htmlFor="review-notes" className="block text-sm font-medium text-gray-700 mb-2">
                Review Notes
              </label>
              <textarea
                id="review-notes"
                rows={4}
                value={reviewNotes}
                onChange={(e) => setReviewNotes(e.target.value)}
                className="w-full border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
                placeholder={selectedAction === 'approve' 
                  ? 'Optional final approval notes...' 
                  : selectedAction === 'reject' 
                  ? 'Required: Explain what needs to be fixed...'
                  : 'Select an action above to add notes...'
                }
                required={selectedAction === 'reject'}
              />
            </div>

            <div className="flex justify-end space-x-3">
              <button
                onClick={() => navigate('/admin/final')}
                className="px-4 py-2 border border-gray-300 rounded-md text-sm font-medium text-gray-700 hover:bg-gray-50"
              >
                Cancel
              </button>
              <button
                onClick={handleSubmitReview}
                disabled={
                  !selectedAction || 
                  (selectedAction === 'reject' && !reviewNotes.trim()) || 
                  (selectedAction === 'approve' && !validation?.is_valid) ||
                  completeJobMutation.isPending || 
                  rejectFinalMutation.isPending
                }
                className={`px-4 py-2 rounded-md text-sm font-medium text-white ${
                  selectedAction === 'approve'
                    ? validation?.is_valid 
                      ? 'bg-green-600 hover:bg-green-700 disabled:bg-gray-300'
                      : 'bg-gray-300'
                    : selectedAction === 'reject'
                    ? 'bg-red-600 hover:bg-red-700 disabled:bg-gray-300'
                    : 'bg-gray-300'
                }`}
              >
                {completeJobMutation.isPending || rejectFinalMutation.isPending ? 'Processing...' : 
                 selectedAction === 'approve' ? 
                   validation?.is_valid ? 'Approve for Client Delivery' : 'Fix Validation Errors First' :
                 selectedAction === 'reject' ? 'Return for QC' :
                 'Select Action'}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Job History */}
      <div className="mt-8 bg-white border border-gray-200 rounded-lg p-6">
        <h3 className="text-lg font-medium text-gray-900 mb-4">Job History</h3>
        <div className="space-y-3">
          {job.review?.history?.map((entry, index) => (
            <div key={index} className="flex items-center justify-between text-sm">
              <div className="flex items-center space-x-3">
                <span className="text-gray-900 font-medium">
                  {entry.status.replace(/_/g, ' ').toUpperCase()}
                </span>
                {entry.by && <span className="text-gray-600">by {entry.by}</span>}
              </div>
              <span className="text-gray-500">
                {new Date(entry.at).toLocaleDateString()}
              </span>
            </div>
          )) || (
            <p className="text-gray-500 text-sm">No history available</p>
          )}
        </div>
      </div>
    </div>
  );
}

// Utility functions for asset counting
function _countVttFiles(outputs: Record<string, LangOutput>): number {
  let count = 0;
  Object.values(outputs).forEach(lang => {
    if (lang.captions_vtt_gcs) count++;
    if (lang.ad_vtt_gcs) count++;
  });
  return count;
}

function _countMp3Files(outputs: Record<string, LangOutput>): number {
  return Object.values(outputs).filter(lang => lang.ad_mp3_gcs).length;
}