import { useState, useEffect } from 'react';
import { Layout } from '../components/layout/Layout';
import { VideoPlayer } from '../components/video-sentence/VideoPlayer';
import { SentencePanel } from '../components/video-sentence/SentencePanel';
import { PlaybackControls } from '../components/video-sentence/PlaybackControls';
import { useSentenceStore } from '../stores/sentenceStore';
import { buildPlaylist, getVideoUrl } from '../lib/videoPlaylist';
import { toast } from 'sonner';

function VideoSentence() {
  const { currentTokens } = useSentenceStore();
  const [currentTokenIndex, setCurrentTokenIndex] = useState(0);
  const [isPlaying, setIsPlaying] = useState(false);
  const [playbackSpeed, setPlaybackSpeed] = useState(1.0);
  const [loopMode, setLoopMode] = useState<'none' | 'sentence' | 'word'>('none');

  const playlist = buildPlaylist(currentTokens);
  const currentItem = playlist[currentTokenIndex];
  const videoUrl = currentItem ? getVideoUrl(currentItem.videoUrl) : null;

  // Preload next video for smooth transitions
  const nextItem = currentTokenIndex < playlist.length - 1 ? playlist[currentTokenIndex + 1] : null;
  const nextVideoUrl = nextItem ? getVideoUrl(nextItem.videoUrl) : null;

  // Reset to first token when tokens change and auto-start playback
  useEffect(() => {
    if (currentTokens.length > 0) {
      setCurrentTokenIndex(0);
      setIsPlaying(true); // Auto-start playback
    }
  }, [currentTokens]);

  // Auto-start playback on page load if tokens exist
  useEffect(() => {
    if (currentTokens.length > 0 && currentTokenIndex === 0) {
      setIsPlaying(true);
    }
  }, []); // Run only once on mount

  // Auto-advance to next video when no video is available
  useEffect(() => {
    if (currentItem && !currentItem.videoUrl && currentTokens.length > 0) {
      const timer = setTimeout(() => {
        handleVideoEnd();
      }, 2000);
      return () => clearTimeout(timer);
    }
  }, [currentTokenIndex, currentItem]);

  const handleVideoEnd = () => {
    if (loopMode === 'word') {
      // Replay current video - the video player will handle this
      return;
    }

    if (currentTokenIndex < playlist.length - 1) {
      // Advance to next token
      setCurrentTokenIndex(prev => prev + 1);
    } else {
      // End of sentence
      if (loopMode === 'sentence') {
        // Restart from beginning
        setCurrentTokenIndex(0);
      } else {
        // Stop playback
        setIsPlaying(false);
        toast.success('Reprodukcija završena');
      }
    }
  };

  const handleNext = () => {
    if (currentTokenIndex < playlist.length - 1) {
      setCurrentTokenIndex(prev => prev + 1);
    }
  };

  const handlePrevious = () => {
    if (currentTokenIndex > 0) {
      setCurrentTokenIndex(prev => prev - 1);
    }
  };

  const handleTokenClick = (index: number) => {
    setCurrentTokenIndex(index);
    setIsPlaying(true);
  };

  const handlePlayPause = () => {
    setIsPlaying(!isPlaying);
  };

  return (
    <Layout>
      <div className="space-y-6">
        <div>
          <h1 className="text-3xl font-bold text-gray-900 mb-2">Video Rečenica</h1>
          <p className="text-gray-600">
            Pogledajte sekvencijalnu reprodukciju znakovnog jezika za cijelu rečenicu
          </p>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-5 gap-6">
          {/* Video Player - 60% (3/5 columns) */}
          <div className="lg:col-span-3">
            <VideoPlayer
              videoUrl={videoUrl}
              isPlaying={isPlaying}
              playbackSpeed={playbackSpeed}
              currentWord={currentItem?.displayText || ''}
              onVideoEnd={handleVideoEnd}
              onPlayPause={handlePlayPause}
            />
            
            <PlaybackControls
              isPlaying={isPlaying}
              playbackSpeed={playbackSpeed}
              loopMode={loopMode}
              onPlayPause={handlePlayPause}
              onNext={handleNext}
              onPrevious={handlePrevious}
              onSpeedChange={setPlaybackSpeed}
              onLoopModeChange={setLoopMode}
              canGoNext={currentTokenIndex < playlist.length - 1}
              canGoPrevious={currentTokenIndex > 0}
            />
          </div>

          {/* Sentence Panel - 40% (2/5 columns) */}
          <div className="lg:col-span-2">
            <SentencePanel
              tokens={currentTokens}
              currentTokenIndex={currentTokenIndex}
              onTokenClick={handleTokenClick}
            />
          </div>
        </div>

        {/* Hidden video element for preloading next video */}
        {nextVideoUrl && (
          <video
            src={nextVideoUrl}
            preload="auto"
            style={{ display: 'none' }}
            aria-hidden="true"
          />
        )}
      </div>
    </Layout>
  );
}

export default VideoSentence;

