import React, { useState, useEffect, useRef } from 'react';
import { 
  Plus, Trash2, Edit3, Download, Play, Pause, ChevronDown, 
  Settings, Save, X, FileText, UploadCloud, RefreshCw, 
  Volume2, Clock, FileVideo, Check, AlertTriangle, Zap, 
  Layers, Grid, ArrowLeft, ArrowRight, Move, Eye
} from 'lucide-react';

// Shadcn UI components
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Badge } from '@/components/ui/badge';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog';
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card';
import { Switch } from '@/components/ui/switch';
import { Progress } from '@/components/ui/progress';
import { Checkbox } from '@/components/ui/checkbox';
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
import { Textarea } from '@/components/ui/textarea';

const VideoGeneratorApp = () => {
  // State management
  const [activeTab, setActiveTab] = useState("blocks");
  const [currentBlock, setCurrentBlock] = useState(null);
  const [isPlaying, setIsPlaying] = useState(false);
  const [progress, setProgress] = useState(0);
  const [showEditor, setShowEditor] = useState(false);
  const [targetLanguage, setTargetLanguage] = useState("es-ES");
  const [nativeLanguage, setNativeLanguage] = useState("en-US");
  const [currentTime, setCurrentTime] = useState(0);
  const [duration, setDuration] = useState(15);
  const [editingElement, setEditingElement] = useState(null);
  const timelineRef = useRef(null);
  const previewRef = useRef(null);
  
  // Project data
  const [projectName, setProjectName] = useState("Vocabulary Project");
  const [showNotification, setShowNotification] = useState(false);
  const [notificationMessage, setNotificationMessage] = useState("");
  const [generatingStatus, setGeneratingStatus] = useState(null);
  const [renderQueue, setRenderQueue] = useState([]);
  const [selectedAnimationStyle, setSelectedAnimationStyle] = useState("fadeIn");
  const [audioSyncEnabled, setAudioSyncEnabled] = useState(true);
  
  // Content data
  const [content, setContent] = useState([
    {
      id: 1,
      targetWord: "médico",
      nativeWord: "doctor",
      targetPhrase1: "quiere ser médico",
      nativePhrase1: "he wants to be a doctor",
      targetPhrase2: "su médico es bueno",
      nativePhrase2: "his doctor is good",
    },
    {
      id: 2,
      targetWord: "abogado",
      nativeWord: "lawyer",
      targetPhrase1: "estudia para abogado",
      nativePhrase1: "he studies to be a lawyer",
      targetPhrase2: "necesita un abogado",
      nativePhrase2: "he needs a lawyer",
    }
  ]);
  
  const [currentContentIndex, setCurrentContentIndex] = useState(0);
  const [newRow, setNewRow] = useState({
    targetWord: "",
    nativeWord: "",
    targetPhrase1: "",
    nativePhrase1: "",
    targetPhrase2: "",
    nativePhrase2: ""
  });
  
  // Blocks
  const [blocks, setBlocks] = useState([
    { 
      id: "vocab-block", 
      name: "Vocabulary Block", 
      description: "Standard vocabulary block with word and phrases",
      duration: 15,
      background: "linear-gradient(135deg, #1a1a2e 0%, #16213e 100%)"
    },
    { 
      id: "grammar-block", 
      name: "Grammar Block", 
      description: "Block for grammar explanations with examples",
      duration: 20,
      background: "linear-gradient(135deg, #16213e 0%, #0f3460 100%)"
    },
    { 
      id: "conversation-block", 
      name: "Conversation Block", 
      description: "Dialog-based block for conversation practice",
      duration: 30,
      background: "linear-gradient(135deg, #0f3460 0%, #950740 100%)"
    }
  ]);
  
  // Timeline elements
  const [timelineElements, setTimelineElements] = useState([
    { 
      id: "el-1", 
      type: "text", 
      content: "Vocabulary Word", 
      start: 0, 
      duration: 3, 
      position: {x: 50, y: 20}, 
      style: {color: "#ffffff", fontSize: 36, fontWeight: "bold"},
      animation: "fadeIn",
      contentKey: "targetWord" 
    },
    { 
      id: "el-2", 
      type: "block", 
      content: "Color Block", 
      start: 0.5, 
      duration: 12, 
      position: {x: 30, y: 35}, 
      style: {width: 200, height: 200, borderRadius: "8px", background: "linear-gradient(45deg, #3490dc, #6574cd)"},
      animation: "zoomIn"
    },
    { 
      id: "el-3", 
      type: "text", 
      content: "Example Phrase 1", 
      start: 4, 
      duration: 3, 
      position: {x: 50, y: 65}, 
      style: {color: "#ffffff", fontSize: 24},
      animation: "slideIn",
      contentKey: "targetPhrase1"
    },
    { 
      id: "el-4", 
      type: "text", 
      content: "Example Phrase 2", 
      start: 8, 
      duration: 3, 
      position: {x: 50, y: 80}, 
      style: {color: "#ffffff", fontSize: 24},
      animation: "slideIn",
      contentKey: "targetPhrase2"
    },
    { 
      id: "el-5", 
      type: "audio", 
      content: "narration.mp3", 
      start: 0, 
      duration: 15
    },
  ]);
  
  // Notification helper
  const showNotify = (message) => {
    setNotificationMessage(message);
    setShowNotification(true);
    setTimeout(() => setShowNotification(false), 3000);
  };
  
  // Block selection
  const selectBlock = (blockId) => {
    setCurrentBlock(blocks.find(b => b.id === blockId));
    showNotify("Block selected: " + blocks.find(b => b.id === blockId).name);
    setActiveTab("content");
  };
  
  // Add new content row
  const addContentRow = () => {
    if (!newRow.targetWord || !newRow.nativeWord) {
      showNotify("Target and native words are required");
      return;
    }
    
    setContent([...content, { 
      id: content.length + 1,
      ...newRow
    }]);
    
    setNewRow({
      targetWord: "",
      nativeWord: "",
      targetPhrase1: "",
      nativePhrase1: "",
      targetPhrase2: "",
      nativePhrase2: ""
    });
    
    showNotify("New content row added");
  };
  
  // Delete content row
  const deleteContentRow = (id) => {
    setContent(content.filter(row => row.id !== id));
    showNotify("Content row deleted");
  };
  
  // Toggle play/pause
  const togglePlayback = () => {
    setIsPlaying(!isPlaying);
  };
  
  // Animation preview
  useEffect(() => {
    let interval;
    if (isPlaying) {
      interval = setInterval(() => {
        setCurrentTime(time => {
          const newTime = time + 0.1;
          if (newTime >= duration) {
            setIsPlaying(false);
            return 0;
          }
          return newTime;
        });
        
        setProgress(prog => {
          const newProg = prog + (100 / (duration * 10));
          return newProg > 100 ? 0 : newProg;
        });
      }, 100);
    }
    
    return () => clearInterval(interval);
  }, [isPlaying, duration]);
  
  // Handle timeline scrubbing
  const handleTimelineClick = (e) => {
    if (!timelineRef.current) return;
    
    const rect = timelineRef.current.getBoundingClientRect();
    const clickPosition = e.clientX - rect.left;
    const percentClicked = clickPosition / rect.width;
    const newTime = percentClicked * duration;
    
    setCurrentTime(Math.max(0, Math.min(newTime, duration)));
    setProgress(percentClicked * 100);
  };
  
  // Open element editor
  const openElementEditor = (element) => {
    setEditingElement(element);
    setShowEditor(true);
  };
  
  // Update element
  const updateElement = (updatedElement) => {
    setTimelineElements(elements => 
      elements.map(el => el.id === updatedElement.id ? updatedElement : el)
    );
    setShowEditor(false);
    showNotify("Element updated");
  };
  
  // Add new element
  const addTimelineElement = (type) => {
    const newElement = {
      id: `el-${Date.now()}`,
      type,
      content: type === 'text' ? 'New Text' : type === 'block' ? 'Color Block' : 'audio.mp3',
      start: currentTime,
      duration: type === 'audio' ? 5 : 3,
      position: type !== 'audio' ? {x: 50, y: 50} : undefined,
      style: type === 'text' ? {color: "#ffffff", fontSize: 24} : 
             type === 'block' ? {
               width: 150, 
               height: 150, 
               borderRadius: "8px", 
               background: "linear-gradient(45deg, #3490dc, #6574cd)"
             } : undefined,
      animation: type !== 'audio' ? selectedAnimationStyle : undefined
    };
    
    setTimelineElements([...timelineElements, newElement]);
    setEditingElement(newElement);
    setShowEditor(true);
    showNotify(`New ${type} element added`);
  };
  
  // Generate audio
  const generateAudio = () => {
    showNotify("Generating audio for content...");
    
    // Simulate audio generation
    setTimeout(() => {
      showNotify("Audio generation complete!");
    }, 1500);
  };
  
  // Generate videos for all content
  const generateAllVideos = () => {
    if (!currentBlock) {
      showNotify("Please select a block first");
      return;
    }
    
    if (content.length === 0) {
      showNotify("No content to generate");
      return;
    }
    
    // Create render queue
    const queue = content.map(item => ({
      id: `render-${item.id}`,
      content: item,
      block: currentBlock,
      status: "pending",
      progress: 0
    }));
    
    setRenderQueue(queue);
    setGeneratingStatus("preparing");
    
    // Simulate processing
    setTimeout(() => {
      setGeneratingStatus("processing");
      
      let currentIndex = 0;
      const processNext = () => {
        if (currentIndex >= queue.length) {
          setGeneratingStatus("complete");
          return;
        }
        
        const updatedQueue = [...queue];
        updatedQueue[currentIndex].status = "processing";
        setRenderQueue(updatedQueue);
        
        // Simulate processing time
        let progress = 0;
        const interval = setInterval(() => {
          progress += 10;
          
          const newQueue = [...updatedQueue];
          newQueue[currentIndex].progress = progress;
          setRenderQueue(newQueue);
          
          if (progress >= 100) {
            clearInterval(interval);
            newQueue[currentIndex].status = "complete";
            setRenderQueue(newQueue);
            currentIndex++;
            setTimeout(processNext, 500);
          }
        }, 300);
      };
      
      processNext();
    }, 1500);
  };
  
  // Reset progress for new render
  const startNewProject = () => {
    setCurrentBlock(null);
    setActiveTab("blocks");
    setProjectName("New Project");
    setContent([]);
    setRenderQueue([]);
    setGeneratingStatus(null);
    showNotify("Started new project");
  };
  
  // Get element animation state
  const getElementAnimationState = (element) => {
    if (currentTime < element.start) {
      return "before";
    } else if (currentTime >= element.start && currentTime < element.start + element.duration) {
      return "active";
    } else {
      return "after";
    }
  };
  
  // Get real content based on timeline element
  const getElementContent = (element) => {
    if (!element.contentKey || currentContentIndex >= content.length) {
      return element.content;
    }
    
    const contentItem = content[currentContentIndex];
    return contentItem[element.contentKey] || element.content;
  };
  
  return (
    <div className="flex flex-col h-screen bg-slate-50 overflow-hidden">
      {/* Header */}
      <header className="border-b bg-white shadow-sm z-10">
        <div className="container mx-auto px-4 py-3 flex items-center justify-between">
          <div className="flex items-center space-x-2">
            <FileVideo className="h-6 w-6 text-blue-600" />
            <h1 className="text-xl font-bold tracking-tight">VideoGen Pro</h1>
          </div>
          
          <div className="flex space-x-2">
            <Input
              className="w-60"
              value={projectName}
              onChange={(e) => setProjectName(e.target.value)}
              placeholder="Project Name"
            />
            
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button variant="outline" size="sm">
                  <FileText className="h-4 w-4 mr-1" /> Project
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent>
                <DropdownMenuItem onClick={startNewProject}>
                  New Project
                </DropdownMenuItem>
                <DropdownMenuItem>
                  Load Project
                </DropdownMenuItem>
                <DropdownMenuItem>
                  Save Project
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
            
            <Button size="sm">
              <Download className="h-4 w-4 mr-1" /> Export
            </Button>
            
            <Button variant="ghost" size="icon">
              <Settings className="h-5 w-5" />
            </Button>
          </div>
        </div>
      </header>
      
      {/* Main Content */}
      <div className="flex-1 flex overflow-hidden">
        {/* Left Sidebar */}
        <div className="w-56 border-r bg-white">
          <div className="p-4">
            <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
              <TabsList className="grid grid-cols-2 mb-4">
                <TabsTrigger value="blocks">Blocks</TabsTrigger>
                <TabsTrigger value="content">Content</TabsTrigger>
              </TabsList>
            </Tabs>
            
            <div className="space-y-2">
              <Button 
                variant={activeTab === "blocks" ? "default" : "outline"} 
                className="w-full justify-start" 
                onClick={() => setActiveTab("blocks")}
              >
                <Layers className="h-4 w-4 mr-2" />
                Blocks
              </Button>
              
              <Button 
                variant={activeTab === "content" ? "default" : "outline"} 
                className="w-full justify-start" 
                onClick={() => setActiveTab("content")}
              >
                <FileText className="h-4 w-4 mr-2" />
                Content
              </Button>
              
              <Button 
                variant={activeTab === "editor" ? "default" : "outline"} 
                className="w-full justify-start" 
                onClick={() => setActiveTab("editor")}
              >
                <Edit3 className="h-4 w-4 mr-2" />
                Editor
              </Button>
              
              <Button 
                variant={activeTab === "generate" ? "default" : "outline"} 
                className="w-full justify-start" 
                onClick={() => setActiveTab("generate")}
              >
                <Zap className="h-4 w-4 mr-2" />
                Generate
              </Button>
            </div>
            
            {activeTab === "editor" && (
              <div className="mt-6 space-y-2 border-t pt-4">
                <h3 className="text-sm font-medium text-slate-500">Add Elements</h3>
                <div className="grid grid-cols-3 gap-2">
                  <Button variant="outline" size="sm" className="w-full p-1" onClick={() => addTimelineElement("text")}>
                    <FileText className="h-4 w-4" />
                  </Button>
                  <Button variant="outline" size="sm" className="w-full p-1" onClick={() => addTimelineElement("block")}>
                    <Layers className="h-4 w-4" />
                  </Button>
                  <Button variant="outline" size="sm" className="w-full p-1" onClick={() => addTimelineElement("audio")}>
                    <Volume2 className="h-4 w-4" />
                  </Button>
                </div>
                
                <h3 className="text-sm font-medium text-slate-500 mt-4">Animation Style</h3>
                <Select value={selectedAnimationStyle} onValueChange={setSelectedAnimationStyle}>
                  <SelectTrigger className="w-full">
                    <SelectValue placeholder="Animation Style" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="fadeIn">Fade In</SelectItem>
                    <SelectItem value="slideIn">Slide In</SelectItem>
                    <SelectItem value="zoomIn">Zoom In</SelectItem>
                    <SelectItem value="bounceIn">Bounce In</SelectItem>
                    <SelectItem value="flipIn">Flip In</SelectItem>
                  </SelectContent>
                </Select>
                
                <div className="flex items-center justify-between mt-4">
                  <Label htmlFor="audio-sync" className="text-sm">
                    Auto-sync to Audio
                  </Label>
                  <Switch 
                    id="audio-sync" 
                    checked={audioSyncEnabled} 
                    onCheckedChange={setAudioSyncEnabled} 
                  />
                </div>
              </div>
            )}
          </div>
        </div>
        
        {/* Main Panel */}
        <div className="flex-1 overflow-auto">
          <div className="container mx-auto p-6">
            {activeTab === "blocks" && (
              <div className="space-y-6">
                <div className="flex justify-between items-center">
                  <h2 className="text-2xl font-bold">Video Blocks</h2>
                  <Button size="sm">
                    <Plus className="h-4 w-4 mr-1" /> Import Block
                  </Button>
                </div>
                
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                  {blocks.map(block => (
                    <Card key={block.id} className={`overflow-hidden transition-all ${currentBlock?.id === block.id ? 'ring-2 ring-blue-500' : ''}`}>
                      <div className="aspect-video relative overflow-hidden" 
                        style={{ background: block.background }}
                      >
                        <div className="absolute inset-0 flex items-center justify-center">
                          <div className="w-24 h-24 rounded" 
                            style={{ background: "rgba(255,255,255,0.1)" }}
                          />
                        </div>
                        <div 
                          className="absolute inset-0 bg-gradient-to-t from-black/70 to-transparent flex flex-col justify-end p-4"
                        >
                          <h3 className="text-lg font-medium text-white">{block.name}</h3>
                          <p className="text-sm text-white/80">{block.description}</p>
                        </div>
                        <Badge className="absolute top-2 right-2">
                          {block.duration}s
                        </Badge>
                      </div>
                      <CardFooter className="bg-white p-3">
                        <Button 
                          className="w-full" 
                          onClick={() => selectBlock(block.id)}
                        >
                          {currentBlock?.id === block.id ? (
                            <>
                              <Check className="h-4 w-4 mr-1" />
                              Selected
                            </>
                          ) : "Select Block"}
                        </Button>
                      </CardFooter>
                    </Card>
                  ))}
                </div>
              </div>
            )}
            
            {activeTab === "content" && (
              <div className="space-y-6">
                <div className="flex justify-between items-center">
                  <h2 className="text-2xl font-bold">Content</h2>
                  <div className="flex space-x-2">
                    <Select value={targetLanguage} onValueChange={setTargetLanguage}>
                      <SelectTrigger className="w-40">
                        <SelectValue placeholder="Target Language" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="es-ES">Español</SelectItem>
                        <SelectItem value="fr-FR">Français</SelectItem>
                        <SelectItem value="de-DE">Deutsch</SelectItem>
                        <SelectItem value="it-IT">Italiano</SelectItem>
                        <SelectItem value="pt-PT">Português</SelectItem>
                      </SelectContent>
                    </Select>
                    
                    <Select value={nativeLanguage} onValueChange={setNativeLanguage}>
                      <SelectTrigger className="w-40">
                        <SelectValue placeholder="Native Language" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="en-US">English</SelectItem>
                        <SelectItem value="es-ES">Español</SelectItem>
                        <SelectItem value="fr-FR">Français</SelectItem>
                        <SelectItem value="de-DE">Deutsch</SelectItem>
                        <SelectItem value="it-IT">Italiano</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>
                
                <div className="bg-white rounded-md shadow overflow-hidden">
                  <div className="border-b px-4 py-2 bg-slate-50 grid grid-cols-7 gap-4 font-medium text-sm">
                    <div className="col-span-1">Target Word</div>
                    <div className="col-span-1">Native Word</div>
                    <div className="col-span-2">Target Phrase 1</div>
                    <div className="col-span-2">Native Phrase 1</div>
                    <div className="col-span-1">Actions</div>
                  </div>
                  
                  {content.map(row => (
                    <div key={row.id} className="px-4 py-3 border-b grid grid-cols-7 gap-4 items-center">
                      <div className="col-span-1">{row.targetWord}</div>
                      <div className="col-span-1">{row.nativeWord}</div>
                      <div className="col-span-2">{row.targetPhrase1}</div>
                      <div className="col-span-2">{row.nativePhrase1}</div>
                      <div className="col-span-1 flex space-x-1">
                        <Button variant="ghost" size="icon" onClick={() => setCurrentContentIndex(content.indexOf(row))}>
                          <Eye className="h-4 w-4" />
                        </Button>
                        <Button variant="ghost" size="icon" onClick={() => deleteContentRow(row.id)}>
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </div>
                    </div>
                  ))}
                  
                  <div className="px-4 py-3 grid grid-cols-7 gap-4 items-center bg-slate-50">
                    <div className="col-span-1">
                      <Input 
                        placeholder="Target Word" 
                        value={newRow.targetWord}
                        onChange={(e) => setNewRow({...newRow, targetWord: e.target.value})}
                      />
                    </div>
                    <div className="col-span-1">
                      <Input 
                        placeholder="Native Word" 
                        value={newRow.nativeWord}
                        onChange={(e) => setNewRow({...newRow, nativeWord: e.target.value})}
                      />
                    </div>
                    <div className="col-span-2">
                      <Input 
                        placeholder="Target Phrase 1" 
                        value={newRow.targetPhrase1}
                        onChange={(e) => setNewRow({...newRow, targetPhrase1: e.target.value})}
                      />
                    </div>
                    <div className="col-span-2">
                      <Input 
                        placeholder="Native Phrase 1" 
                        value={newRow.nativePhrase1}
                        onChange={(e) => setNewRow({...newRow, nativePhrase1: e.target.value})}
                      />
                    </div>
                    <div className="col-span-1">
                      <Button onClick={addContentRow}>
                        <Plus className="h-4 w-4 mr-1" /> Add
                      </Button>
                    </div>
                  </div>
                </div>
                
                <div className="flex justify-between">
                  <Button variant="outline" onClick={generateAudio}>
                    <Volume2 className="h-4 w-4 mr-1" /> Generate Audio
                  </Button>
                  
                  <Button onClick={() => setActiveTab("editor")}>
                    Continue to Editor <ChevronDown className="h-4 w-4 ml-1 rotate-270" />
                  </Button>
                </div>
              </div>
            )}
            
            {(activeTab === "editor" || activeTab === "generate") && (
              <div className="space-y-6">
                <div className="flex justify-between items-center">
                  <h2 className="text-2xl font-bold">
                    {activeTab === "editor" ? "Block Editor" : "Generate Videos"}
                  </h2>
                  {activeTab === "generate" && (
                    <div className="flex space-x-2">
                      <Select defaultValue="1080p">
                        <SelectTrigger className="w-32">
                          <SelectValue placeholder="Resolution" />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="720p">720p</SelectItem>
                          <SelectItem value="1080p">1080p</SelectItem>
                          <SelectItem value="4k">4K</SelectItem>
                        </SelectContent>
                      </Select>
                      
                      <Select defaultValue="mp4">
                        <SelectTrigger className="w-32">
                          <SelectValue placeholder="Format" />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="mp4">MP4 (H.264)</SelectItem>
                          <SelectItem value="webm">WebM</SelectItem>
                          <SelectItem value="gif">GIF</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                  )}
                </div>
                
                {/* Preview and Timeline Area */}
                <div className="space-y-4">
                  {/* Preview Area */}
                  <div 
                    ref={previewRef}
                    className="aspect-video rounded-lg relative overflow-hidden"
                    style={{ 
                      background: currentBlock?.background || "linear-gradient(135deg, #1a1a2e 0%, #16213e 100%)"
                    }}
                  >
                    {/* Preview elements */}
                    {timelineElements.map(element => {
                      if (element.type === 'audio') return null; // Audio doesn't render visually
                      
                      const animationState = getElementAnimationState(element);
                      if (animationState === "before") return null;
                      
                      // Calculate opacity based on time
                      const opacity = animationState === "active" ? 1 : 0;
                      
                      return (
                        <div
                          key={element.id}
                          className="absolute"
                          style={{
                            left: `${element.position?.x || 0}%`,
                            top: `${element.position?.y || 0}%`,
                            opacity,
                            transition: 'opacity 0.3s',
                            cursor: 'move',
                            transform: 'translate(-50%, -50%)'
                          }}
                          onClick={() => openElementEditor(element)}
                        >
                          {element.type === 'text' ? (
                            <div 
                              style={{
                                color: element.style?.color || 'white',
                                fontSize: `${element.style?.fontSize || 24}px`,
                                fontWeight: element.style?.fontWeight || 'normal',
                                textShadow: '0 1px 2px rgba(0,0,0,0.5)',
                                whiteSpace: 'nowrap'
                              }}
                            >
                              {getElementContent(element)}
                            </div>
                          ) : element.type === 'block' ? (
                            <div 
                              style={{
                                width: `${element.style?.width || 100}px`,
                                height: `${element.style?.height || 100}px`,
                                borderRadius: element.style?.borderRadius || '0px',
                                background: element.style?.background || 'rgba(255,255,255,0.2)'
                              }}
                            />
                          ) : null}
                        </div>
                      );
                    })}
                    
                    {/* Controls */}
                    <div className="absolute bottom-4 left-1/2 transform -translate-x-1/2 flex space-x-2 bg-black/70 rounded-full p-2">
                      <Button variant="ghost" size="icon" className="text-white">
                        <ArrowLeft className="h-4 w-4" />
                      </Button>
                      <Button variant="ghost" size="icon" className="text-white" onClick={togglePlayback}>
                        {isPlaying ? <Pause className="h-5 w-5" /> : <Play className="h-5 w-5" />}
                      </Button>
                      <Button variant="ghost" size="icon" className="text-white">
                        <ArrowRight className="h-4 w-4" />
                      </Button>
                    </div>
                    
                    {/* Timeline progress */}
                    <div className="absolute bottom-0 left-0 right-0 h-1 bg-gray-700">
                      <div 
                        className="h-full bg-blue-500 transition-all" 
                        style={{ width: `${progress}%` }}
                      ></div>
                    </div>
                  </div>
                  
                  {/* Timeline */}
                  <div 
                    ref={timelineRef}
                    className="h-16 bg-gray-800 rounded relative overflow-hidden cursor-pointer"
                    onClick={handleTimelineClick}
                  >
                    {/* Time markers */}
                    <div className="absolute top-0 left-0 right-0 h-4 flex text-xs text-gray-400">
                      {Array.from({ length: Math.ceil(duration) + 1 }).map((_, i) => (
                        <div 
                          key={i} 
                          className="border-l border-gray-700 h-full flex items-center px-1"
                          style={{ 
                            position: 'absolute', 
                            left: `${(i / duration) * 100}%`
                          }}
                        >
                          {i}s
                        </div>
                      ))}
                    </div>
                    
                    {/* Elements timeline */}
                    <div className="absolute top-4 left-0 right-0 bottom-0 px-2">
                      {timelineElements.map(element => (
                        <div 
                          key={element.id}
                          className={`absolute h-5 rounded cursor-pointer ${
                            element.type === 'text' ? 'bg-blue-600/70' : 
                            element.type === 'block' ? 'bg-green-600/70' : 
                            'bg-purple-600/70'
                          } ${currentTime >= element.start && currentTime < element.start + element.duration ? 'ring-1 ring-white' : ''}`}
                          style={{
                            left: `${(element.start / duration) * 100}%`,
                            width: `${(element.duration / duration) * 100}%`,
                            top: element.type === 'audio' ? '7px' : '0px'
                          }}
                          onClick={(e) => {
                            e.stopPropagation();
                            openElementEditor(element);
                          }}
                        >
                          <div className="truncate text-xs text-white px-1 py-0.5">
                            {element.type === 'text' ? getElementContent(element).substring(0, 10) : element.type}
                            {element.type === 'text' && getElementContent(element).length > 10 ? '...' : ''}
                          </div>
                        </div>
                      ))}
                    </div>
                    
                    {/* Current time indicator */}
                    <div className="absolute top-0 bottom-0 w-px bg-red-500 z-10" style={{ left: `${(currentTime / duration) * 100}%` }}>
                      <div className="w-2 h-2 bg-red-500 rounded-full -ml-1"></div>
                    </div>
                  </div>
                  
                  <div className="flex justify-between">
                    <div className="flex space-x-2">
                      <Button 
                        variant="outline" 
                        size="sm" 
                        onClick={() => setCurrentContentIndex(prev => (prev > 0 ? prev - 1 : 0))}
                        disabled={currentContentIndex <= 0}
                      >
                        <ArrowLeft className="h-4 w-4 mr-1" />
                        Previous
                      </Button>
                      <Button 
                        variant="outline" 
                        size="sm" 
                        onClick={() => setCurrentContentIndex(prev => (prev < content.length - 1 ? prev + 1 : prev))}
                        disabled={currentContentIndex >= content.length - 1}
                      >
                        Next
                        <ArrowRight className="h-4 w-4 ml-1" />
                      </Button>
                      <div className="bg-slate-100 rounded px-2 py-1 text-sm flex items-center">
                        Item {currentContentIndex + 1} of {content.length}
                      </div>
                    </div>
                    
                    {activeTab === "editor" && (
                      <Button onClick={() => setActiveTab("generate")}>
                        Continue to Generate <ChevronDown className="h-4 w-4 ml-1 rotate-270" />
                      </Button>
                    )}
                    
                    {activeTab === "generate" && (
                      <Button onClick={generateAllVideos} disabled={generatingStatus === "processing" || generatingStatus === "preparing"}>
                        {generatingStatus === "complete" ? 
                          <><RefreshCw className="h-4 w-4 mr-1" /> Generate More</> : 
                          generatingStatus === "processing" || generatingStatus === "preparing" ? 
                            <><RefreshCw className="h-4 w-4 mr-1 animate-spin" /> Processing...</> : 
                            <><Zap className="h-4 w-4 mr-1" /> Generate All Videos</>}
                      </Button>
                    )}
                  </div>
                </div>
                
                {activeTab === "generate" && (
                  <div className="mt-6">
                    <Alert className={generatingStatus === "complete" ? "bg-green-50 border-green-200" : "bg-blue-50 border-blue-200"}>
                      <AlertDescription className={generatingStatus === "complete" ? "text-green-700" : "text-blue-700"}>
                        {generatingStatus === "complete" ? 
                          `Successfully generated ${renderQueue.length} videos.` : 
                          generatingStatus === "processing" ? 
                            `Processing ${renderQueue.filter(item => item.status === "complete").length} of ${renderQueue.length} videos...` : 
                            generatingStatus === "preparing" ?
                              "Setting up render queue..." :
                              "Click the button below to generate videos for all content."}
                      </AlertDescription>
                    </Alert>
                    
                    <Card className="mt-4">
                      <CardHeader>
                        <CardTitle>Generation Queue</CardTitle>
                        <CardDescription>
                          {content.length} videos to generate using {currentBlock?.name || "selected block"}
                        </CardDescription>
                      </CardHeader>
                      <CardContent className="space-y-4">
                        {renderQueue.length > 0 ? (
                          renderQueue.map(item => (
                            <div key={item.id} className="flex items-center space-x-4">
                              <div className="w-8 h-8 rounded-full bg-slate-100 flex items-center justify-center">
                                {item.status === "complete" ? 
                                  <Check className="h-4 w-4 text-green-500" /> : 
                                  item.status === "processing" ?
                                    <RefreshCw className="h-4 w-4 text-blue-500 animate-spin" /> :
                                    <Clock className="h-4 w-4 text-slate-400" />}
                              </div>
                              <div className="flex-1">
                                <div className="font-medium">{item.content.targetWord} - {item.content.nativeWord}</div>
                                <Progress 
                                  value={item.progress} 
                                  className="h-2 mt-1"
                                />
                              </div>
                              <div className="text-sm text-slate-500">
                                {item.status === "complete" ? 
                                  "Complete" : 
                                  item.status === "processing" ?
                                    `${item.progress}%` :
                                    "Pending"}
                              </div>
                              <Button 
                                variant="ghost" 
                                size="icon" 
                                disabled={item.status !== "complete"}
                              >
                                <Download className="h-4 w-4" />
                              </Button>
                            </div>
                          ))
                        ) : (
                          <div className="text-center py-8 text-slate-500">
                            <Grid className="h-8 w-8 mx-auto mb-2" />
                            <p>No videos in queue yet</p>
                            <p className="text-sm">Click the "Generate All Videos" button to start generation</p>
                          </div>
                        )}
                      </CardContent>
                      <CardFooter className="flex justify-between">
                        <div>
                          <div className="flex items-center space-x-2">
                            <Checkbox id="audio-checkbox" checked />
                            <Label htmlFor="audio-checkbox">Include audio</Label>
                          </div>
                        </div>
                      </CardFooter>
                    </Card>
                  </div>
                )}
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Element Editor Dialog */}
      <Dialog open={showEditor} onOpenChange={setShowEditor}>
        <DialogContent className="sm:max-w-[500px]">
          <DialogHeader>
            <DialogTitle>Edit Element</DialogTitle>
            <DialogDescription>
              Adjust properties for this timeline element
            </DialogDescription>
          </DialogHeader>
          
          {editingElement && (
            <div className="space-y-4 pt-2">
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label>Start Time (seconds)</Label>
                  <Input 
                    type="number" 
                    min="0" 
                    step="0.1" 
                    value={editingElement.start} 
                    onChange={(e) => setEditingElement({...editingElement, start: parseFloat(e.target.value)})}
                  />
                </div>
                
                <div className="space-y-2">
                  <Label>Duration (seconds)</Label>
                  <Input 
                    type="number" 
                    min="0.1" 
                    step="0.1" 
                    value={editingElement.duration} 
                    onChange={(e) => setEditingElement({...editingElement, duration: parseFloat(e.target.value)})}
                  />
                </div>
              </div>
              
              {editingElement.type === "text" && (
                <>
                  <div className="space-y-2">
                    <Label>Text Content</Label>
                    <Textarea 
                      value={editingElement.content} 
                      onChange={(e) => setEditingElement({...editingElement, content: e.target.value})}
                    />
                  </div>
                  
                  <div className="grid grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <Label>Font Size</Label>
                      <Input 
                        type="number" 
                        value={editingElement.style?.fontSize || 24} 
                        onChange={(e) => setEditingElement({
                          ...editingElement, 
                          style: {...editingElement.style, fontSize: parseInt(e.target.value)}
                        })}
                      />
                    </div>
                    
                    <div className="space-y-2">
                      <Label>Text Color</Label>
                      <Input 
                        type="color" 
                        value={editingElement.style?.color || "#ffffff"} 
                        onChange={(e) => setEditingElement({
                          ...editingElement, 
                          style: {...editingElement.style, color: e.target.value}
                        })}
                      />
                    </div>
                  </div>
                  
                  <div className="space-y-2">
                    <Label>Content Link</Label>
                    <Select 
                      value={editingElement.contentKey || "none"} 
                      onValueChange={(val) => setEditingElement({
                        ...editingElement,
                        contentKey: val === "none" ? undefined : val
                      })}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="Link to content field" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="none">No link (use fixed text)</SelectItem>
                        <SelectItem value="targetWord">Target Word</SelectItem>
                        <SelectItem value="nativeWord">Native Word</SelectItem>
                        <SelectItem value="targetPhrase1">Target Phrase 1</SelectItem>
                        <SelectItem value="nativePhrase1">Native Phrase 1</SelectItem>
                        <SelectItem value="targetPhrase2">Target Phrase 2</SelectItem>
                        <SelectItem value="nativePhrase2">Native Phrase 2</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </>
              )}
              
              {editingElement.type === "block" && (
                <>
                  <div className="grid grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <Label>Width (px)</Label>
                      <Input 
                        type="number" 
                        value={editingElement.style?.width || 100} 
                        onChange={(e) => setEditingElement({
                          ...editingElement, 
                          style: {...editingElement.style, width: parseInt(e.target.value)}
                        })}
                      />
                    </div>
                    
                    <div className="space-y-2">
                      <Label>Height (px)</Label>
                      <Input 
                        type="number" 
                        value={editingElement.style?.height || 100} 
                        onChange={(e) => setEditingElement({
                          ...editingElement, 
                          style: {...editingElement.style, height: parseInt(e.target.value)}
                        })}
                      />
                    </div>
                  </div>
                  
                  <div className="space-y-2">
                    <Label>Border Radius (px)</Label>
                    <Input 
                      type="number" 
                      value={parseInt(editingElement.style?.borderRadius) || 0} 
                      onChange={(e) => setEditingElement({
                        ...editingElement, 
                        style: {...editingElement.style, borderRadius: `${e.target.value}px`}
                      })}
                    />
                  </div>
                  
                  <div className="space-y-2">
                    <Label>Background</Label>
                    <Select 
                      value={editingElement.style?.background || "gradient1"} 
                      onValueChange={(val) => {
                        let bgValue = val;
                        if (val === "gradient1") {
                          bgValue = "linear-gradient(45deg, #3490dc, #6574cd)";
                        } else if (val === "gradient2") {
                          bgValue = "linear-gradient(45deg, #38c172, #4dc0b5)";
                        } else if (val === "gradient3") {
                          bgValue = "linear-gradient(45deg, #e3342f, #f6993f)";
                        } else if (val === "solid1") {
                          bgValue = "#3490dc";
                        } else if (val === "solid2") {
                          bgValue = "#38c172";
                        } else if (val === "solid3") {
                          bgValue = "#e3342f";
                        }
                        
                        setEditingElement({
                          ...editingElement,
                          style: {...editingElement.style, background: bgValue}
                        });
                      }}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="Choose background" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="gradient1">Blue Gradient</SelectItem>
                        <SelectItem value="gradient2">Green Gradient</SelectItem>
                        <SelectItem value="gradient3">Red Gradient</SelectItem>
                        <SelectItem value="solid1">Solid Blue</SelectItem>
                        <SelectItem value="solid2">Solid Green</SelectItem>
                        <SelectItem value="solid3">Solid Red</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </>
              )}
              
              {editingElement.type === "audio" && (
                <div className="space-y-2">
                  <Label>Audio Source</Label>
                  <div className="flex space-x-2">
                    <Input 
                      value={editingElement.content} 
                      onChange={(e) => setEditingElement({...editingElement, content: e.target.value})}
                    />
                    <Button variant="outline" size="icon">
                      <UploadCloud className="h-4 w-4" />
                    </Button>
                  </div>
                </div>
              )}
              
              {editingElement.type !== "audio" && (
                <div className="space-y-2">
                  <Label>Position</Label>
                  <div className="grid grid-cols-2 gap-4">
                    <div className="flex items-center space-x-2">
                      <Label className="w-8">X %</Label>
                      <Input 
                        type="number" 
                        min="0" 
                        max="100" 
                        value={editingElement.position?.x || 50} 
                        onChange={(e) => setEditingElement({
                          ...editingElement, 
                          position: {...editingElement.position, x: parseFloat(e.target.value)}
                        })}
                      />
                    </div>
                    <div className="flex items-center space-x-2">
                      <Label className="w-8">Y %</Label>
                      <Input 
                        type="number" 
                        min="0" 
                        max="100" 
                        value={editingElement.position?.y || 50} 
                        onChange={(e) => setEditingElement({
                          ...editingElement, 
                          position: {...editingElement.position, y: parseFloat(e.target.value)}
                        })}
                      />
                    </div>
                  </div>
                </div>
              )}
              
              {editingElement.type !== "audio" && (
                <div className="space-y-2">
                  <Label>Animation</Label>
                  <Select 
                    value={editingElement.animation || "fadeIn"} 
                    onValueChange={(val) => setEditingElement({
                      ...editingElement,
                      animation: val
                    })}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="Choose animation" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="fadeIn">Fade In</SelectItem>
                      <SelectItem value="slideIn">Slide In</SelectItem>
                      <SelectItem value="zoomIn">Zoom In</SelectItem>
                      <SelectItem value="bounceIn">Bounce In</SelectItem>
                      <SelectItem value="flipIn">Flip In</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              )}
              
              <div className="flex items-center mt-4 space-x-2">
                <Label htmlFor="element-sync" className="text-sm">
                  Sync with audio
                </Label>
                <Switch 
                  id="element-sync" 
                  checked={true}
                />
              </div>
            </div>
          )}
          
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowEditor(false)}>Cancel</Button>
            <Button onClick={() => updateElement(editingElement)}>Save Changes</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
      
      {/* Notification Toast */}
      <div className={`fixed bottom-4 right-4 bg-slate-800 text-white px-4 py-2 rounded-md shadow-lg transition-opacity duration-300 flex items-center ${showNotification ? 'opacity-100' : 'opacity-0'}`}>
        <Check className="h-4 w-4 mr-2 text-green-400" />
        {notificationMessage}
      </div>
    </div>
  );
};

export default VideoGeneratorApp;
