'use client';

import { useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { Pencil, Check, X, RefreshCw, Clock, ArrowRight, Wand2, Image as ImageIcon, Mic, Maximize2, Sparkles } from 'lucide-react';

interface SceneCardProps {
  scene: {
    id: string;
    order: number;
    title?: string;
    narrationText: string;
    visualPrompt: string;
    subtitleText?: string;
    duration: number;
    transitionType: string;
    mediaAssets?: Array<{ id: string; type: string; url?: string }>;
  };
  isEditable: boolean;
  isRendering?: boolean;
  onUpdate?: (sceneId: string, data: { narrationText?: string; visualPrompt?: string; subtitleText?: string }) => void;
  onRegenerate?: (sceneId: string) => void;
  onGenerateImage?: (sceneId: string, customPrompt?: string) => void;
  onUpscaleImage?: (sceneId: string) => void;
  isRegenerating?: boolean;
  isGeneratingImage?: boolean;
  isUpscalingImage?: boolean;
}

export function SceneCard({
  scene,
  isEditable,
  isRendering = false,
  onUpdate,
  onRegenerate,
  onGenerateImage,
  onUpscaleImage,
  isRegenerating,
  isGeneratingImage,
  isUpscalingImage,
}: SceneCardProps) {
  const [isEditing, setIsEditing] = useState(false);
  const [editNarration, setEditNarration] = useState(scene.narrationText);
  const [editVisual, setEditVisual] = useState(scene.visualPrompt);
  const [lightboxOpen, setLightboxOpen] = useState(false);

  const handleSave = () => {
    onUpdate?.(scene.id, {
      narrationText: editNarration,
      visualPrompt: editVisual,
      subtitleText: editNarration,
    });
    // If user edited visual prompt, and maybe wants to generate, they can click generate visual later.
    setIsEditing(false);
  };

  const handleCancel = () => {
    setEditNarration(scene.narrationText);
    setEditVisual(scene.visualPrompt);
    setIsEditing(false);
  };

  const thumbnailAsset = scene.mediaAssets?.find(a => a.type === 'THUMBNAIL');

  return (
    <motion.div
      layout
      initial={{ opacity: 0, y: 12 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ delay: scene.order * 0.05, duration: 0.4 }}
      className="relative group"
    >
      <div className="card-surface p-4 md:p-5 hover:border-violet-500/20 transition-all duration-300">
        {/* Header */}
        <div className="flex items-center justify-between mb-3">
          <div className="flex items-center gap-2.5">
            <div className="w-8 h-8 rounded-lg bg-gradient-to-br from-violet-500/20 to-violet-600/10 flex items-center justify-center">
              <span className="text-xs font-bold text-violet-400">{scene.order}</span>
            </div>
            <div>
              <h4 className="text-sm font-semibold text-[var(--color-text-primary)]">
                {scene.title || `Sahne ${scene.order}`}
              </h4>
              <div className="flex items-center gap-2 mt-0.5">
                <span className="flex items-center gap-1 text-[10px] text-[var(--color-text-ghost)]">
                  <Clock size={10} /> {scene.duration}s
                </span>
                <span className="flex items-center gap-1 text-[10px] text-[var(--color-text-ghost)]">
                  <ArrowRight size={10} /> {scene.transitionType.toLowerCase()}
                </span>
              </div>
            </div>
          </div>

          {/* Aksiyon butonları */}
          {!isEditing && (
            <div className="flex items-center gap-1 opacity-100 md:opacity-0 md:group-hover:opacity-100 transition-opacity">
              <button
                onClick={() => setIsEditing(true)}
                disabled={!isEditable || isRendering}
                className="w-7 h-7 rounded-lg flex items-center justify-center text-[var(--color-text-muted)] hover:text-violet-400 hover:bg-violet-500/10 transition-colors disabled:opacity-40 disabled:cursor-not-allowed"
                title="Düzenle"
              >
                <Pencil size={13} />
              </button>
              <button
                onClick={() => onRegenerate?.(scene.id)}
                disabled={!isEditable || isRendering || isRegenerating}
                className="w-7 h-7 rounded-lg flex items-center justify-center text-[var(--color-text-muted)] hover:text-cyan-400 hover:bg-cyan-500/10 transition-colors disabled:opacity-40 disabled:cursor-not-allowed"
                title="AI ile yeniden üret"
              >
                <RefreshCw size={13} className={isRegenerating ? 'animate-spin' : ''} />
              </button>
            </div>
          )}
        </div>

        <AnimatePresence mode="wait">
          {isEditing ? (
            <motion.div
              key="editing"
              initial={{ opacity: 0, height: 0 }}
              animate={{ opacity: 1, height: 'auto' }}
              exit={{ opacity: 0, height: 0 }}
              className="space-y-3"
            >
              {/* Narrasyon düzenleme */}
              <div>
                <label className="flex items-center gap-1.5 text-xs font-medium text-[var(--color-text-muted)] mb-1.5">
                  <Mic size={12} /> Narrasyon
                </label>
                <textarea
                  value={editNarration}
                  onChange={(e) => setEditNarration(e.target.value)}
                  rows={3}
                  className="w-full px-3 py-2 rounded-lg bg-[var(--color-bg-deep)] border border-[var(--color-border-faint)] text-sm text-[var(--color-text-primary)] resize-none focus:outline-none focus:ring-1 focus:ring-violet-500/40 transition-all"
                />
              </div>

              {/* Görsel prompt düzenleme */}
              <div>
                <label className="flex items-center gap-1.5 text-xs font-medium text-[var(--color-text-muted)] mb-1.5">
                  <ImageIcon size={12} /> Görsel Prompt
                </label>
                <textarea
                  value={editVisual}
                  onChange={(e) => setEditVisual(e.target.value)}
                  rows={2}
                  className="w-full px-3 py-2 rounded-lg bg-[var(--color-bg-deep)] border border-[var(--color-border-faint)] text-sm text-[var(--color-text-secondary)] resize-none focus:outline-none focus:ring-1 focus:ring-cyan-500/40 transition-all"
                />
              </div>

              {/* Kaydet/İptal */}
              <div className="flex items-center gap-2 pt-1">
                <button
                  onClick={handleSave}
                  className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-violet-500/15 text-violet-400 text-xs font-medium hover:bg-violet-500/25 transition-colors"
                >
                  <Check size={13} /> Kaydet
                </button>
                <button
                  onClick={handleCancel}
                  className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-[var(--color-bg-elevated)] text-[var(--color-text-muted)] text-xs font-medium hover:text-[var(--color-text-secondary)] transition-colors"
                >
                  <X size={13} /> İptal
                </button>
              </div>
            </motion.div>
          ) : (
            <motion.div key="viewing" className="space-y-2.5">
              {/* Narrasyon */}
              <div className="flex gap-2">
                <div className="w-5 h-5 rounded-md bg-violet-500/10 flex items-center justify-center shrink-0 mt-0.5">
                  <Mic size={11} className="text-violet-400" />
                </div>
                <p className="text-sm text-[var(--color-text-secondary)] leading-relaxed">
                  {scene.narrationText}
                </p>
              </div>

              {/* Görsel Prompt */}
              <div className="flex gap-2">
                <div className="w-5 h-5 rounded-md bg-cyan-500/10 flex items-center justify-center shrink-0 mt-0.5">
                  <ImageIcon size={11} className="text-cyan-400" />
                </div>
                <div className="flex-1 group/prompt relative">
                  <p className="text-xs text-[var(--color-text-ghost)] leading-relaxed italic pr-6">
                    {scene.visualPrompt}
                  </p>
                  <button
                    onClick={() => {
                      navigator.clipboard.writeText(scene.visualPrompt);
                    }}
                    className="absolute top-0 right-0 p-1 opacity-0 group-hover/prompt:opacity-100 transition-opacity bg-[var(--color-bg-elevated)] rounded-md text-[var(--color-text-muted)] hover:text-cyan-400 hover:bg-cyan-500/10"
                    title="Prompt'u Kopyala"
                  >
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                      <rect width="14" height="14" x="8" y="8" rx="2" ry="2" />
                      <path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2" />
                    </svg>
                  </button>
                </div>
              </div>

              {/* Görsel / Upscale Alanı */}
              <div className="flex flex-col gap-2 pt-2">
                {thumbnailAsset?.url && !isGeneratingImage ? (
                  <div className="relative group/thumb rounded-lg overflow-hidden border border-[var(--color-border-faint)] aspect-video max-w-sm">
                    <img 
                      src={thumbnailAsset.url} 
                      alt="Scene Thumbnail" 
                      className="w-full h-full object-cover cursor-pointer hover:scale-105 transition-transform duration-500" 
                      onClick={() => setLightboxOpen(true)}
                    />
                    <div className="absolute inset-0 bg-black/40 opacity-0 group-hover/thumb:opacity-100 transition-opacity flex items-center justify-center pointer-events-none">
                       <Maximize2 size={24} className="text-white" />
                    </div>
                  </div>
                ) : (
                  <div className="rounded-lg border border-dashed border-[var(--color-border-faint)] bg-[var(--color-bg-deep)] aspect-video max-w-sm flex flex-col items-center justify-center p-4 relative overflow-hidden">
                    {isGeneratingImage ? (
                      <div className="flex flex-col items-center justify-center animate-in fade-in zoom-in duration-300">
                        <div className="relative w-12 h-12 mb-3">
                          <div className="absolute inset-0 rounded-full border-2 border-emerald-500/20"></div>
                          <div className="absolute inset-0 rounded-full border-2 border-emerald-500 border-t-transparent animate-spin"></div>
                          <Sparkles size={16} className="absolute inset-0 m-auto text-emerald-400 animate-pulse" />
                        </div>
                        <p className="text-xs font-medium text-emerald-400 text-center animate-pulse">
                          AI Görsel Üretiyor...
                        </p>
                      </div>
                    ) : (
                      <>
                        <ImageIcon size={24} className="text-[var(--color-text-ghost)] mb-2" />
                        <p className="text-xs text-[var(--color-text-muted)] text-center">Görsel Henüz Üretilmedi</p>
                      </>
                    )}
                  </div>
                )}
                
                {/* Görsel üretim butonları — tüm projelerde her zaman göster, render sürecinde disable et */}
                <div className="flex items-center gap-2 mt-1">
                  <button
                    onClick={() => onGenerateImage?.(scene.id, scene.visualPrompt)}
                    disabled={isGeneratingImage || isUpscalingImage}
                    className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-emerald-500/15 text-emerald-400 text-xs font-medium hover:bg-emerald-500/25 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    {isGeneratingImage ? <RefreshCw size={13} className="animate-spin" /> : <ImageIcon size={13} />}
                    {thumbnailAsset ? "Görseli Yeniden Üret" : "Görsel Üret"}
                  </button>
                  {thumbnailAsset?.url && (
                    <button
                      onClick={() => onUpscaleImage?.(scene.id)}
                      disabled={isUpscalingImage || isGeneratingImage}
                      className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-orange-500/15 text-orange-400 text-xs font-medium hover:bg-orange-500/25 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                    >
                      {isUpscalingImage ? <RefreshCw size={13} className="animate-spin" /> : <Wand2 size={13} />}
                      Upscale (4K)
                    </button>
                  )}
                </div>
              </div>
            </motion.div>
          )}
        </AnimatePresence>
      </div>

      {/* Sahne bağlantı çizgisi */}
      <div className="absolute left-7 -bottom-3 w-px h-3 bg-gradient-to-b from-[var(--color-border-faint)] to-transparent" />
      
      {/* Lightbox Modal */}
      <AnimatePresence>
        {lightboxOpen && thumbnailAsset?.url && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            onClick={() => setLightboxOpen(false)}
            className="fixed inset-0 z-[100] flex items-center justify-center bg-black/80 backdrop-blur-sm p-4 md:p-10 cursor-zoom-out"
          >
            <motion.img 
              initial={{ scale: 0.9, opacity: 0 }}
              animate={{ scale: 1, opacity: 1 }}
              exit={{ scale: 0.9, opacity: 0 }}
              transition={{ type: "spring", damping: 25, stiffness: 300 }}
              src={thumbnailAsset.url}
              alt="Fullscreen Scene"
              className="max-w-full max-h-full object-contain rounded-xl shadow-2xl"
              onClick={(e) => e.stopPropagation()} // Click image prevents closing
            />
            <button 
              onClick={() => setLightboxOpen(false)}
              className="absolute top-6 right-6 p-2 rounded-full bg-black/50 text-white/70 hover:text-white hover:bg-black/70 transition-colors"
            >
              <X size={24} />
            </button>
          </motion.div>
        )}
      </AnimatePresence>
    </motion.div>
  );
}
