import { useRef, useEffect, useState } from 'react';
import { AlertCircle } from 'lucide-react';

interface VideoPlayerProps {
  videoUrl: string | null;
  isPlaying: boolean;
  playbackSpeed: number;
  currentWord: string;
  onVideoEnd: () => void;
  onPlayPause: () => void;
}

export function VideoPlayer({
  videoUrl,
  isPlaying,
  playbackSpeed,
  currentWord,
  onVideoEnd,
  onPlayPause,
}: VideoPlayerProps) {
  const videoRef = useRef<HTMLVideoElement>(null);
  const [hasError, setHasError] = useState(false);
  const [isLoading, setIsLoading] = useState(true);

  // Handle play/pause state changes
  useEffect(() => {
    if (!videoRef.current || !videoUrl) return;

    if (isPlaying) {
      videoRef.current.play().catch(err => {
        console.error('Error playing video:', err);
        setHasError(true);
      });
    } else {
      videoRef.current.pause();
    }
  }, [isPlaying, videoUrl]);

  // Handle playback speed changes
  useEffect(() => {
    if (videoRef.current) {
      videoRef.current.playbackRate = playbackSpeed;
    }
  }, [playbackSpeed]);

  // Reset error state when video URL changes
  useEffect(() => {
    setHasError(false);
    setIsLoading(true);
  }, [videoUrl]);

  const handleVideoError = () => {
    console.error('Video load error for:', videoUrl);
    setHasError(true);
    setIsLoading(false);
    // Auto-advance to next video after a short delay
    setTimeout(() => {
      onVideoEnd();
    }, 1500);
  };

  const handleLoadedData = () => {
    setIsLoading(false);
  };

  // No video available for this word
  if (!videoUrl) {
    return (
      <div className="bg-gray-900 rounded-lg aspect-video flex flex-col items-center justify-center text-white p-8">
        <AlertCircle className="h-16 w-16 text-gray-400 mb-4" />
        <h3 className="text-2xl font-bold mb-2">{currentWord}</h3>
        <p className="text-gray-400 text-center">Video nije dostupan za ovu riječ</p>
        <p className="text-sm text-gray-500 mt-2">Automatski prelazak na sljedeću riječ...</p>
      </div>
    );
  }

  // Video error state
  if (hasError) {
    return (
      <div className="bg-gray-900 rounded-lg aspect-video flex flex-col items-center justify-center text-white p-8">
        <AlertCircle className="h-16 w-16 text-red-400 mb-4" />
        <h3 className="text-2xl font-bold mb-2">{currentWord}</h3>
        <p className="text-gray-400 text-center">Greška pri učitavanju videa</p>
        <p className="text-sm text-gray-500 mt-2">Automatski prelazak na sljedeću riječ...</p>
      </div>
    );
  }

  return (
    <div className="bg-gray-900 rounded-lg overflow-hidden">
      <div className="relative aspect-video">
        {isLoading && (
          <div className="absolute inset-0 flex items-center justify-center bg-gray-900">
            <div className="h-12 w-12 animate-spin rounded-full border-4 border-orange-500 border-t-transparent"></div>
          </div>
        )}
        <video
          ref={videoRef}
          src={videoUrl}
          className="w-full h-full object-contain bg-black"
          onEnded={onVideoEnd}
          onError={handleVideoError}
          onLoadedData={handleLoadedData}
          onClick={onPlayPause}
          playsInline
        />
      </div>
      
      {/* Current word display */}
      <div className="bg-gray-800 px-6 py-4">
        <p className="text-sm text-gray-400 mb-1">Trenutno:</p>
        <h3 className="text-2xl font-bold text-white">{currentWord}</h3>
      </div>
    </div>
  );
}

