import { useState } from 'react';
import { useParams, Link } from 'react-router-dom';
import { formatDistanceToNow } from 'date-fns';
import { useJob, useJobDownloads, useJobVttContent } from '../../hooks/useJob';
import { StatusBadge } from '../../components/StatusBadge';
import { VideoWithCaptions } from '../../components/VideoWithCaptions';
import { useGlobalWebSocket } from '../../contexts/GlobalWebSocketContext';


const ProgressIndicator = ({ status }: { status: string }) => {
  const steps = [
    'created',
    'ingesting',
    'ai_processing',
    'pending_qc',
    'approved',  // Generic - matches both approved_english and approved_source
    'translating',
    'tts_generating',
    'pending_final_review',
    'completed'
  ];

  // Map approved statuses to generic 'approved' for progress display
  const normalizedStatus = (status === 'approved_english' || status === 'approved_source') ? 'approved' : status;
  const currentIndex = steps.indexOf(normalizedStatus);
  const isRejected = status === 'rejected';

  if (isRejected) {
    return (
      <div className="bg-red-50 border border-red-200 rounded-md p-4">
        <p className="text-red-800 font-medium">Job Rejected</p>
        <p className="text-red-600 text-sm mt-1">
          This job has been rejected during review. Please check the review notes for feedback.
        </p>
      </div>
    );
  }

  return (
    <div className="bg-white border border-gray-200 rounded-lg p-4">
      <h3 className="text-sm font-medium text-gray-900 mb-3">Processing Progress</h3>
      <div className="space-y-2">
        {steps.map((step, index) => (
          <div key={step} className="flex items-center">
            <div className={`w-3 h-3 rounded-full mr-3 ${
              index <= currentIndex ? 'bg-green-500' : 'bg-gray-300'
            }`} />
            <span className={`text-sm ${
              index === currentIndex ? 'font-medium text-gray-900' : 
              index < currentIndex ? 'text-gray-600' : 'text-gray-400'
            }`}>
              {step.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase())}
            </span>
          </div>
        ))}
      </div>
    </div>
  );
};

export function JobDetail() {
  const { id } = useParams();
  const [activeTab, setActiveTab] = useState<'overview' | 'video' | 'assets' | 'history'>('overview');

  const { data: job, isLoading, error } = useJob(id!);
  const { data: downloads } = useJobDownloads(id!);
  // Get source language from job (default to 'en' for backwards compatibility)
  const sourceLanguage = job?.source?.language || 'en';
  const { data: sourceVtt } = useJobVttContent(id!, sourceLanguage);

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


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

  const tabs = [
    { id: 'overview' as const, label: 'Overview', icon: '📋', disabled: false },
    { id: 'video' as const, label: 'Video Preview', icon: '🎥', disabled: !videoUrl },
    { id: 'assets' as const, label: 'Assets', icon: '📁', disabled: false },
    { id: 'history' as const, label: 'History', icon: '📜', disabled: false },
  ];

  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="grid gap-6 lg:grid-cols-3">
            <div className="lg:col-span-2 space-y-6">
              <div className="h-64 bg-gray-200 rounded"></div>
              <div className="h-32 bg-gray-200 rounded"></div>
            </div>
            <div className="h-48 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>
        </div>
      </div>
    );
  }

  const renderTabContent = () => {
    switch (activeTab) {
      case 'overview':
        return (
          <div className="space-y-6">
            {/* Job Information */}
            <div className="bg-white border border-gray-200 rounded-lg p-6">
              <h2 className="text-lg font-medium text-gray-900 mb-4">Job Information</h2>
              <dl className="grid grid-cols-1 gap-x-4 gap-y-4 sm:grid-cols-2">
                <div>
                  <dt className="text-sm font-medium text-gray-500">Original File</dt>
                  <dd className="text-sm text-gray-900 mt-1">{job.source?.original_filename || 'N/A'}</dd>
                </div>
                <div>
                  <dt className="text-sm font-medium text-gray-500">Source Language</dt>
                  <dd className="text-sm text-gray-900 mt-1">{job.source?.language?.toUpperCase() || 'N/A'}</dd>
                </div>
                <div>
                  <dt className="text-sm font-medium text-gray-500">Requested Languages</dt>
                  <dd className="text-sm text-gray-900 mt-1">
                    {job.requested_outputs?.languages?.join(', ') || 'N/A'}
                  </dd>
                </div>
                <div>
                  <dt className="text-sm font-medium text-gray-500">Outputs</dt>
                  <dd className="text-sm text-gray-900 mt-1">
                    <div className="space-y-1">
                      {job.requested_outputs?.captions_vtt && <div>✓ Captions (VTT)</div>}
                      {job.requested_outputs?.audio_description_vtt && <div>✓ Audio Descriptions (VTT)</div>}
                      {job.requested_outputs?.audio_description_mp3 && <div>✓ Audio Descriptions (MP3)</div>}
                    </div>
                  </dd>
                </div>
                {/* Transcreation Languages - HIDDEN: Not fully implemented */}
                {/* {job.requested_outputs?.transcreation && job.requested_outputs.transcreation.length > 0 && (
                  <div className="sm:col-span-2">
                    <dt className="text-sm font-medium text-gray-500">Transcreation Languages</dt>
                    <dd className="text-sm text-gray-900 mt-1">
                      {job.requested_outputs.transcreation.join(', ')} (Cultural adaptation)
                    </dd>
                  </div>
                )} */}
              </dl>
            </div>

            {/* Download Section */}
            {job.status === 'completed' && (
              <div className="bg-green-50 border border-green-200 rounded-lg p-6">
                <div className="flex items-center justify-between">
                  <div>
                    <h3 className="text-lg font-medium text-green-800">Ready for Download</h3>
                    <p className="text-green-700 text-sm mt-1">
                      Your accessible video assets are ready. Click below to access your files.
                    </p>
                  </div>
                  <Link
                    to={`/downloads/${job.id}`}
                    className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-green-600 hover:bg-green-700"
                  >
                    <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 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 Files
                  </Link>
                </div>
              </div>
            )}
          </div>
        );

      case 'video':
        return (
          <div className="bg-white border border-gray-200 rounded-lg p-6">
            <h2 className="text-lg font-medium text-gray-900 mb-4">Video Preview</h2>
            {videoUrl ? (
              <VideoWithCaptions
                videoUrl={videoUrl}
                captionsVtt={sourceVtt?.captions_vtt || ''}
                audioDescriptionVtt={sourceVtt?.audio_description_vtt || ''}
                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>
        );

      case 'assets':
        return (
          <div className="space-y-6">
            {/* Language Assets */}
            {job.outputs && Object.keys(job.outputs).length > 0 && (
              <div className="bg-white border border-gray-200 rounded-lg p-6">
                <h2 className="text-lg font-medium text-gray-900 mb-4">Language Assets</h2>
                <div className="space-y-4">
                  {Object.entries(job.outputs).map(([language, output]) => {
                    const assets = output as {
                      captions_vtt_gcs?: string;
                      ad_vtt_gcs?: string;
                      ad_mp3_gcs?: string;
                      qa_notes?: string;
                    };
                    return (
                      <div key={language} className="border border-gray-200 rounded-lg p-4">
                        <div className="flex items-center justify-between mb-3">
                          <h3 className="font-medium text-gray-900">{language.toUpperCase()}</h3>
                          <div className="flex items-center space-x-2">
                            {assets.captions_vtt_gcs && (
                              <span className="inline-flex items-center px-2 py-1 rounded text-xs font-medium bg-green-100 text-green-800">
                                Captions Ready
                              </span>
                            )}
                            {assets.ad_vtt_gcs && (
                              <span className="inline-flex items-center px-2 py-1 rounded text-xs font-medium bg-blue-100 text-blue-800">
                                AD Ready
                              </span>
                            )}
                            {assets.ad_mp3_gcs && (
                              <span className="inline-flex items-center px-2 py-1 rounded text-xs font-medium bg-purple-100 text-purple-800">
                                MP3 Ready
                              </span>
                            )}
                          </div>
                        </div>
                        {assets.qa_notes && (
                          <div className="mt-2 p-2 bg-red-50 border border-red-200 rounded">
                            <p className="text-sm text-red-800">
                              <strong>QA Issues:</strong> {assets.qa_notes}
                            </p>
                          </div>
                        )}
                      </div>
                    );
                  })}
                </div>
              </div>
            )}
          </div>
        );

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

      default:
        return null;
    }
  };

  return (
    <div className="container mx-auto px-4 py-8">
      {/* Header */}
      <div className="mb-8">
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-3xl font-bold text-gray-900 mb-2">
              {job.title}
            </h1>
            <p className="text-gray-600">
              {job.source?.original_filename} • 
              Created {formatDistanceToNow(new Date(job.created_at))} ago
            </p>
          </div>
          <div className="flex items-center gap-2">
            <StatusBadge status={job.status} />
            {connectionStatus === 'connected' && (
              <span className="inline-block w-2 h-2 bg-green-400 rounded-full" title="Connected - receiving real-time updates" />
            )}
            {connectionStatus === 'connecting' && (
              <span className="inline-block w-2 h-2 bg-yellow-400 rounded-full animate-pulse" title="Connecting..." />
            )}
            {connectionStatus === 'error' && (
              <span className="inline-block w-2 h-2 bg-red-400 rounded-full" title="Connection error" />
            )}
          </div>
        </div>
      </div>

      <div className="grid gap-6 lg:grid-cols-4">
        <div className="lg:col-span-3">
          {/* Tab Navigation */}
          <div className="border-b border-gray-200 mb-6">
            <nav className="-mb-px flex space-x-8">
              {tabs.map((tab) => (
                <button
                  key={tab.id}
                  onClick={() => setActiveTab(tab.id)}
                  disabled={tab.disabled}
                  className={`py-2 px-1 border-b-2 font-medium text-sm ${
                    activeTab === tab.id
                      ? 'border-blue-500 text-blue-600'
                      : tab.disabled
                      ? 'border-transparent text-gray-400 cursor-not-allowed'
                      : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
                  }`}
                >
                  <span className="mr-2">{tab.icon}</span>
                  {tab.label}
                </button>
              ))}
            </nav>
          </div>

          {/* Tab Content */}
          {renderTabContent()}
        </div>

        {/* Sidebar */}
        <div className="space-y-6">
          <ProgressIndicator status={job.status} />

          {/* Error Display */}
          {job.error && (
            <div className="bg-red-50 border border-red-200 rounded-lg p-4">
              <h3 className="text-sm font-medium text-red-800 mb-2">Processing Error</h3>
              <p className="text-xs text-red-600">{String(job.error.message || 'Unknown error')}</p>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}