'use client';

import { motion } from 'framer-motion';
import { Loader2, CheckCircle2, XCircle, Wifi, WifiOff } from 'lucide-react';
import type { RenderProgressState } from '@/hooks/use-render-progress';

const STAGE_ORDER = ['tts', 'image_generation', 'music_generation', 'compositing', 'encoding'];

const STAGE_DETAILS: Record<string, { label: string; icon: string; color: string }> = {
  tts: { label: 'Seslendirme', icon: '🔊', color: 'from-neutral-500 to-neutral-600' },
  image_generation: { label: 'Görsel Üretim', icon: '🎨', color: 'from-neutral-400 to-neutral-500' },
  music_generation: { label: 'Müzik Üretim', icon: '🎵', color: 'from-neutral-600 to-neutral-700' },
  compositing: { label: 'Birleştirme', icon: '🎬', color: 'from-neutral-500 to-neutral-600' },
  encoding: { label: 'Kodlama', icon: '📦', color: 'from-neutral-400 to-neutral-500' },
};

interface RenderProgressProps {
  renderState: RenderProgressState;
  projectStatus?: string;
}

export function RenderProgress({ renderState, projectStatus }: RenderProgressProps) {
  const { progress, stage, stageLabel, currentScene, totalScenes, eta, status, isConnected } = renderState;

  if (status === 'idle') {
    return (
      <motion.div
        initial={{ opacity: 0, y: 12 }}
        animate={{ opacity: 1, y: 0 }}
        className="card-surface p-5 md:p-6"
      >
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-2.5">
            <Loader2 size={18} className="animate-spin text-amber-400" />
            <h3 className="text-sm font-semibold text-[var(--color-text-primary)]">
              {projectStatus === 'GENERATING_SCRIPT' ? 'AI Senaryo Üretiyor...' : 'İşlem kuyrukta veya başlatılıyor...'}
            </h3>
          </div>
          <div className="flex items-center gap-1.5">
            {isConnected ? (
              <Wifi size={13} className="text-emerald-400" />
            ) : (
              <WifiOff size={13} className="text-red-400" />
            )}
            <span className="text-[10px] text-[var(--color-text-ghost)]">
              {isConnected ? 'Canlı' : 'Bağlantı koptu'}
            </span>
          </div>
        </div>
      </motion.div>
    );
  }


  return (
    <motion.div
      initial={{ opacity: 0, y: 12 }}
      animate={{ opacity: 1, y: 0 }}
      className="card-surface p-5 md:p-6"
    >
      {/* Header */}
      <div className="flex items-center justify-between mb-4">
        <div className="flex items-center gap-2.5">
          {status === 'rendering' && (
            <Loader2 size={18} className="animate-spin text-neutral-400" />
          )}
          {status === 'completed' && (
            <CheckCircle2 size={18} className="text-emerald-400" />
          )}
          {status === 'failed' && (
            <XCircle size={18} className="text-red-400" />
          )}
          <h3 className="text-sm font-semibold text-[var(--color-text-primary)]">
            {status === 'rendering' && 'Video Üretiliyor...'}
            {status === 'completed' && 'Video Hazır!'}
            {status === 'failed' && 'Üretim Başarısız'}
          </h3>
        </div>

        {/* WebSocket bağlantı durumu */}
        <div className="flex items-center gap-1.5">
          {isConnected ? (
            <Wifi size={13} className="text-emerald-400" />
          ) : (
            <WifiOff size={13} className="text-red-400" />
          )}
          <span className="text-[10px] text-[var(--color-text-ghost)]">
            {isConnected ? 'Canlı' : 'Bağlantı koptu'}
          </span>
        </div>
      </div>

      {/* Ana Progress Bar */}
      <div className="mb-4">
        <div className="flex items-center justify-between mb-1.5">
          <span className="text-xs text-[var(--color-text-muted)]">{stageLabel}</span>
          <span className="text-xs font-mono font-semibold text-[var(--color-text-primary)]">
            %{Math.round(progress)}
          </span>
        </div>
        <div className="h-2.5 w-full rounded-full bg-[var(--color-bg-deep)] overflow-hidden">
          <motion.div
            className="h-full rounded-full bg-gradient-to-r from-neutral-500 via-neutral-400 to-neutral-300"
            initial={{ width: 0 }}
            animate={{ width: `${progress}%` }}
            transition={{ duration: 0.5, ease: 'easeOut' }}
          />
        </div>
      </div>

      {/* Aşama adımları */}
      {status === 'rendering' && (
        <div className="grid grid-cols-5 gap-1.5 mb-3">
          {STAGE_ORDER.map((s) => {
            const detail = STAGE_DETAILS[s];
            const stageIndex = STAGE_ORDER.indexOf(s);
            const currentIndex = STAGE_ORDER.indexOf(stage);
            const isDone = stageIndex < currentIndex;
            const isCurrent = s === stage;

            return (
              <div
                key={s}
                className={`flex flex-col items-center gap-1 py-2 px-1 rounded-lg transition-all ${
                  isCurrent
                    ? 'bg-[var(--color-bg-elevated)] border border-neutral-500/20'
                    : isDone
                    ? 'bg-neutral-500/10'
                    : 'opacity-40'
                }`}
              >
                <span className="text-sm">{detail.icon}</span>
                <span className="text-[9px] text-center text-[var(--color-text-ghost)] leading-tight">
                  {detail.label}
                </span>
                {isDone && <CheckCircle2 size={10} className="text-neutral-300" />}
                {isCurrent && <Loader2 size={10} className="animate-spin text-neutral-400" />}
              </div>
            );
          })}
        </div>
      )}

      {/* Alt bilgi */}
      <div className="flex items-center justify-between text-[10px] text-[var(--color-text-ghost)]">
        {currentScene > 0 && totalScenes > 0 && (
          <span>Sahne {currentScene}/{totalScenes}</span>
        )}
        {eta > 0 && status === 'rendering' && (
          <span>Tahmini kalan: ~{Math.ceil(eta / 60)} dk</span>
        )}
      </div>

      {/* Hata mesajı */}
      {status === 'failed' && renderState.error && (
        <div className="mt-3 p-3 rounded-lg bg-red-500/10 border border-red-500/20">
          <p className="text-xs text-red-400">{renderState.error}</p>
        </div>
      )}
    </motion.div>
  );
}
