import React from 'react';

import type { YouTubeEmbedBlock as YouTubeEmbedBlockProps } from '@/payload-types';
import { cn } from '@/utilities/ui';

type Props = YouTubeEmbedBlockProps & {
  className?: string;
  enableGutter?: boolean;
};

// Convert YouTube URLs to embed format
function getYouTubeEmbedUrl(url: string): string | null {
  if (!url) return null;

  try {
    const urlObj = new URL(url);
    let videoId: string | null = null;

    // Handle youtube.com/watch?v=... format
    if (urlObj.hostname.includes('youtube.com') && urlObj.pathname === '/watch') {
      videoId = urlObj.searchParams.get('v');
    }
    // Handle youtu.be/... format
    else if (urlObj.hostname === 'youtu.be') {
      videoId = urlObj.pathname.slice(1);
    }
    // Handle youtube.com/shorts/... format
    else if (urlObj.hostname.includes('youtube.com') && urlObj.pathname.startsWith('/shorts/')) {
      videoId = urlObj.pathname.split('/')[2];
    }
    // Handle youtube.com/embed/... format (already embedded)
    else if (urlObj.hostname.includes('youtube.com') && urlObj.pathname.startsWith('/embed/')) {
      videoId = urlObj.pathname.split('/')[2];
    }

    if (!videoId) return null;

    return `https://www.youtube.com/embed/${videoId}`;
  } catch (error) {
    console.error('Invalid YouTube URL:', error);
    return null;
  }
}

export const YouTubeEmbedBlock: React.FC<Props> = (props) => {
  const { url, className, enableGutter = true } = props;

  const embedUrl = getYouTubeEmbedUrl(url);

  if (!embedUrl) {
    return (
      <div
        className={cn(
          'my-8',
          {
            container: enableGutter,
          },
          className
        )}
      >
        <p className='text-red-500'>Invalid YouTube URL</p>
      </div>
    );
  }

  return (
    <div
      className={cn(
        'my-8',
        {
          container: enableGutter,
        },
        className
      )}
    >
      <div
        className='relative w-full overflow-hidden rounded-[0.8rem] border border-border'
        style={{ paddingBottom: '56.25%' }}
      >
        <iframe
          src={embedUrl}
          className='absolute left-0 top-0 h-full w-full'
          frameBorder='0'
          allow='accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share'
          allowFullScreen
          title='YouTube video'
        />
      </div>
    </div>
  );
};
