import LiteYouTubeEmbed from 'react-lite-youtube-embed';
import 'react-lite-youtube-embed/dist/LiteYouTubeEmbed.css';

interface YoutubeVideoProps {
  id: string | null | undefined;
  title?: string;
  backgroundSize?: 'contain' | 'cover';
  onPlayStart?: () => void;
  poster?: 'default' | 'mqdefault' | 'hqdefault' | 'sddefault' | 'maxresdefault';
}

const YouTubeVideo: React.FC<YoutubeVideoProps> = ({
  id,
  title,
  backgroundSize = 'contain',
  onPlayStart,
  poster = 'hqdefault',
}) => {
  if (!id) return null;

  const extractVideoId = (input: string) => {
    if (!input) return null;

    // If it's already just the video ID (11 characters)
    if (typeof input === 'string' && input.length === 11 && !/[\/=&?]/.test(input)) {
      return input;
    }

    // Handle array format (your current case)
    if (Array.isArray(input) && input[1]) {
      return extractVideoId(input[1]);
    }

    // Handle full YouTube URLs
    const url = typeof input === 'string' ? input : String(input);

    // Match various YouTube URL formats
    const patterns = [
      /(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/)([a-zA-Z0-9_-]{11})/,
      /youtube\.com\/watch\?.*v=([a-zA-Z0-9_-]{11})/,
      /youtu\.be\/([a-zA-Z0-9_-]{11})/,
    ];

    for (const pattern of patterns) {
      const match = url.match(pattern);
      if (match && match[1]) {
        return match[1];
      }
    }

    return null;
  };

  const videoId = extractVideoId(id);

  if (!videoId) {
    console.error('Invalid YouTube video ID:', id);
    return null;
  }

  return (
    <LiteYouTubeEmbed
      wrapperClass="w-full h-full yt-lite relative flex items-center justify-center"
      playerClass="youtube-play-button"
      id={videoId}
      title={title || 'YouTube video'}
      onIframeAdded={onPlayStart}
      style={{
        backgroundSize: backgroundSize,
        backgroundRepeat: 'no-repeat',
      }}
      poster={poster}
    />
  );
};

export default YouTubeVideo;
