import { useState } from 'react';
import { cn } from '@/lib/utils';
import { extractYouTubeVideoId, generateYouTubeEmbedUrl } from '@/lib/video-utils';

interface YouTubeEmbedProps {
  /** YouTube video URL or video ID */
  url: string;
  /** Video title for accessibility */
  title?: string;
  /** Optional caption below the video */
  caption?: string;
  /** Additional CSS classes */
  className?: string;
  /** Autoplay the video (muted on mobile) */
  autoplay?: boolean;
  /** Show video controls */
  controls?: boolean;
  /** Reduce YouTube branding */
  modestbranding?: boolean;
  /** Show related videos at the end */
  showRelated?: boolean;
  /** Start time in seconds */
  startTime?: number;
  /** End time in seconds */
  endTime?: number;
  /** Show loading state */
  showLoading?: boolean;
}

export function YouTubeEmbed({
  url,
  title = 'YouTube video',
  caption,
  className,
  autoplay = false,
  controls = true,
  modestbranding = true,
  showRelated = false,
  startTime,
  endTime,
  showLoading = true,
}: YouTubeEmbedProps) {
  const [isLoaded, setIsLoaded] = useState(false);
  const [hasError, setHasError] = useState(false);
  
  // Extract video ID from URL
  const videoId = extractYouTubeVideoId(url);
  
  if (!videoId) {
    return (
      <div className={cn('p-4 bg-destructive/10 border border-destructive/20 rounded-lg', className)}>
        <p className="text-destructive text-sm">
          Invalid YouTube URL: {url}
        </p>
      </div>
    );
  }
  
  // Generate embed URL with options
  const embedUrl = generateYouTubeEmbedUrl(videoId, {
    autoplay,
    controls,
    modestbranding,
    rel: showRelated,
    playsinline: true,
    start: startTime,
    end: endTime,
  });
  
  return (
    <div className={cn('w-full', className)}>
      {/* Video container with aspect ratio */}
      <div className="relative pt-[56.25%] bg-muted rounded-lg overflow-hidden">
        {/* Loading state */}
        {showLoading && !isLoaded && !hasError && (
          <div className="absolute inset-0 flex items-center justify-center">
            <div className="w-12 h-12 border-4 border-primary/30 border-t-primary rounded-full animate-spin" />
          </div>
        )}
        
        {/* Error state */}
        {hasError && (
          <div className="absolute inset-0 flex flex-col items-center justify-center p-4 text-center">
            <div className="text-destructive mb-2">
              <svg
                className="w-12 h-12 mx-auto"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
                xmlns="http://www.w3.org/2000/svg"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
                />
              </svg>
            </div>
            <p className="text-destructive font-medium">Video failed to load</p>
            <p className="text-muted-foreground text-sm mt-1">
              The YouTube video could not be loaded. Please check the URL or try again later.
            </p>
          </div>
        )}
        
        {/* YouTube iframe */}
        {!hasError && (
          <iframe
            className={cn(
              'absolute top-0 left-0 w-full h-full border-0 rounded-lg',
              !isLoaded && 'opacity-0'
            )}
            src={embedUrl}
            title={title}
            allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
            allowFullScreen
            loading="lazy"
            referrerPolicy="strict-origin-when-cross-origin"
            onLoad={() => setIsLoaded(true)}
            onError={() => setHasError(true)}
          />
        )}
      </div>
      
      {/* Caption */}
      {caption && (
        <div className="mt-2 text-sm text-muted-foreground text-center">
          {caption}
        </div>
      )}
    </div>
  );
}