import { useState } from 'react';
import {
  Download,
  Languages,
  Film,
  CheckCircle,
  XCircle,
  Loader,
  ChevronDown,
  ChevronUp,
  Volume2,
  VolumeX,
  PenLine,
  Music2,
  Mic,
  FileAudio,
  Wand2,
  RefreshCw,
} from 'lucide-react';

// 6-step pipeline
const PIPELINE_STEPS = [
  {
    key: 'downloading',
    label: '영상 다운로드',
    icon: Download,
    description: 'yt-dlp로 원본 영상 다운로드',
    statusKey: 'downloading',
  },
  {
    key: 'extracting_audio',
    label: '오디오 추출',
    icon: FileAudio,
    description: 'FFmpeg로 오디오 스트림 추출',
    statusKey: 'extracting_audio',
  },
  {
    key: 'noise_reduction',
    label: '노이즈 제거',
    icon: Wand2,
    description: '배경 잡음 제거 및 음성 강화',
    statusKey: 'noise_reduction',
  },
  {
    key: 'transcribing',
    label: 'Whisper STT',
    icon: Mic,
    description: 'OpenAI Whisper로 음성 인식',
    statusKey: 'transcribing',
  },
  {
    key: 'translating',
    label: '요약 + 한국어 변환',
    icon: Languages,
    description: 'GPT로 요약 및 자연스러운 한국어 작성 (중국어만)',
    statusKey: 'translating',
  },
  {
    key: 'processing',
    label: '영상 합성 + BGM',
    icon: Film,
    description: 'FFmpeg로 자막 합성 및 BGM 추가',
    statusKey: 'processing',
  },
];

// Status progression order
const STATUS_ORDER = [
  'pending',
  'downloading',
  'ready_for_trim',  // Download complete, ready for trimming
  'trimming',  // Video trimming step
  'extracting_audio',
  'noise_reduction',
  'transcribing',
  'awaiting_subtitle',
  'translating',
  'awaiting_review',  // Script ready, waiting for user review
  'processing',
  'completed',
];

function getStepStatus(step, job) {
  const currentIndex = STATUS_ORDER.indexOf(job.status);
  const stepIndex = STATUS_ORDER.indexOf(step.statusKey);

  if (job.status === 'failed') {
    // Check if this step was the one that failed
    if (stepIndex <= currentIndex) {
      return stepIndex === currentIndex ? 'failed' : 'completed';
    }
    return 'pending';
  }

  if (job.status === 'completed') {
    // Check if translation was skipped (non-Chinese)
    if (step.key === 'translating' && job.detected_language && !['zh', 'zh-cn', 'zh-tw', 'chinese', 'mandarin'].includes(job.detected_language.toLowerCase())) {
      return 'skipped';
    }
    return 'completed';
  }

  if (job.status === 'awaiting_subtitle') {
    // Special handling for no-audio case
    if (step.key === 'transcribing') {
      return 'warning'; // Show as warning (no audio)
    }
    if (stepIndex < STATUS_ORDER.indexOf('transcribing')) {
      return 'completed';
    }
    return 'pending';
  }

  if (stepIndex < currentIndex) {
    return 'completed';
  }
  if (stepIndex === currentIndex) {
    return 'active';
  }
  return 'pending';
}

function StepIcon({ step, status }) {
  const Icon = step.icon;

  const baseClasses = 'w-10 h-10 rounded-xl flex items-center justify-center transition-all duration-300';

  switch (status) {
    case 'completed':
      return (
        <div className={`${baseClasses} bg-green-500 shadow-lg shadow-green-500/30`}>
          <CheckCircle size={20} className="text-white" />
        </div>
      );
    case 'active':
      return (
        <div className={`${baseClasses} bg-red-500 shadow-lg shadow-red-500/30 animate-pulse`}>
          <Loader size={20} className="text-white animate-spin" />
        </div>
      );
    case 'failed':
      return (
        <div className={`${baseClasses} bg-red-600 shadow-lg shadow-red-600/30`}>
          <XCircle size={20} className="text-white" />
        </div>
      );
    case 'warning':
      return (
        <div className={`${baseClasses} bg-amber-500 shadow-lg shadow-amber-500/30`}>
          <VolumeX size={20} className="text-white" />
        </div>
      );
    case 'skipped':
      return (
        <div className={`${baseClasses} bg-gray-600 shadow-lg shadow-gray-600/20`}>
          <CheckCircle size={20} className="text-gray-300" />
        </div>
      );
    default:
      return (
        <div className={`${baseClasses} bg-gray-700`}>
          <Icon size={20} className="text-gray-400" />
        </div>
      );
  }
}

function StepCard({ step, status, index, isLast, job, onRetranslate }) {
  const [isExpanded, setIsExpanded] = useState(false);
  const [isRetranslating, setIsRetranslating] = useState(false);

  const getStatusBadge = () => {
    switch (status) {
      case 'completed':
        return <span className="text-xs px-2 py-0.5 bg-green-500/20 text-green-400 rounded-full">완료</span>;
      case 'active':
        return <span className="text-xs px-2 py-0.5 bg-red-500/20 text-red-400 rounded-full animate-pulse">진행 중</span>;
      case 'failed':
        return <span className="text-xs px-2 py-0.5 bg-red-600/20 text-red-400 rounded-full">실패</span>;
      case 'warning':
        return (
          <span className="text-xs px-2 py-0.5 bg-amber-500/20 text-amber-400 rounded-full">
            {job.audio_status === 'singing_only' ? '노래만 감지' : '오디오 없음'}
          </span>
        );
      case 'skipped':
        return <span className="text-xs px-2 py-0.5 bg-gray-600/20 text-gray-400 rounded-full">스킵</span>;
      default:
        return <span className="text-xs px-2 py-0.5 bg-gray-700/50 text-gray-500 rounded-full">대기</span>;
    }
  };

  const getTextColor = () => {
    switch (status) {
      case 'completed':
        return 'text-green-400';
      case 'active':
        return 'text-white';
      case 'failed':
        return 'text-red-400';
      case 'warning':
        return 'text-amber-400';
      case 'skipped':
        return 'text-gray-400';
      default:
        return 'text-gray-500';
    }
  };

  return (
    <div className="flex items-start gap-4">
      {/* Step Icon & Connector */}
      <div className="flex flex-col items-center">
        <StepIcon step={step} status={status} />
        {!isLast && (
          <div className={`w-0.5 h-16 mt-2 transition-colors duration-500 ${
            status === 'completed' ? 'bg-green-500' : 'bg-gray-700'
          }`} />
        )}
      </div>

      {/* Step Content */}
      <div className="flex-1 pb-6">
        <div className="flex items-center gap-3 mb-1">
          <span className="text-xs font-mono text-gray-500">0{index + 1}</span>
          <h4 className={`font-semibold ${getTextColor()}`}>{step.label}</h4>
          {getStatusBadge()}
        </div>
        <p className={`text-sm ${status === 'pending' ? 'text-gray-600' : 'text-gray-400'}`}>
          {status === 'warning'
            ? job.audio_status === 'singing_only'
              ? '노래/배경음악만 감지됨 - 음성 없음'
              : '오디오가 없거나 무음입니다'
            : status === 'skipped'
              ? `중국어가 아닌 콘텐츠 (${job.detected_language || '알 수 없음'}) - GPT 스킵`
              : step.description}
        </p>

        {/* Expandable Details */}
        {status === 'completed' && step.key === 'transcribing' && job.transcript?.length > 0 && (
          <div className="mt-3">
            <button
              onClick={() => setIsExpanded(!isExpanded)}
              className="flex items-center gap-2 text-xs text-gray-400 hover:text-white transition-colors"
            >
              {isExpanded ? <ChevronUp size={14} /> : <ChevronDown size={14} />}
              인식 결과 ({job.transcript.length}개 세그먼트)
            </button>
            {isExpanded && (
              <div className="mt-2 p-3 bg-gray-800/50 rounded-lg border border-gray-700 max-h-64 overflow-y-auto">
                {job.transcript.map((seg, i) => (
                  <div key={i} className="text-xs text-gray-300 mb-1">
                    <span className="text-gray-500 font-mono mr-2">
                      {formatTime(seg.start)}
                    </span>
                    {seg.text}
                  </div>
                ))}
              </div>
            )}
          </div>
        )}

        {status === 'completed' && step.key === 'translating' && job.transcript?.some((s) => s.translated) && (
          <div className="mt-3">
            <div className="flex items-center gap-3">
              <button
                onClick={() => setIsExpanded(!isExpanded)}
                className="flex items-center gap-2 text-xs text-gray-400 hover:text-white transition-colors"
              >
                {isExpanded ? <ChevronUp size={14} /> : <ChevronDown size={14} />}
                번역 결과 보기
              </button>
              {onRetranslate && (
                <button
                  onClick={async () => {
                    setIsRetranslating(true);
                    await onRetranslate();
                    setIsRetranslating(false);
                  }}
                  disabled={isRetranslating}
                  className="flex items-center gap-1.5 text-xs px-2 py-1 bg-blue-600/20 text-blue-400 hover:bg-blue-600/30 rounded-md transition-colors disabled:opacity-50"
                >
                  <RefreshCw size={12} className={isRetranslating ? 'animate-spin' : ''} />
                  {isRetranslating ? '재번역 중...' : 'GPT 재번역'}
                </button>
              )}
            </div>
            {isExpanded && (
              <div className="mt-2 p-3 bg-gray-800/50 rounded-lg border border-gray-700 max-h-64 overflow-y-auto space-y-2">
                {job.transcript
                  .filter((s) => s.translated)
                  .map((seg, i) => (
                    <div key={i} className="text-xs">
                      <div className="text-gray-500 line-through">{seg.text}</div>
                      <div className="text-white mt-0.5">{seg.translated}</div>
                    </div>
                  ))}
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  );
}

function formatTime(seconds) {
  const mins = Math.floor(seconds / 60);
  const secs = Math.floor(seconds % 60);
  return `${mins}:${secs.toString().padStart(2, '0')}`;
}

export default function PipelineView({ job, onRetranslate }) {
  const getOverallProgress = () => {
    if (job.status === 'completed') return 100;
    if (job.status === 'failed') return job.progress || 0;

    const currentIndex = STATUS_ORDER.indexOf(job.status);
    const totalSteps = PIPELINE_STEPS.length;
    const stepProgress = (currentIndex / (totalSteps + 2)) * 100;
    return Math.min(Math.round(stepProgress), 99);
  };

  const getStatusText = () => {
    switch (job.status) {
      case 'completed':
        return '처리 완료';
      case 'failed':
        return '처리 실패';
      case 'awaiting_subtitle':
        return '자막 입력 대기';
      case 'awaiting_review':
        return '스크립트 확인 대기';
      case 'ready_for_trim':
        return '다운로드 완료';
      case 'pending':
        return '시작 대기';
      case 'trimming':
        return '영상 자르기 중...';
      default:
        return '처리 중...';
    }
  };

  const getStatusColor = () => {
    switch (job.status) {
      case 'completed':
        return 'text-green-400';
      case 'failed':
        return 'text-red-400';
      case 'awaiting_subtitle':
        return 'text-amber-400';
      case 'awaiting_review':
        return 'text-blue-400';
      case 'ready_for_trim':
        return 'text-blue-400';
      case 'trimming':
        return 'text-amber-400';
      default:
        return 'text-white';
    }
  };

  return (
    <div className="space-y-6">
      {/* Progress Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-4">
          <div className={`text-3xl font-bold ${getStatusColor()}`}>
            {job.progress || getOverallProgress()}%
          </div>
          <div>
            <div className={`font-medium ${getStatusColor()}`}>{getStatusText()}</div>
            <div className="text-sm text-gray-500">
              {job.original_url?.substring(0, 40)}...
            </div>
          </div>
        </div>
      </div>

      {/* Progress Bar */}
      <div className="relative h-2 bg-gray-800 rounded-full overflow-hidden">
        <div
          className={`absolute inset-y-0 left-0 transition-all duration-700 ease-out ${
            job.status === 'failed'
              ? 'bg-red-500'
              : job.status === 'completed'
              ? 'bg-green-500'
              : job.status === 'awaiting_subtitle'
              ? 'bg-amber-500'
              : job.status === 'awaiting_review' || job.status === 'ready_for_trim'
              ? 'bg-blue-500'
              : 'bg-gradient-to-r from-red-500 to-red-400'
          }`}
          style={{ width: `${job.progress || getOverallProgress()}%` }}
        />
        {!['completed', 'failed', 'awaiting_subtitle', 'awaiting_review', 'ready_for_trim', 'pending'].includes(job.status) && (
          <div
            className="absolute inset-y-0 bg-white/20 animate-pulse"
            style={{
              left: `${(job.progress || getOverallProgress()) - 5}%`,
              width: '5%',
            }}
          />
        )}
      </div>

      {/* Pipeline Steps */}
      <div className="mt-8">
        {PIPELINE_STEPS.map((step, index) => (
          <StepCard
            key={step.key}
            step={step}
            status={getStepStatus(step, job)}
            index={index}
            isLast={index === PIPELINE_STEPS.length - 1}
            job={job}
            onRetranslate={step.key === 'translating' ? onRetranslate : undefined}
          />
        ))}
      </div>

      {/* No Audio Alert */}
      {job.status === 'awaiting_subtitle' && (
        <div className="p-4 bg-amber-900/20 border border-amber-700/50 rounded-xl">
          <div className="flex items-center gap-2 text-amber-400 font-medium mb-3">
            {job.audio_status === 'singing_only' ? <Music2 size={18} /> : <VolumeX size={18} />}
            {job.audio_status === 'no_audio_stream'
              ? '오디오 스트림 없음'
              : job.audio_status === 'singing_only'
              ? '노래/배경음악만 감지됨'
              : '무음 오디오'}
          </div>
          <p className="text-amber-200/80 text-sm mb-4">
            {job.audio_status === 'no_audio_stream'
              ? '이 영상에는 오디오 트랙이 없습니다.'
              : job.audio_status === 'singing_only'
              ? '음성 없이 배경음악/노래만 감지되었습니다.'
              : '오디오가 거의 무음입니다.'}
          </p>

          <div className="grid grid-cols-2 gap-3">
            <div className="p-3 bg-gray-800/50 rounded-lg border border-gray-700/50">
              <div className="flex items-center gap-2 text-white font-medium text-sm mb-1">
                <PenLine size={14} />
                자막 직접 입력
              </div>
              <p className="text-xs text-gray-400">원하는 자막을 수동으로 입력</p>
            </div>
            <div className="p-3 bg-gray-800/50 rounded-lg border border-gray-700/50">
              <div className="flex items-center gap-2 text-white font-medium text-sm mb-1">
                <Volume2 size={14} />
                BGM만 추가
              </div>
              <p className="text-xs text-gray-400">자막 없이 음악만 추가</p>
            </div>
          </div>
        </div>
      )}

      {/* Error Display */}
      {job.error && (
        <div className="p-4 bg-red-900/20 border border-red-800/50 rounded-xl">
          <div className="flex items-center gap-2 text-red-400 font-medium mb-2">
            <XCircle size={18} />
            오류 발생
          </div>
          <p className="text-red-300/80 text-sm font-mono">{job.error}</p>
        </div>
      )}
    </div>
  );
}
